Skip to content

Commit

Permalink
search field
Browse files Browse the repository at this point in the history
  • Loading branch information
colevandersWands committed Jun 29, 2023
1 parent 9c1906f commit 14cc183
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 17 deletions.
6 changes: 5 additions & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,11 @@

<h1>Snippetry</h1>

<div id="tags"></div>
<div class="center">
<input id="search-field" type="text" placeholder="ctr-f" />
</div>

<div id="tags" class="center"></div>

<hr />
</div>
Expand Down
41 changes: 26 additions & 15 deletions public/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const state = await fetch('./public/snippets.json')
.then((res) => res.json())
.then((preState) => ({
...preState,
query: '',
tags: preState.tags.map((tag) => ({ value: tag, selected: false })),
repo: 'https://github.com/colevandersWands/snippetry',
}));
Expand Down Expand Up @@ -157,6 +158,24 @@ const renderSnippet = (snippet) => {
snippet.root.appendChild(snippet.container);
};

const filterSnippets = () => {
const ignoreTags = state.tags.every((tag) => !tag.selected);

for (const snippet of state.snippets) {
const tagsAreSelected =
ignoreTags ||
state.tags.find(
(tag) => tag.selected && snippet.tags.includes(tag.value),
);

if (tagsAreSelected && snippet.code.toLowerCase().includes(state.query)) {
snippet.visible(true);
} else {
snippet.visible(false);
}
}
};

// ----- initialize UI -----

document
Expand Down Expand Up @@ -191,22 +210,14 @@ for (const snippet of state.snippets) {
document.getElementById('tags').addEventListener('change', (e) => {
const [key, value] = e.target.id.split(SEPARATOR);

const entry = state[key].find((entry) => entry.value === value);
entry.selected = e.target.checked;
const tag = state[key].find((entry) => entry.value === value);
tag.selected = e.target.checked;

const ignoreTags = state.tags.every((tag) => !tag.selected);
filterSnippets();
});

for (const snippet of state.snippets) {
const tagsAreSelected =
ignoreTags ||
state.tags.find(
(tag) => tag.selected && snippet.tags.includes(tag.value),
);
document.getElementById('search-field').addEventListener('input', (e) => {
state.query = e.target.value;

if (tagsAreSelected) {
snippet.visible(true);
} else {
snippet.visible(false);
}
}
filterSnippets();
});
2 changes: 1 addition & 1 deletion public/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ button {
margin-top: 3em;
}

#tags {
.center {
text-align: center;
}

Expand Down

0 comments on commit 14cc183

Please sign in to comment.