Line data Source code
1 : import { computedAsync } from '@vueuse/core'
2 : import { ref, toValue } from 'vue'
3 : import type { MaybeRefOrGetter } from 'vue'
4 :
5 : interface TextSource {
6 : content?: string
7 : url?: string
8 : }
9 :
10 11 : export function useTextFileContent(
11 : source: MaybeRefOrGetter<TextSource | undefined>
12 : ) {
13 11 : const isLoading = ref(false)
14 11 : const hasError = ref(false)
15 :
16 : const textContent = computedAsync(
17 : async () => {
18 11 : hasError.value = false
19 11 : const { content, url } = toValue(source) ?? {}
20 11 : if (content !== undefined) return content
21 10 : if (!url) return ''
22 :
23 0 : const response = await fetch(url)
24 0 : if (!response.ok) {
25 0 : hasError.value = true
26 0 : return ''
27 : }
28 0 : return await response.text()
29 : },
30 : '',
31 : {
32 : evaluating: isLoading,
33 : onError: () => {
34 0 : hasError.value = true
35 : }
36 : }
37 : )
38 :
39 11 : return { textContent, isLoading, hasError }
40 : }
|