Shioriko/web/app/src/routes/Posts.svelte

99 lines
2.6 KiB
Svelte
Raw Normal View History

2021-05-10 15:47:35 +00:00
<script>
2021-05-09 15:07:23 +00:00
import { onMount } from "svelte";
2021-05-10 20:25:33 +00:00
import { getPostSearchTag } from "../api.js";
import { navigate } from "svelte-routing";
2021-05-10 17:37:27 +00:00
import PostPaginator from "../PostPaginator.svelte";
2021-05-10 20:25:33 +00:00
import queryString from "query-string";
import Tags from "svelte-tags-input";
2021-05-10 02:45:40 +00:00
export let location;
2021-05-09 15:07:23 +00:00
2021-05-10 20:25:33 +00:00
let searchTerms = [];
2021-05-09 15:07:23 +00:00
let page = 1;
let totalPages = 1;
let posts = [];
const getData = async () => {
2021-05-10 20:25:33 +00:00
const data = await getPostSearchTag({ page, q: searchTerms.join("+") });
2021-05-10 15:47:35 +00:00
if (Array.isArray(data.posts)) {
2021-05-10 02:45:40 +00:00
posts = data.posts;
2021-05-10 02:47:19 +00:00
totalPages = data.totalPage;
2021-05-10 02:45:40 +00:00
}
2021-05-10 15:47:35 +00:00
};
2021-05-10 20:25:33 +00:00
let queryParams;
const onTagChange = (value) => {
searchTerms = value.detail.tags;
};
$: {
2021-05-10 15:47:35 +00:00
queryParams = queryString.parse(location.search);
2021-05-10 20:25:33 +00:00
console.log(queryParams);
2021-05-10 15:47:35 +00:00
if (queryParams.page) {
page = parseInt(queryParams.page);
}
2021-05-10 20:25:33 +00:00
if (queryParams.tags) {
searchTerms = queryParams.tags.split(" ");
} else {
searchTerms = [];
}
2021-05-10 02:45:40 +00:00
getData();
2021-05-10 20:25:33 +00:00
}
2021-05-10 15:47:35 +00:00
2021-05-10 02:45:40 +00:00
const handlePage = (i) => {
return () => {
2021-05-10 03:17:42 +00:00
page = i;
2021-05-10 02:45:40 +00:00
getData();
2021-05-10 15:47:35 +00:00
};
};
2021-05-10 20:25:33 +00:00
const onSearch = (i) => {
if (searchTerms.length > 0) {
navigate(`/posts?tags=${searchTerms.join("+")}`);
} else {
navigate(`/posts`);
}
};
2021-05-09 15:07:23 +00:00
</script>
<section class="hero is-primary">
<div class="hero-body">
2021-05-10 15:47:35 +00:00
<p class="title">Posts</p>
2021-05-09 15:07:23 +00:00
</div>
</section>
2021-05-10 20:25:33 +00:00
<section class="section">
<div class="container">
<div class="block">
<form on:submit|preventDefault={onSearch}>
<div class="field has-addons">
<div class="control is-expanded">
<div class="control" id="tags">
<Tags
tags={searchTerms}
addKeys={[9,32]}
on:tags={onTagChange}
/>
</div>
</div>
<div class="control">
<button type="submit" class="button is-primary">
Search
</button>
</div>
</div>
</form>
</div>
<div class="block">
<PostPaginator
url="/posts?tags={searchTerms.join('+')}&"
{posts}
{page}
{totalPages}
{handlePage}
/>
</div>
</div>
</section>