Skip to content

Commit

Permalink
7476 - update search fields/ranking
Browse files Browse the repository at this point in the history
fixes

Fix tests

fixes

Added changes to pushstate

fix
  • Loading branch information
fessehaye committed Oct 21, 2021
1 parent 145ad47 commit e1fea73
Show file tree
Hide file tree
Showing 7 changed files with 124 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
{% else %}{% blocktrans context "“*privacy not included” can be localized. This is a reference to the “*batteries not included” mention on toys." %}*privacy not included | Shop smart and safe{% endblocktrans %} | Mozilla Foundation{% endif %}
{% endblock %}


{# TODO: consider using a different ga_identifier? #}


Expand All @@ -23,6 +22,8 @@

{% block wagtail_metadata %}
{% meta_tags %}
<meta name="pni-home-title" content="{% blocktrans context "“*privacy not included” can be localized. This is a reference to the “*batteries not included” mention on toys." %}*privacy not included | Shop smart and safe | Mozilla Foundation{% endblocktrans %}">
<meta name="pni-category-title" content="{% trans "Privacy & Security Guide | Mozilla Foundation" %}">
{% endblock %}


Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{% extends "buyersguide/bg_base.html" %}

{% load env i18n static wagtailimages_tags cache %}
{% load env i18n static wagtailimages_tags cache bg_nav_tags %}

{% block bodyclass %}pni catalog{% endblock %}

Expand All @@ -21,7 +21,7 @@ <h1 class="h1-heading text-center mt-0">{{ page.header }}</h1>
<p class="body-large mb-0">{{ page.intro_text }}</p>
<div id="product-filter-search" class='col-12 col-md-9 tw-my-5' tabindex="0">
<span class="search-icon">&nbsp;</span>
<input type="text" role="searchbox" id="product-filter-search-input" placeholder="{% trans "Search all products" %}" class="body-large" value="">
<input type="text" role="searchbox" id="product-filter-search-input" placeholder="{% trans "Search all products" %}" class="body-large tw-text-black" value="">
<label for="product-filter-search-input" class="clear-icon">&nbsp;</label>
</div>
</div>
Expand Down Expand Up @@ -69,13 +69,16 @@ <h1 class="h1-heading text-center mt-0">{{ page.header }}</h1>
{# User is not logged in. Return cached results. 24 hour caching applied. #}
{% cache 86400 pni_home_page template_cache_key_fragment %}
{% for product in products %}
{% include "../fragments/buyersguide_item.html" with product=product.localized %}
{% prod_in_cat product category as matched %}
{% include "../fragments/buyersguide_item.html" with product=product.localized matched=matched %}
{% endfor %}
{% endcache %}
{% else %}
{# User is logged in. Don't cache their results so they can see live and draft products here. #}
{% for product in products %}
{% include "../fragments/buyersguide_item.html" with product=product.localized %}
{% prod_in_cat product category as matched %}
{{matched}}
{% include "../fragments/buyersguide_item.html" with product=product.localized matched=matched %}
{% endfor %}
{% endif %}
</div>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{% load static i18n wagtailimages_tags l10n localization %}

<figure
class="product-box d-flex flex-column justify-content-between{% if product.draft %} draft-product{% endif %}{% if product.adult_content %} adult-content{% endif %}{% if product.privacy_ding %} privacy-ding{% endif%}"
class="product-box {% if matched == False %}d-none{% else %}d-flex{% endif %} flex-column justify-content-between{% if product.draft %} draft-product{% endif %}{% if product.adult_content %} adult-content{% endif %}{% if product.privacy_ding %} privacy-ding{% endif%}"
data-creepiness="{{ product.creepiness|unlocalize }}">
<div class="top-left-badge-container">
{% if product.privacy_ding %}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,13 @@ def bg_active_nav(current, target):
return 'active' if urlparse(current).path == urlparse(target).path else ''


@register.simple_tag(name='prod_in_cat')
def prod_in_cat(productpage, categorySlug):
if categorySlug == "":
return True
return categorySlug in [cat.category.slug for cat in productpage.product_categories.all()]


"""
# Instantiate a list of category page links based on the current page's relation to them
# NOTE: this points to the new, namespaced category_nav_links. If we need to revert to the old app, change this back.
Expand Down
2 changes: 1 addition & 1 deletion network-api/networkapi/wagtailpages/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,7 @@ def test_category_filter_view(self):
with self.settings(CACHES={'default': {'BACKEND': 'django.core.cache.backends.dummy.DummyCache'}}):
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertEqual(len(response.context['products']), 0)
self.assertEqual(len(response.context['products']), 1)

# Add BuyersGuideProductCategory
category_orderable = ProductPageCategory(
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
"server": "python network-api/manage.py runserver 0.0.0.0:8000",
"server:silent": "python network-api/manage.py runserver 0.0.0.0:8000 >> server.log 2>&1",
"start": "docker-compose up",
"sync": "browser-sync start --proxy \"localhost:8000\" --reload-debounce 50 --files \"./network-api/networkapi/**/*.html\" \"./network-api/networkapi/frontend/_css/*.css\" \"./network-api/networkapi/frontend/_js/*.js\"",
"sync": "npx browser-sync start --proxy \"localhost:8000\" --reload-debounce 50 --files \"./network-api/networkapi/**/*.html\" \"./network-api/networkapi/frontend/_css/*.css\" \"./network-api/networkapi/frontend/_js/*.js\"",
"tailwind": "run-p tailwind:watch sync",
"tailwind:watch": "tailwindcss -i source/postcss/tailwind.css -o network-api/networkapi/frontend/_css/tailwind.compiled.css -w",
"test:procfile": "node test/test-procfile.js",
Expand Down
113 changes: 105 additions & 8 deletions source/js/buyers-guide/search.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ const NO_RESULTS_NOTICE = document.getElementById(
`product-filter-no-results-notice`
);
const FILTERS = [`company`, `name`, `blurb`, `worst-case`];
const SORTS = [`name`, `company`, `blurb`];
const SUBMIT_PRODUCT = document.querySelector(".recommend-product");
const CREEPINESS_FACE = document.querySelector(".creep-o-meter-information");

const SearchFilter = {
init: () => {
const searchBar = document.querySelector(`#product-filter-search`);
const categoryTitle = document.querySelector(`.category-title`);

if (!searchBar) {
return console.warn(
Expand All @@ -28,12 +30,6 @@ const SearchFilter = {
}
});

const categoryTitle = document.querySelector(`.category-title`);

if (categoryTitle.value.trim()) {
SearchFilter.filterCategory(categoryTitle.value.trim());
}

const clear = searchBar.querySelector(`.clear-icon`);
if (!clear) {
return console.warn(
Expand All @@ -46,6 +42,7 @@ const SearchFilter = {
searchInput.value = ``;
searchInput.focus();
ALL_PRODUCTS.forEach((product) => product.classList.remove(`d-none`));
SearchFilter.sortOnCreepiness();
SearchFilter.moveCreepyFace();
};

Expand All @@ -59,6 +56,11 @@ const SearchFilter = {
for (const nav of navLinks) {
nav.addEventListener("click", (evt) => {
evt.stopPropagation();

if (evt.shiftKey || evt.metaKey || evt.ctrlKey || evt.altKey) {
return;
}

evt.preventDefault();

document
Expand All @@ -68,6 +70,18 @@ const SearchFilter = {
evt.target.classList.add(`active`);

if (evt.target.dataset.name) {
clearText();
history.pushState(
{
title: SearchFilter.getTitle(evt.target.dataset.name),
href: window.location.href,
category: evt.target.dataset.name,
},
SearchFilter.getTitle(evt.target.dataset.name),
evt.target.href
);

document.title = SearchFilter.getTitle(evt.target.dataset.name);
SearchFilter.filterCategory(evt.target.dataset.name);
}
});
Expand All @@ -81,6 +95,34 @@ const SearchFilter = {

SearchFilter.filterCategory("None");
});

window.addEventListener(`popstate`, (event) => {
const { state } = event;
if (!state) return; // if it's a "real" back, we shouldn't need to do anything

const { title, category } = state;
document.title = title;
SearchFilter.clearCategories();
SearchFilter.filterCategory(category);

document
.querySelector(`#multipage-nav a.active`)
.classList.remove(`active`);

document
.querySelector(`#multipage-nav a[data-name="${category}"]`)
.classList.add(`active`);
});

history.replaceState(
{
title: SearchFilter.getTitle(categoryTitle.value.trim()),
href: window.location.href,
category: categoryTitle.value.trim(),
},
SearchFilter.getTitle(categoryTitle.value.trim()),
location.href
);
},

clearCategories: () => {
Expand All @@ -94,6 +136,16 @@ const SearchFilter = {
.classList.add(`active`);
},

getTitle: (category) => {
if (category == "None")
return document.querySelector('meta[name="pni-home-title"]').content;
else {
return `${category} | ${
document.querySelector('meta[name="pni-category-title"]').content
}`;
}
},

moveCreepyFace: () => {
// When searching, check to see how many products are still visible
// If there are no visible products, there are "no search results"
Expand All @@ -110,6 +162,7 @@ const SearchFilter = {
filter: (text) => {
// remove category filters
SearchFilter.clearCategories();

document
.querySelector(`#multipage-nav a.active`)
.classList.remove(`active`);
Expand All @@ -127,13 +180,56 @@ const SearchFilter = {
}
});

SearchFilter.sortProducts();

SearchFilter.moveCreepyFace();
SearchFilter.checkForEmptyNotice();
},

sortProducts: () => {
const container = document.querySelector(`.product-box-list`);
const list = [...container.querySelectorAll(`.product-box`)];

list.sort((a, b) => {
for (field of SORTS) {
const qs = `.product-${field}`;
const [propertyA, propertyB] = [
a.querySelector(qs),
b.querySelector(qs),
];
const [propertyNameA, propertyNameB] = [
(propertyA.value || propertyA.textContent).toLowerCase(),
(propertyB.value || propertyB.textContent).toLowerCase(),
];

if (
propertyNameA !== propertyNameB ||
field === SORTS[SORTS.length - 1]
) {
return propertyNameA < propertyNameB
? -1
: propertyNameA > propertyNameB
? 1
: 0;
}
}
});

list.forEach((p) => container.append(p));
},

sortOnCreepiness: () => {
const container = document.querySelector(`.product-box-list`);
const list = [...container.querySelectorAll(`.product-box`)];
const creepVal = (e) => parseFloat(e.dataset.creepiness);
list
.sort((a, b) => creepVal(a) - creepVal(b))
.forEach((p) => container.append(p));
},

filterCategory: (category) => {
ALL_PRODUCTS.forEach((product) => {
if (SearchFilter.testCateories(product, category)) {
if (SearchFilter.testCategories(product, category)) {
product.classList.remove(`d-none`);
product.classList.add(`d-flex`);
} else {
Expand All @@ -142,6 +238,7 @@ const SearchFilter = {
}
});

SearchFilter.sortOnCreepiness();
SearchFilter.moveCreepyFace();
SearchFilter.checkForEmptyNotice();
},
Expand Down Expand Up @@ -180,7 +277,7 @@ const SearchFilter = {
return false;
},

testCateories: (product, category) => {
testCategories: (product, category) => {
if (category === "None") {
return true;
}
Expand Down

0 comments on commit e1fea73

Please sign in to comment.