<commit_before><!--
  - @copyright Copyright (c) 2021 <NAME> <<EMAIL>>
  -
  - @author <NAME> <<EMAIL>>
  -
  - @license GNU AGPL version 3 or any later version
  -
  - This program is free software: you can redistribute it and/or modify
  - it under the terms of the GNU Affero General Public License as
  - published by the Free Software Foundation, either version 3 of the
  - License, or (at your option) any later version.
  -
  - This program is distributed in the hope that it will be useful,
  - but WITHOUT ANY WARRANTY; without even the implied warranty of
  - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  - GNU Affero General Public License for more details.
  -
  - You should have received a copy of the GNU Affero General Public License
  - along with this program. If not, see <http://www.gnu.org/licenses/>.
  -
  -->

<template>
	<div v-if="searchQuery!==''" class="global-search">
		<h2><RichText :text="t('deck', 'Search for {searchQuery} in all boards')" :arguments="queryStringArgs" /></h2>
		<Actions>
			<ActionButton icon="icon-close" @click="$store.commit('setSearchQuery', '')" />
		</Actions>
		<div class="search-wrapper">
			<div v-if="loading || filteredResults.length > 0" class="search-results">
				<CardItem v-for="card in filteredResults"
					:id="card.id"
					:key="card.id"
					:standalone="true" />
				<Placeholder v-if="loading" />
				<InfiniteLoading :identifier="searchQuery" @infinite="infiniteHandler">
					<div slot="spinner" />
					<div slot="no-more" />
					<div slot="no-results">
						{{ t('deck', 'No results found') }}
					</div>
				</InfiniteLoading>
			</div>
			<div v-else>
				<p>{{ t('deck', 'No results found') }}</p>
			</div>
		</div>
	</div>
</template>

<script>
import CardItem from '../cards/CardItem'
import { mapState } from 'vuex'
import axios from '@nextcloud/axios'
import { generateOcsUrl } from '@nextcloud/router'
import InfiniteLoading from 'vue-infinite-loading'
import RichText from '@juliushaertl/vue-richtext'
import Placeholder from './Placeholder'
import { Actions, ActionButton } from '@nextcloud/vue'

const createCancelToken = () => axios.CancelToken.source()

function search({ query, cursor }) {
	const cancelToken = createCancelToken()

	const request = async() => axios.get(generateOcsUrl('apps/deck/api/v1.0/search'), {
		cancelToken: cancelToken.token,
		params: {
			term: query,
			limit: 20,
			cursor,
		},
	})

	return {
		request,
		cancel: cancelToken.cancel,
	}
}

export default {
	name: 'GlobalSearchResults',
	components: { CardItem, InfiniteLoading, RichText, Placeholder, Actions, ActionButton },
	data() {
		return {
			results: [],
			cancel: null,
			loading: false,
			cursor: null,
		}
	},
	computed: {
		...mapState({
			searchQuery: state => state.searchQuery,
		}),
		filteredResults() {
			const sortFn = (a, b) => a.archived - b.archived || b.lastModified - a.lastModified
			if (this.$route.params.id) {
				return this.results.filter((result) => result.relatedBoard.id.toString() !== this.$route.params.id.toString()).sort(sortFn)
			}
			return [...this.results].sort(sortFn)
		},
		queryStringArgs() {
			return {
				searchQuery: this.searchQuery,
			}
		},
	},
	watch: {
		searchQuery() {
			this.cursor = null
			this.loading = true
			this.search()
		},
	},
	methods: {
		infiniteHandler($state) {
			this.loading = true
			this.search().then((data) => {
				if (data.length) {
					$state.loaded()
				} else {
					$state.complete()
				}
				this.loading = false
			})
		},
		async search() {
			if (this.cancel) {
				this.cancel()
			}
			const { request, cancel } = await search({ query: this.searchQuery, cursor: this.cursor })
			this.cancel = cancel
			const { data } = await request()

			if (this.cursor === null) {
				this.results = []
			}
			if (data.ocs.data.length > 0) {
				data.ocs.data.forEach((card) => {
					this.$store.dispatch('addCardData', card)
				})
				this.results = [...this.results, ...data.ocs.data]
				this.cursor = data.ocs.data[data.ocs.data.length - 1].lastModified
			}
			return data.ocs.data
		},
	},
}
</script>

<style lang="scss" scoped>
@import '../../css/variables.scss';

