aboutsummaryrefslogtreecommitdiff
path: root/front-end/src/store/bookmarks.ts
blob: 76cc5b95b402418401ca7eaad2df9e1b89a796e1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
// Copyright (C) 2024 Vaughn Nugent
//
// 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 <https://www.gnu.org/licenses/>.

import 'pinia'
import { MaybeRef, shallowRef, watch, computed, Ref, ref } from 'vue';
import { apiCall, useAxios, WebMessage } from '@vnuge/vnlib.browser';
import { useToggle, get, set, useOffsetPagination, watchDebounced, syncRef } from '@vueuse/core';
import { PiniaPluginContext, PiniaPlugin, storeToRefs } from 'pinia'
import { isArray, join, map, split, sortBy } from 'lodash-es';
import { useQuery } from './index';

export interface Bookmark{
    readonly Id: string
    Name: string
    Url: string
    Tags: string[]
    Description: string
    Created: string
    LastModified: string
}

export interface BatchUploadResult{
    readonly invalid: BookmarkError[]
}

export interface BookmarkError{
    readonly subject: Bookmark
    readonly errors: Array<{
        readonly message: string
        readonly property: string
    }>
}

export type DownloadContentType = 'application/json' | 'text/html' | 'text/csv' | 'text/plain'

export interface BookmarkApi{
    list: (page: number, limit: number, search: BookmarkSearch) => Promise<Bookmark[]>
    add: (bookmark: Bookmark) => Promise<void>
    addMany: (bookmarks: Bookmark[], failOnValidationError: boolean) => Promise<BatchUploadResult | string>
    set: (bookmark: Bookmark) => Promise<void>
    getTags: () => Promise<string[]>
    delete: (bookmark: Bookmark | Bookmark[]) => Promise<void>
    count: () => Promise<number>
    downloadAll: (contentType: DownloadContentType) => Promise<string>
}

export interface BookmarkSearch{
    query: string | undefined | null
    tags: string[]
}

declare module 'pinia' {
    export interface PiniaCustomProperties {
        bookmarks:{
            api: BookmarkApi
            query: string
            tags: string[]
            allTags: string[]
            list: Bookmark[]
            pages: ReturnType<typeof useOffsetPagination>
            refresh: () => void
        }
    }
}

const useBookmarkApi = (endpoint: MaybeRef<string>): BookmarkApi => {

    const axios = useAxios(null)

    const listBookmarks = async (page: number, limit: number, search: BookmarkSearch) => {
        const query = get(search.query)
        const tagQuery = join(get(search.tags), ' ')

        const params = new URLSearchParams()
        params.append('page', (page - 1).toString())
        params.append('limit', limit.toString())
        params.append('t', tagQuery)

        //Add query if defined
        if(query){
            params.append('q', query)
        }
      
        const { data } = await axios.get<Bookmark[]>(`${get(endpoint)}?${params.toString()}`)
        return data;
    }

    const addBookmark = async (bookmark: Bookmark) => {
        const { data } = await axios.post<WebMessage>(`${get(endpoint)}`, bookmark)
        data.getResultOrThrow();
    }

    const setBookmark = async (bookmark: Bookmark) => {
        const { data } = await axios.patch<WebMessage<Bookmark>>(`${get(endpoint)}`, bookmark)
        data.getResultOrThrow();
    }

    const deleteBookmark = async (bookmark: Bookmark | Bookmark[]) => {
        if(isArray(bookmark)){
            //Delete multiple bookmarks with comma separated ids
            const bookmarIds = join(map(bookmark, b => b.Id), ',')
            const { data } = await axios.delete<WebMessage<Bookmark>>(`${get(endpoint)}?ids=${bookmarIds}`)
            data.getResultOrThrow();    
        }
        else {
            //Delete a single bookmark
            const { data } = await axios.delete<WebMessage<Bookmark>>(`${get(endpoint)}?id=${bookmark.Id}`)
            data.getResultOrThrow();
        }
    }

    const getItemsCount = async () => {
        const { data } = await axios.get<WebMessage<number>>(`${get(endpoint)}?count=true`)
        return data.getResultOrThrow();
    }

    const getTags = async () => {
        const { data } = await axios.get<string[]>(`${get(endpoint)}?getTags=true`)
        return sortBy(data);
    }

    const addMany = async (bookmarks: Bookmark[], failOnValidationError: boolean): Promise<BatchUploadResult | string> => {
        let params = '' 
        
        if(failOnValidationError){
            params = '?failOnInvalid=true'
        }

        //Exec request, ignore a validation error on a 20x response
        const { data } = await axios.put<WebMessage<BatchUploadResult>>(`${get(endpoint)}${params}`, bookmarks);
        return data.result;
    }

    const downloadAll = async (contentType: DownloadContentType) => {
        //download the bookmarks as a html file
        const { data } = await axios.get<string>(`${get(endpoint)}?export=true`, { 
            headers: { 'Accept': contentType }
        })
        return data;
    }

    return {
        list: listBookmarks,
        add: addBookmark,
        set: setBookmark,
        delete: deleteBookmark,
        count: getItemsCount,
        addMany,
        getTags,
        downloadAll
    }
}

