Readlebee/app/views/search/controller.js

88 lines
2.7 KiB
JavaScript
Raw Normal View History

import { ViewController } from '../controller';
export class SearchController extends ViewController {
2019-09-25 22:41:56 +02:00
constructor(state, emit, i18n) {
// Super passes state, view name, and default state to ViewController,
// which stores state in this.appState and the view controller's state to this.state
super(state, i18n, 'search', {
lastSearch: '',
2019-09-26 20:56:28 +02:00
lastSource: 'inventaire',
lastBy: 'title',
2019-09-26 18:39:08 +02:00
searchSource: 'inventaire',
searchBy: 'title',
done: true,
results: [],
openModal: null,
});
2019-09-25 22:41:56 +02:00
this.emit = emit;
// If using controller methods in an input's onchange or onclick instance,
// either bind the class's 'this' instance to the method first...
// or use `onclick=${() => controller.submit()}` to maintain the 'this' of the class instead.
}
2019-09-11 01:16:01 +02:00
get doneSearching() {
return this.state.done;
}
get results() {
2019-09-11 01:16:01 +02:00
return this.state.results;
}
get hasQuery() {
return this.appState.query.hasOwnProperty('for') && this.appState.query.for.trim() !== '';
}
get queryIsNew() {
2019-09-26 20:56:28 +02:00
return this.state.lastSearch !== this.appState.query.for.trim()
|| this.state.lastSource !== this.state.searchSource
|| this.state.lastBy !== this.state.searchBy;
}
get openModal() {
return this.state.openModal;
}
set openModal(modalId) {
this.state.openModal = modalId;
}
2019-09-10 01:09:25 +02:00
search() {
if (this.hasQuery) {
this.state.done = false;
2019-09-25 22:41:56 +02:00
this.emit('render', () => {
this.state.lastSearch = this.appState.query.for;
2019-09-26 20:56:28 +02:00
this.state.lastSource = this.state.searchSource;
this.state.lastBy = this.state.searchBy;
2019-09-25 22:41:56 +02:00
const searchTerm = this.appState.query.for.trim();
2019-09-26 20:22:58 +02:00
return fetch(`/api/search?for=${searchTerm}&by=${this.state.searchBy}&lang=${this.appState.language}&source=${this.state.searchSource}`)
2019-09-25 22:41:56 +02:00
.then(response => response.json())
.then(responseJSON => {
this.state.results = responseJSON;
this.state.done = true;
})
.then(() => this.emit('render'));
});
2019-09-10 01:09:25 +02:00
}
}
getCovers(inventaireURI) {
// This should only be callable after results are displayed.
const workIndex = this.results.works.findIndex(work => work.uri === inventaireURI);
if (workIndex > -1) { // This should never be false, but just in case...
if (typeof this.state.results.works[workIndex].covers === 'undefined') {
// Only fetch covers if not already fetched.
return fetch(`/api/books/covers?uri=${inventaireURI}&lang=${this.appState.language}`)
.then(response => response.json())
.then(responseJSON => {
this.state.results.works[workIndex].covers = responseJSON;
});
}
}
return Promise.resolve();
}
}