.global-search {
	width: 100%;
	padding: $board-spacing + $stack-spacing;
	padding-bottom: 0;
	overflow: hidden;
	min-height: 35vh;
	max-height: 50vh;
	flex-shrink: 1;
	flex-grow: 1;
	border-top: 1px solid var(--color-border);
	z-index: 1010;
	position: relative;

	.action-item.icon-close {
		position: absolute;
		top: 10px;
		right: 10px;
	}
	.search-wrapper {
		overflow: scroll;
		height: 100%;
		position: relative;
		padding: 10px;
	}

	h2::v-deep span {
		background-color: var(--color-background-dark);
		padding: 3px;
		border-radius: var(--border-radius);
	}

	.search-results {
		display: flex;
		flex-wrap: wrap;
<commit_msg>Catch canceled requests and show better loading indication<commit_after><!--
  - @copyright Copyright (c) 2021 <NAME> <<EMAIL>>
  -
  - @author <NAME> <<EMAIL>>
  -
  - @license GNU AGPL version 3 or any later version
  -
  - This program is free software: you can redistribute it and/or modify
  - it under the terms of the GNU Affero General Public License as
  - published by the Free Software Foundation, either version 3 of the
  - License, or (at your option) any later version.
  -
  - This program is distributed in the hope that it will be useful,
  - but WITHOUT ANY WARRANTY; without even the implied warranty of
  - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  - GNU Affero General Public License for more details.
  -
  - You should have received a copy of the GNU Affero General Public License
  - along with this program. If not, see <http://www.gnu.org/licenses/>.
  -
  -->

<template>
	<div v-if="searchQuery!==''" class="global-search">
		<h2>
			<RichText :text="t('deck', 'Search for {searchQuery} in all boards')" :arguments="queryStringArgs" />
			<div v-if="loading" class="icon-loading-small" />
		</h2>
		<Actions>
			<ActionButton icon="icon-close" @click="$store.commit('setSearchQuery', '')" />
		</Actions>
		<div class="search-wrapper">
			<div v-if="loading || filteredResults.length > 0" class="search-results">
				<CardItem v-for="card in filteredResults"
					:id="card.id"
					:key="card.id"
					:standalone="true" />
				<Placeholder v-if="loading" />
				<InfiniteLoading :identifier="searchQuery" @infinite="infiniteHandler">
					<div slot="spinner" />
					<div slot="no-more" />
					<div slot="no-results">
						{{ t('deck', 'No results found') }}
					</div>
				</InfiniteLoading>
			</div>
			<div v-else>
				<p>{{ t('deck', 'No results found') }}</p>
			</div>
		</div>
	</div>
</template>

<script>
import CardItem from '../cards/CardItem'
import { mapState } from 'vuex'
import axios from '@nextcloud/axios'
import { generateOcsUrl } from '@nextcloud/router'
import InfiniteLoading from 'vue-infinite-loading'
import RichText from '@juliushaertl/vue-richtext'
import Placeholder from './Placeholder'
import { Actions, ActionButton } from '@nextcloud/vue'

const createCancelToken = () => axios.CancelToken.source()

function search({ query, cursor }) {
	const cancelToken = createCancelToken()

	const request = async() => axios.get(generateOcsUrl('apps/deck/api/v1.0/search'), {
		cancelToken: cancelToken.token,
		params: {
			term: query,
			limit: 20,
			cursor,
		},
	})

	return {
		request,
		cancel: cancelToken.cancel,
	}
}

export default {
	name: 'GlobalSearchResults',
	components: { CardItem, InfiniteLoading, RichText, Placeholder, Actions, ActionButton },
	data() {
		return {
			results: [],
			cancel: null,
			loading: false,
			cursor: null,
		}
	},
	computed: {
		...mapState({
			searchQuery: state => state.searchQuery,
		}),
		filteredResults() {
			const sortFn = (a, b) => a.archived - b.archived || b.lastModified - a.lastModified
			if (this.$route.params.id) {
				return this.results.filter((result) => result.relatedBoard.id.toString() !== this.$route.params.id.toString()).sort(sortFn)
			}
			return [...this.results].sort(sortFn)
		},
		queryStringArgs() {
			return {
				searchQuery: this.searchQuery,
			}
		},
	},
	watch: {
		async searchQuery() {
			this.cursor = null
			this.loading = true
			try {
				await this.search()
				this.loading = false
			} catch (e) {
				if (!axios.isCancel(e)) {
					console.error('Search request failed', e)
					this.loading = false
				}
			}
		},
	},
	methods: {
		async infiniteHandler($state) {
			this.loading = true
			try {
				const data = await this.search()
				if (data.length) {
					$state.loaded()
				} else {
					$state.complete()
				}
				this.loading = false
			} catch (e) {
				if (!axios.isCancel(e)) {
					console.error('Search request failed', e)
					$state.complete()
					this.loading = false
				}
			}
		},
		async search() {
			if (this.cancel) {
				this.cancel()
			}
			const { request, cancel } = await search({ query: this.searchQuery, cursor: this.cursor })
			this.cancel = cancel
			const { data } = await request()

			if (this.cursor === null) {
				this.results = []
			}
			if (data.ocs.data.length > 0) {
				data.ocs.data.forEach((card) => {
					this.$store.dispatch('addCardData', card)
				})
				this.results = [...this.results, ...data.ocs.data]
				this.cursor = data.ocs.data[data.ocs.data.length - 1].lastModified
			}
			return data.ocs.data
		},
	},
}
</script>

<style lang="scss" scoped>
@import '../../css/variables.scss';

.global-search {
	width: 100%;
	padding: $board-spacing + $stack-spacing;
	padding-bottom: 0;
	overflow: hidden;
	min-height: 35vh;
	max-height: 50vh;
	flex-shrink: 1;
	flex-grow: 1;
	border-top: 1px solid var(--color-border);
	z-index: 1010;
	position: relative;

	.action-item.icon-close {
		position: absolute;
		top: 10px;
		right: 10px;
	}
	.search-wrapper {
		overflow: scroll;
		height: 100%;
		position: relative;
		padding: 10px;
	}

	h2 > div {
		display: inline-block;

		&.icon-loading-small {
			margin-right: 20px;
		}
	}
	h2::v-deep span {
		background-color: var(--color-background-dark);
		padding: 3px;
		border-radius: var(--border-radius);
	}

	.search-results {
		display: flex;
		flex-wrap: wrap;

{'fraction_non_alphanumeric': 0.1564592359196534, 'fraction_numerical': 0.008369436786136273, 'mean_word_length': 3.1661197703035273, 'pattern_counts': {'":': 0, '<': 78, '<?xml version=': 0, '>': 96, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6604840', 'n_tokens_mistral': 3963, 'n_tokens_neox': 3389, 'n_words': 865}