From 14cc183c89ef10c3e44ff8e260849bdd79766491 Mon Sep 17 00:00:00 2001 From: colevandersWands <18554853+colevandersWands@users.noreply.github.com> Date: Thu, 29 Jun 2023 07:31:03 +0200 Subject: [PATCH] search field --- index.html | 6 +++++- public/script.js | 41 ++++++++++++++++++++++++++--------------- public/styles.css | 2 +- 3 files changed, 32 insertions(+), 17 deletions(-) diff --git a/index.html b/index.html index 40d6018..3f673c3 100644 --- a/index.html +++ b/index.html @@ -48,7 +48,11 @@

Snippetry

-
+
+ +
+ +

diff --git a/public/script.js b/public/script.js index 68ffb1f..8e113a9 100644 --- a/public/script.js +++ b/public/script.js @@ -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', })); @@ -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 @@ -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(); }); diff --git a/public/styles.css b/public/styles.css index 6cfad91..bccef8c 100644 --- a/public/styles.css +++ b/public/styles.css @@ -20,7 +20,7 @@ button { margin-top: 3em; } -#tags { +.center { text-align: center; }