Skip to content
This repository has been archived by the owner on Mar 26, 2023. It is now read-only.

Commit

Permalink
feat: отображение подсказок по истории просмотров (#23)
Browse files Browse the repository at this point in the history
Работает не лучшим образом. Вынужденно загружает вообще всю историю просмотров, чтобы получить несколько последних элементов, как как нативные возможности idb не позволяют получить N записей по индексу с конца.

Смотри:
jakearchibald/idb#176
w3c/IndexedDB#130
  • Loading branch information
cawa-93 authored Jun 3, 2021
1 parent e507cf6 commit f15685f
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 23 deletions.
61 changes: 50 additions & 11 deletions packages/renderer/src/components/HomeSearch.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<template>
<form
class="container shadow"
class="container shadow card"
@submit.prevent="onSearch"
>
<div class="card-body border-primary">
Expand All @@ -19,7 +19,25 @@
type="url"
class="form-control"
aria-describedby="search-field-help"
list="history"
@input="onDatalistOptionSelect"
>

<datalist
v-if="history.length > 0"
id="history"
>
<optgroup label="Вы недавно смотрели">
Вы недавно смотрели
<option
v-for="item of history"
:key="item.id"
>
{{ item.title }}
</option>
</optgroup>
</datalist>

<button
class="btn btn-outline-secondary"
type="submit"
Expand All @@ -29,12 +47,12 @@
</div>


<div
<small
id="search-field-help"
class="form-text"
>
{{ title || 'Вставьте ссылка на аниме с Шикимори или MyAnimeList' }}
</div>
</small>
</div>
</form>
</template>
Expand All @@ -43,9 +61,11 @@
import {computed, defineComponent, ref, watch} from 'vue';
import {useRouter} from 'vue-router';
import {getSeriesId} from '/@shared/utils/getSeriesId';
import type {Series} from '/@/utils/videoProvider';
import {getEpisodes, getSeries} from '/@/utils/videoProvider';
import {asyncComputed} from '@vueuse/core';
import WinIcon from '/@/components/WinIcon.vue';
import {getHistoryItems} from '/@/utils/history-views';
export default defineComponent({
Expand All @@ -54,10 +74,31 @@ export default defineComponent({
setup() {
const router = useRouter();
const defaultSearchText = import.meta.env.MODE === 'development' ? 'https://shikimori.org/animes/14719-jojo-no-kimyou-na-bouken-tv' : '';
const searchText = ref(defaultSearchText);
const searchText = ref('');
const animeID = computed(() => getSeriesId(searchText.value));
const history = ref<Series[]>([]);
getHistoryItems()
.then(items => Promise.all(items.map((i) => getSeries(i.seriesId))))
.then(series => history.value = series.filter(<T>(s?: T): s is T => s !== undefined));
const onDatalistOptionSelect = () => {
if (history.value.length === 0) {
return;
}
const searchTextTrimmed = searchText.value.trim();
const target = history.value.find(i => i && i.title.toLowerCase() === searchTextTrimmed.toLowerCase());
if (!target) {
return;
}
return open(target.id);
};
/**
* Если удалось определить ID аниме -- выполнить загрузку серий, чтобы они кэшировались
*/
Expand All @@ -82,15 +123,13 @@ export default defineComponent({
*/
const onSearch = () => {
if (animeID.value) {
router.push({name: 'Watch', params: {seriesId: animeID.value}});
open(animeID.value);
}
};
return {onSearch, searchText, title};
const open = (seriesId: number) => router.push({name: 'Watch', params: {seriesId}});
return {onSearch, onDatalistOptionSelect, searchText, title, history};
},
});
</script>

<style scoped>
</style>
30 changes: 19 additions & 11 deletions packages/renderer/src/utils/history-views/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {getUserRate, isLoggedIn, saveUserRate} from '/@/utils/shikimori-api';
// type HistoryViewsItemStates = 'planned' | 'watching' | 'rewatching' | 'completed' | 'on_hold' | 'dropped'


interface HistoryViewsItem {
export interface HistoryViewsItem {
seriesId: number,
episode: {
number: number,
Expand All @@ -32,9 +32,10 @@ interface HistoryViews extends DBSchema {
history: {
value: HistoryViewsItem;
key: HistoryViewsItem['seriesId'];
// indexes: {
// 'by-state': HistoryViewsItem['state']
// }
indexes: {
'by-updated-at': number
// 'by-state': HistoryViewsItem['state']
}
};
meta: Meta
}
Expand All @@ -52,16 +53,16 @@ function getDB() {
return dbPromise;
}

dbPromise = openDB<HistoryViews>('history-views', 1, {
upgrade(db, oldVersion: number) {
dbPromise = openDB<HistoryViews>('history-views', 2, {
upgrade(db, oldVersion, _newVersion, transaction) {
if (oldVersion < 1) {
db
.createObjectStore('history', {keyPath: 'seriesId'});
// .createIndex('by-state', 'state');


db.createObjectStore('history', {keyPath: 'seriesId'});
db.createObjectStore('meta');
}

if (oldVersion < 2) {
transaction.objectStore('history').createIndex('by-updated-at', 'updated_at');
}
},
});

Expand Down Expand Up @@ -137,3 +138,10 @@ export async function getViewHistoryItem(seriesId: number): Promise<HistoryViews

return savedItem;
}


export function getHistoryItems(limit = 5): Promise<HistoryViewsItem[]> {
return getDB()
.then(db => db.getAllFromIndex('history', 'by-updated-at'))
.then(items => items.splice(-limit).reverse());
}
2 changes: 1 addition & 1 deletion packages/renderer/src/utils/videoProvider/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export interface TranslationAuthor {
/**
* Возвращает {@link Series} по его MyAnimeListID
*/
export function getSeries(malId: number): Promise<DeepReadonly<Series> | undefined> {
export function getSeries(malId: number): Promise<Series | undefined> {
return deDuplicatedRequest(
`series-${malId}`,
() => provider.getSeries(malId).then(s => s === undefined ? s : readonly(s)),
Expand Down

0 comments on commit f15685f

Please sign in to comment.