const urlPagiation = (p: Ref<number>, l: Ref<number>) => {
    const page = useQuery('page')
    const limit = useQuery('limit')

    const currentPage = computed({
        get: () => page.value ? parseInt(page.value) : 1,
        set: (value) => set(page, value.toString())
    })

    const currentPageSize = computed({
        get: () => limit.value ? parseInt(limit.value) : 20,
        set: (value) => set(limit, value.toString())
    })

    //Sync current page and limit with the provided refs
    syncRef(currentPage, p, { immediate: true })
    syncRef(currentPageSize, l, { immediate: true })
}

const searchQuery = (search: Ref<string | null>, tags: Ref<string[]>) => {
    
    const query = useQuery('q')
    const tagQuery = useQuery('t')

    const currentTags = computed({
        get: () => split(tagQuery.value, ' '),
        set: (value) => set(tagQuery, join(value, ' '))
    })

    //Sync current page and limit with the provided refs
    syncRef(query, search, { immediate: true })
    syncRef(currentTags, tags, { immediate: true })
}

export const bookmarkPlugin = (bookmarkEndpoint: MaybeRef<string>): PiniaPlugin => {

    return ({ store }: PiniaPluginContext) => {

        const { loggedIn } = storeToRefs(store)
        const [onRefresh, refresh] = useToggle()

        const totalBookmarks = shallowRef(0)
        const bookmarks = shallowRef<Bookmark[]>()   
        const allTags = shallowRef<string[]>([])     

        const pages = useOffsetPagination({ page: 1, pageSize: 20 })
        const { currentPage, currentPageSize } = pages;
        //Sync url query params with the pagination
        urlPagiation(currentPage, currentPageSize)

        //sync search query and tags
        const query = ref<string | null>(null)
        const tags = ref<string[]>([])
        searchQuery(query, tags)

        //Init api
        const bookmarkApi = useBookmarkApi(bookmarkEndpoint)

        watch([loggedIn, onRefresh], ([ li ]) => {
            if(!li){
                //Clear the bookmarks
                set(totalBookmarks, 0)
                set(bookmarks, [])
                return
            }

            //Update the total bookmarks
            apiCall(async () => {
                allTags.value = await bookmarkApi.getTags()
                totalBookmarks.value = await bookmarkApi.count()
            })
        })

        //Watch for serach query changes
        watchDebounced([currentPage, currentPageSize, tags, query, allTags], 
            ([ page, pageSize, tags, query ]) => {
                apiCall(async () => bookmarks.value = await bookmarkApi.list(page, pageSize, { tags, query }))
        }, { debounce: 50 })

        //Watch for page changes and scroll to top
        watch([currentPage], () => window.scrollTo({ top: 0, behavior: 'smooth' }))

        //reset current page when tags change or query changes
        watch([tags, query], () => set(currentPage, 1))
        
        return {
            bookmarks:{
                list: bookmarks,
                pages,
                refresh,
                query,
                tags,
                allTags,
                api: bookmarkApi
            }
        }
    }
}