-
Notifications
You must be signed in to change notification settings - Fork 103
/
NftMedia.svelte
112 lines (97 loc) · 3.1 KB
/
NftMedia.svelte
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
<script lang="typescript">
import { selectedAccountIndex } from '@core/account'
import { localize } from '@core/i18n'
import { getNftByIdFromAllAccountNfts, rewriteIpfsUri } from '@core/nfts'
import { MediaDisplay } from 'shared/components'
import MediaPlaceholder from './MediaPlaceholder.svelte'
export let nftId: string
export let autoplay: boolean = false
export let controls: boolean = false
export let loop: boolean = false
export let muted: boolean = false
export let classes: string = ''
export let error: string = ''
export let warning: string = ''
export let translationSuffix: string = 'long'
const bgColor = 'gray-200'
const darkBgColor = 'gray-700'
let isLoaded = false
let hasError = false
$: nft = getNftByIdFromAllAccountNfts($selectedAccountIndex, nftId)
$: url = composeUrl(nft?.parsedMetadata?.uri)
$: nftId, resetProps()
function resetProps(): void {
isLoaded = false
hasError = false
}
function composeUrl(targetUrl: string): string {
if (!targetUrl) {
return undefined
}
const url = new URL(targetUrl)
let newUrl
switch (url.protocol) {
case 'http:':
newUrl = targetUrl.replace('http:', 'https:')
break
case 'https:':
newUrl = targetUrl
break
case 'ipfs:':
newUrl = rewriteIpfsUri(targetUrl)
break
default:
error = localize('error.nft.unsupportedUrl.' + translationSuffix)
return undefined
}
if (nft?.parsedMetadata?.issuerName === 'Soonaverse') {
return newUrl + '/' + nft?.parsedMetadata?.name
} else {
return newUrl
}
}
function handleLoadingError(err): void {
hasError = true
error = localize(err + translationSuffix)
}
function handleWarning(warn): void {
hasError = true
warning = localize(warn + translationSuffix)
}
function handleOnLoad(): void {
isLoaded = true
}
</script>
{#if !url || hasError}
<slot name="placeholder">
<MediaPlaceholder type={nft?.parsedMetadata?.type} {bgColor} {darkBgColor} />
</slot>
{:else}
<MediaDisplay
src={url}
expectedType={nft.parsedMetadata.type}
alt={`Media display for ${nft.name}`}
classes="hidden {classes}"
onLoad={handleOnLoad}
onError={handleLoadingError}
onWarning={handleWarning}
/>
{#if !isLoaded}
<slot name="placeholder">
<MediaPlaceholder type={nft?.parsedMetadata?.type} {bgColor} {darkBgColor} classes="animate-pulse" />
</slot>
{:else}
<MediaDisplay
src={url}
expectedType={nft.parsedMetadata.type}
alt={`Media display for ${nft.name}`}
{autoplay}
{controls}
{loop}
{muted}
{classes}
onError={handleLoadingError}
onWarning={handleWarning}
/>
{/if}
{/if}