Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Search History for ZoLa #13

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions addon/components/zola-search.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<Input @type='text'
placeholder={{this.searchPlaceholder}}
class='map-search-input'
id="map-search-input"
@value={{this.searchTerms}}
{{on 'focus' (action 'handleFocusIn')}}
{{on 'blur' (action 'handleFocusOut')}}
autocomplete="off"
/>
<label class="show-for-sr" for="map-search-input">Search the map</label>

{{#if this.searchTerms}}
<button class="clear-button" aria-label="Clear Search" type="button" {{action 'clear'}}>
{{#if (and this.loading (this.is-fulfilled this.loading))}}
<FaIcon @icon='spinner' @spin={{true}} class="dark-gray" />
{{else}}
<FaIcon @icon='times' class="dark-gray" />
{{/if}}
</button>
{{else}}
<FaIcon @icon='search' class="search-icon" />
{{/if}}

<ul class="search-results no-bullet{{if (or this.resultsCount this.currResults)' has-results'}} {{if this._focused 'focused'}}"
onmouseleave={{action 'handleHoverOut'}}>
{{#each-in (group-by "typeTitle" this.currResults) as |type rows|}}
<li>

{{#if (eq type "Search History")}}
<div style="display: flex; flex-direction: row; justify-content: space-between;">
<h4 class="header-small results-header">{{type}}</h4>
<span {{action 'clearSearchHistory'}} style="color: #ae561f; cursor: pointer;">
Clear History
</span>
</div>

{{else}}
<h4 class="header-small results-header">{{type}}</h4>
{{/if}}
</li>
{{#each rows key='label' as |result|}}
<li class="result {{if (eq this.selected result.id) 'highlighted-result'}}"
onmouseover={{action 'handleHoverResult' result}}
role="button" style="display: flex; flex-direction: row; justify-content: space-between;">
<div {{action 'goTo' result}} style="flex-grow: 1;">
{{#if this.hasBlock}}
{{yield (hash result=result)}}
{{else}}
{{result.label}}
{{/if}}
</div>
{{#if (eq type "Search History")}}
<span {{action 'removeSearchFromSearchHistory' result}} style="width: 12px;">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><!--!Font Awesome Free 6.5.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2024 Fonticons, Inc.--><path d="M342.6 150.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L192 210.7 86.6 105.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L146.7 256 41.4 361.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0L192 301.3 297.4 406.6c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L237.3 256 342.6 150.6z" fill="red" /></svg>
</span>
{{/if}}
</li>

{{/each}}
{{/each-in}}
</ul>

{{#if (and this.searchTerms (not this.resultsCount) (this.is-fulfilled this.results))}}
<div class="search-results--loading">No Results Found</div>
{{/if}}
227 changes: 227 additions & 0 deletions addon/components/zola-search.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
import Component from '@ember/component';
import { computed } from '@ember/object'; // eslint-disable-line
import { timeout, task } from 'ember-concurrency';
import { getOwner } from '@ember/application';
import { Promise } from 'rsvp';

const DEBOUNCE_MS = 100;

export default Component.extend({
init() {
this._super(...arguments);

const {
host = 'https://search-api-production.herokuapp.com',
route = 'search',
helpers = ['geosearch', 'city-map-street-search', 'city-map-alteration'],
} = getOwner(this).resolveRegistration('config:environment')[
'labs-search'
] || {};

this.setProperties({
typeTitleLookup: {
lot: 'Lot',
},
currResults: [],
host: host,
route: route,
helpers: helpers,
});
},

classNames: ['labs-geosearch'],

onSelect() {},

onHoverResult() {},

onHoverOut() {},

onClear() {},

results: computed('debouncedResults', 'searchTerms', function () {
const searchTerms = this.searchTerms;

return this.debouncedResults.perform(searchTerms);
}),

resultsCount: computed('results.value', function () {
const results = this.get('results.value');
if (results) return results.length;
return 0;
}),

endpoint: computed('helpers', 'host', 'route', 'searchTerms', function () {
const searchTerms = this.searchTerms;
const host = this.host;
const route = this.route;
const helpers = this.helpers
.map((string) => `helpers[]=${string}&`)
.join('');

return `${host}/${route}?${helpers}q=${searchTerms}`;
}),

searchHistory: window.localStorage["search-history"] ? JSON.parse(window.localStorage["search-history"]) : [],

searchPlaceholder: 'Search...',
searchTerms: '',
selected: 0,
_focused: false,

loading: null,

filteredSearchHistory: [],

debouncedResults: task(function* (searchTerms) {
this.send('filterSearchHistory', searchTerms)
if (searchTerms.length < 2) {
this.set('currResults', this.filteredSearchHistory);
return;
}
yield timeout(DEBOUNCE_MS);
const URL = this.endpoint;

this.set(
'loading',
new Promise(function (resolve) {
setTimeout(resolve, 500);
})
);

const raw = yield fetch(URL);
const resultList = yield raw.json();
const mergedWithTitles = resultList.map((result, index) => {
const mutatedResult = result;
mutatedResult.id = index;
mutatedResult.typeTitle =
this.get(`typeTitleLookup.${result.type}`) || 'Result';
return mutatedResult;
});

this.set('currResults', this.filteredSearchHistory.concat(mergedWithTitles));
this.set('loading', null);

return mergedWithTitles;
}).keepLatest(),

keyPress(event) {
const selected = this.selected;
const { keyCode } = event;

// enter
if (keyCode === 13) {
const results = this.get('results.value');
if (results && results.get('length')) {
const selectedResult = results.objectAt(selected);
this.send('goTo', selectedResult);
}
}
},

keyUp(event) {
const selected = this.selected;
const resultsCount = this.resultsCount;
const { keyCode } = event;

const incSelected = () => {
this.set('selected', selected + 1);
};
const decSelected = () => {
this.set('selected', selected - 1);
};

if ([38, 40, 27].includes(keyCode)) {
const results = this.get('results.value');

// up
if (keyCode === 38) {
if (results) {
if (selected > 0) decSelected();
}
}

// down
if (keyCode === 40) {
if (results) {
if (selected < resultsCount - 1) incSelected();
}
}

// escape
if (keyCode === 27) {
this.send('clear');
this.send('handleFocusOut');
}
}
},

actions: {
clear() {
this.set('searchTerms', '');
this.onClear();
},

goTo(result) {
this.send('addSearchToSearchHistory', result)
const el = document.querySelector('.map-search-input');
const event = document.createEvent('HTMLEvents');
event.initEvent('blur', true, false);
el.dispatchEvent(event);

result.searchQuery = this.get('searchTerms');

this.setProperties({
selected: 0,
searchTerms: result.label,
_focused: false,
currResults: [],
});

this.onSelect(result);
},

handleFocusIn() {
this.set('_focused', true);
},

handleHoverResult(result) {
this.onHoverResult(result);
},

handleFocusOut() {
this.set('_focused', false);
},

handleHoverOut() {
this.onHoverOut();
},

saveSearchHistory() {
window.localStorage["search-history"] = JSON.stringify(this.searchHistory.slice(0, 100))
},

addSearchToSearchHistory(result) {
const h = [...this.searchHistory].filter((search) => search.label !== result.label);
this.set('searchHistory', [{...result, typeTitle: "Search History"}, ...h]);
this.send('saveSearchHistory');
},

removeSearchFromSearchHistory(result) {
this.set('searchHistory', [...this.searchHistory].filter((search) => search.label !== result.label));
this.send('saveSearchHistory');
this.set('currResults', [...this.currResults].filter((curr) => curr.label !== result.label));
},

clearSearchHistory() {
this.set('searchHistory', []);
this.send('saveSearchHistory');
this.set('currResults', [...this.currResults].filter((search) => search.typeTitle !== "Search History"))
},

filterSearchHistory(query) {
const h = [...this.searchHistory].filter((search) => search.label.toUpperCase().includes(query.toUpperCase())).slice(0, 5);
this.set('filteredSearchHistory', h)
},
},
});
1 change: 1 addition & 0 deletions app/components/zola-search.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from '@nycplanning/ember/components/zola-search';
Loading