Skip to content

Commit

Permalink
Fixed prettier complaints
Browse files Browse the repository at this point in the history
Signed-off-by: George Araújo <george.gcac@gmail.com>
  • Loading branch information
george-gca committed Jan 10, 2025
1 parent d0f6860 commit 51d1879
Show file tree
Hide file tree
Showing 5 changed files with 127 additions and 135 deletions.
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ permalink: / # link no qual a página vai ser acessada
O layout base é um arquivo que contém o html básico de todas as páginas, e é onde são incluídos os arquivos de css e js necessários para o site. A extensão `.liquid` é uma extensão padrão usada pelo Jekyll. No layout básico é possível encontrar algumas expressões como:

```liquid
<meta name="description" content="{{ page.site_description }}" />
<meta name="description" content="{{ page.site_description }}">
{% include script.liquid.js %}
```

Expand Down
119 changes: 50 additions & 69 deletions _includes/script.js.liquid
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
<script type="module">
import { levenshtein } from "/assets/js/levenshtein.js";
import { levenshtein } from '/assets/js/levenshtein.js';
const exactWordScore = 12;
const partialWordScore = 10;
const levenshteinScore = 10;
const levenshteinThreshold = 3;
const searchInput = document.querySelector("#search-input");
const cardsSection = document.querySelector("#cards");
const filterSelect = document.querySelector("#tags-filter");
const searchInput = document.querySelector('#search-input');
const cardsSection = document.querySelector('#cards');
const filterSelect = document.querySelector('#tags-filter');
let listOfCardsFiltered = [];
let favoriteCards = [];
function insertTagsIntoSelect(tags) {
tags.sort();
for (const tag of tags) {
const newOption = document.createElement("option");
const newOption = document.createElement('option');
newOption.value = tag;
newOption.text = tag;
filterSelect.appendChild(newOption);
}
}
function getTagsFromCards(data) {
const tags = ["{{ page.favorites }}"];
const tags = ['{{ page.favorites }}'];
data.map((objeto) => {
if (objeto.tags) {
objeto.tags.map((tag) => {
Expand All @@ -40,16 +40,13 @@
function filterCards() {
listOfCardsFiltered = [];
const listOfCards = document.querySelectorAll(".card");
const listOfCards = document.querySelectorAll('.card');
listOfCards.forEach((element) => {
if (
element.getAttribute("tags").includes(filterSelect.value) ||
filterSelect.value == "{{ page.all }}"
) {
element.style.display = "";
if (element.getAttribute('tags').includes(filterSelect.value) || filterSelect.value == '{{ page.all }}') {
element.style.display = '';
listOfCardsFiltered.push(element);
} else {
element.style.display = "none";
element.style.display = 'none';
}
});
searchCards();
Expand All @@ -58,21 +55,19 @@
function sortCards(sortingArray) {
if (listOfCardsFiltered.length > 0) {
if (!Array.isArray(sortingArray) || !sortingArray.length) {
const cards = document.querySelector("#cards");
const cards = document.querySelector('#cards');
// selects all cards that are not hidden and sorts them by title
// every child is re-appended to cards in the order of the now sorted array. When an element is re-appended it is actually moved from its previous location
[...cards.querySelectorAll(".card:not([style*='display: none;'])")]
.sort((a, b) =>
a
.querySelector(".card__title")
.querySelector('.card__title')
.textContent.toLowerCase()
.localeCompare(
b.querySelector(".card__title").textContent.toLowerCase(),
),
.localeCompare(b.querySelector('.card__title').textContent.toLowerCase()),
)
.forEach((node) => cards.appendChild(node));
} else {
const cards = document.querySelector("#cards");
const cards = document.querySelector('#cards');
// selects all cards that are not hidden and sorts them by the order of the sortingArray
// every child is re-appended to cards in the order of the now sorted array. When an element is re-appended it is actually moved from its previous location
[...cards.querySelectorAll(".card:not([style*='display: none;'])")]
Expand All @@ -94,9 +89,7 @@
// search for words inside the title that either contains the search words or have a low levenshtein distance
// only consider the best case for each search word
const cardTitle = card
.querySelector(".card__title")
.textContent.toLowerCase();
const cardTitle = card.querySelector('.card__title').textContent.toLowerCase();
const titleWords = cardTitle.split(/\s+/);
let titleScore = 0;
Expand All @@ -115,10 +108,7 @@
const levenshteinDistance = levenshtein(searchWord, word);
// only the word with the lowest levenshtein distance will be considered
if (
levenshteinDistance <= levenshteinThreshold &&
levenshteinScore - levenshteinDistance > wordScore
) {
if (levenshteinDistance <= levenshteinThreshold && levenshteinScore - levenshteinDistance > wordScore) {
wordScore = levenshteinScore - levenshteinDistance;
}
}
Expand All @@ -133,9 +123,7 @@
// search for words inside the description that either contains the search words or have a low levenshtein distance
// only consider the best case for each search word
const cardDescription = card
.querySelector(".card__description")
.textContent.toLowerCase();
const cardDescription = card.querySelector('.card__description').textContent.toLowerCase();
const descriptionWords = cardDescription.split(/\s+/);
let descriptionScore = 0;
Expand All @@ -154,10 +142,7 @@
const levenshteinDistance = levenshtein(searchWord, word);
// only the word with the lowest levenshtein distance will be considered
if (
levenshteinDistance <= levenshteinThreshold &&
levenshteinScore - levenshteinDistance > wordScore
) {
if (levenshteinDistance <= levenshteinThreshold && levenshteinScore - levenshteinDistance > wordScore) {
wordScore = levenshteinScore - levenshteinDistance;
}
}
Expand All @@ -170,34 +155,34 @@
cardScore += descriptionScore;
if (cardScore > 0) {
card.style.display = "";
card.style.display = '';
cardsScores.push([card, cardScore]);
} else {
card.style.display = "none";
card.style.display = 'none';
}
}
const msgNotFound = document.querySelector("div.msg");
const msgNotFound = document.querySelector('div.msg');
if (cardsScores.length > 0) {
msgNotFound.style.display = "none";
msgNotFound.style.display = 'none';
// sort the array of cards by score
cardsScores.sort((a, b) => b[1] - a[1]);
// remove the scores from the array
cardsScores = cardsScores.map((card) => card[0]);
sortCards(cardsScores);
} else {
msgNotFound.style.display = "";
msgNotFound.style.display = '';
}
} else {
// display all cards if search input is empty
for (const card of listOfCardsFiltered) {
card.style.display = "";
card.style.display = '';
cardsScores.push(card);
}
const msgNotFound = document.querySelector("div.msg");
msgNotFound.style.display = "none";
const msgNotFound = document.querySelector('div.msg');
msgNotFound.style.display = 'none';
sortCards();
}
}
Expand All @@ -215,19 +200,15 @@
data.forEach((card) => {
const cardId = generateCardId(card.id, card.title, card.description);
cards += `
<section class="card" tags="${
card.tags ? card.tags : "{{ page.all }}"
}" id="${cardId}">
<section class="card" tags="${card.tags ? card.tags : '{{ page.all }}'}" id="${cardId}">
<div class="card__header">
<h3 class="card__title">${card.title}</h3>
<i
alt="star"
unique-title="${cardId}"
id="fav_${cardId}"
class="${
card.tags.includes("{{ page.favorites }}")
? "ph-fill ph-star"
: "ph ph-star"
card.tags.includes('{{ page.favorites }}') ? 'ph-fill ph-star' : 'ph ph-star'
} fav__button">
</i>
</div>
Expand All @@ -240,14 +221,14 @@
</div>
`;
}
cards += "</section>";
cards += '</section>';
});
cardsSection.innerHTML = cards;
const favButtons = document.querySelectorAll(".fav__button");
const favButtons = document.querySelectorAll('.fav__button');
favButtons.forEach((button) => {
button.addEventListener("click", () => {
setCardAsFavorite(button.getAttribute("unique-title"));
button.addEventListener('click', () => {
setCardAsFavorite(button.getAttribute('unique-title'));
});
});
Expand All @@ -256,37 +237,37 @@
function addFavoriteTagToCard(cardId) {
const card = document.getElementById(cardId);
const tags = card.getAttribute("tags").split(",");
const tags = card.getAttribute('tags').split(',');
if (tags.includes("{{ page.favorites }}")) {
tags.splice(tags.indexOf("{{ page.favorites }}"), 1);
if (tags.includes('{{ page.favorites }}')) {
tags.splice(tags.indexOf('{{ page.favorites }}'), 1);
} else {
tags.push("{{ page.favorites }}");
tags.push('{{ page.favorites }}');
}
card.setAttribute("tags", tags);
card.setAttribute('tags', tags);
}
function setCardAsFavorite(cardId) {
const favIcon = document.querySelector(`#fav_${cardId}`);
if (favoriteCards.includes(cardId)) {
favIcon.className = "ph ph-star fav__button";
favIcon.className = 'ph ph-star fav__button';
favoriteCards.splice(favoriteCards.indexOf(cardId), 1);
} else {
favIcon.className = "ph-fill ph-star fav__button";
favIcon.className = 'ph-fill ph-star fav__button';
favoriteCards.push(cardId);
}
addFavoriteTagToCard(cardId);
localStorage.setItem("favoriteCards", favoriteCards);
localStorage.setItem('favoriteCards', favoriteCards);
}
async function loadFavoriteCardsId() {
const cardsId = localStorage.getItem("favoriteCards");
const cardsId = localStorage.getItem('favoriteCards');
if (cardsId) {
favoriteCards = cardsId.split(",");
favoriteCards = cardsId.split(',');
}
}
Expand All @@ -297,7 +278,7 @@
if (!card.tags) {
card.tags = [];
}
card.tags.push("{{ page.favorites }}");
card.tags.push('{{ page.favorites }}');
}
});
return cards;
Expand All @@ -309,21 +290,21 @@
async function getCardsFromJson() {
try {
const res = await fetch("assets/data/cards.json");
const res = await fetch('assets/data/cards.json');
const data = await res.json();
const sortedCards = await sortCardsByTitle(data);
document.getElementById("total-terms").textContent = sortedCards.length;
document.getElementById('total-terms').textContent = sortedCards.length;
await loadFavoriteCardsId();
await addFavoriteTag(sortedCards);
getTagsFromCards(sortedCards);
insertCardsIntoHtml(sortedCards);
} catch (error) {
console.error("An error occurred while fetching card data.", error);
console.error('An error occurred while fetching card data.', error);
}
}
searchInput.addEventListener("input", searchCards);
filterSelect.addEventListener("change", filterCards);
searchInput.addEventListener('input', searchCards);
filterSelect.addEventListener('change', filterCards);
getCardsFromJson();
/**
Expand All @@ -347,8 +328,8 @@
* @param {number} hash - The initial hash value.
* @returns {string} The hashed representation of the content.
*/
function generateContentId(title = "", description = "", hash = 5381) {
const data = (title + description).slice(0, 32).split(" ").join("");
function generateContentId(title = '', description = '', hash = 5381) {
const data = (title + description).slice(0, 32).split(' ').join('');
for (let i = 0; i < data.length; i++) {
hash = (hash << 5) + hash + data.charCodeAt(i);
Expand Down
35 changes: 16 additions & 19 deletions _json/en-us/cards.json.liquid
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,21 @@
id: cards
permalink: /assets/data/cards.json
---
{
"cards": [
{%- for letter in site.data[site.active_lang] -%}
{%- for card in letter[1] -%}
{
"title": "{{ card.title | escape }}",
"tags": [
{%- for tag in card.tags -%}
"{{ tag }}"{%- unless forloop.last -%},{%- endunless -%}
{%- endfor -%}
],
"description": "{{ card.description | escape }}"
{%- if card.content -%}
,"content": { "code": "{{ card.content.code | escape }}" }
{%- endif -%}
}{%- unless forloop.last -%},{%- endunless -%}
{%- endfor -%}
{ "cards": [
{%- for letter in site.data[site.active_lang] -%}
{%- for card in letter[1] -%}
{ "title": "{{ card.title | escape }}", "tags": [
{%- for tag in card.tags -%}
"{{ tag }}"
{%- unless forloop.last -%},{%- endunless -%}
{%- endfor -%}
]
}
], "description": "{{ card.description | escape }}"
{%- if card.content -%}
,"content": { "code": "{{ card.content.code | escape }}" }
{%- endif -%}
}
{%- unless forloop.last -%},{%- endunless -%}
{%- endfor -%}
{%- unless forloop.last -%},{%- endunless -%}
{%- endfor -%}
] }
35 changes: 16 additions & 19 deletions _json/pt-br/cards.json.liquid
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,21 @@
id: cards
permalink: /assets/data/cards.json
---
{
"cards": [
{%- for letter in site.data[site.active_lang] -%}
{%- for card in letter[1] -%}
{
"title": "{{ card.title | escape }}",
"tags": [
{%- for tag in card.tags -%}
"{{ tag }}"{%- unless forloop.last -%},{%- endunless -%}
{%- endfor -%}
],
"description": "{{ card.description | escape }}"
{%- if card.content -%}
,"content": { "code": "{{ card.content.code | escape }}" }
{%- endif -%}
}{%- unless forloop.last -%},{%- endunless -%}
{%- endfor -%}
{ "cards": [
{%- for letter in site.data[site.active_lang] -%}
{%- for card in letter[1] -%}
{ "title": "{{ card.title | escape }}", "tags": [
{%- for tag in card.tags -%}
"{{ tag }}"
{%- unless forloop.last -%},{%- endunless -%}
{%- endfor -%}
]
}
], "description": "{{ card.description | escape }}"
{%- if card.content -%}
,"content": { "code": "{{ card.content.code | escape }}" }
{%- endif -%}
}
{%- unless forloop.last -%},{%- endunless -%}
{%- endfor -%}
{%- unless forloop.last -%},{%- endunless -%}
{%- endfor -%}
] }
Loading

0 comments on commit 51d1879

Please sign in to comment.