tangled
alpha
login
or
join now
flo-bit.dev
/
blento
your personal website on atproto - mirror
blento.app
20
fork
atom
overview
issues
pulls
pipelines
Compare changes
Choose any two refs to compare.
base:
various-fixes
updated-blentos
update-docs
timer-card-tiny-fix
theme-colors
switch-map
switch-grid-layout
statusphere-fix
small-fixes
signup
show-login-error
section-settings
section-fix-undo
remove-extra-buttons
refactor-cards
refactor
record-visualizer-card
qr-codes
profile-stuff-2
profile-stuff
product-hunt
polijn/main
pages
npmx
next
new-og-image-wip
move-qr-click
mobile-editing
map
main-favicon
main
mail-icon
lastfm
kickstarter-card
invalid-handle-fix
improve-saving
improve-oauth
improve-link-card
improve-fluid-text
image-fixes
hide-friends
github-contribs
gifs-heypster
funding
fuck-another-fix
floating-button
fixes
fix-xss
fix-timer-stuff
fix-signup-pds
fix-package-manager
fix-other-handles-on-custom-domain
fix-invalid-site.standard.documents
fix-formatting
fix-favicon
fix-build
event-card
edit-profile
drawing-card
custom-domains-editing
custom-domains
copy-page
card-label
card-command-bar-v2
card-command-bar
button
bump-text-padding
bluesky-post-nsfw-labels
bluesky-post-card
bluesky-feed-card
apple-music-playlist
no tags found
compare:
various-fixes
updated-blentos
update-docs
timer-card-tiny-fix
theme-colors
switch-map
switch-grid-layout
statusphere-fix
small-fixes
signup
show-login-error
section-settings
section-fix-undo
remove-extra-buttons
refactor-cards
refactor
record-visualizer-card
qr-codes
profile-stuff-2
profile-stuff
product-hunt
polijn/main
pages
npmx
next
new-og-image-wip
move-qr-click
mobile-editing
map
main-favicon
main
mail-icon
lastfm
kickstarter-card
invalid-handle-fix
improve-saving
improve-oauth
improve-link-card
improve-fluid-text
image-fixes
hide-friends
github-contribs
gifs-heypster
funding
fuck-another-fix
floating-button
fixes
fix-xss
fix-timer-stuff
fix-signup-pds
fix-package-manager
fix-other-handles-on-custom-domain
fix-invalid-site.standard.documents
fix-formatting
fix-favicon
fix-build
event-card
edit-profile
drawing-card
custom-domains-editing
custom-domains
copy-page
card-label
card-command-bar-v2
card-command-bar
button
bump-text-padding
bluesky-post-nsfw-labels
bluesky-post-card
bluesky-feed-card
apple-music-playlist
no tags found
go
+1763
-426
35 changed files
expand all
collapse all
unified
split
package.json
src
lib
cards
index.ts
media
LastFMCard
CreateLastFMCardModal.svelte
LastFMAlbumArt.svelte
LastFMPeriodSettings.svelte
LastFMProfileCard
LastFMProfileCard.svelte
index.ts
LastFMRecentTracksCard
LastFMRecentTracksCard.svelte
index.ts
LastFMTopAlbumsCard
LastFMTopAlbumsCard.svelte
LastFMTopAlbumsCardSettings.svelte
index.ts
LastFMTopTracksCard
LastFMTopTracksCard.svelte
index.ts
social
GitHubContributorsCard
GitHubContributorsCard.svelte
NpmxLikesLeaderboardCard
NpmxLikesLeaderboardCard.svelte
components
ImageGrid.svelte
website
ThemeScript.svelte
params
handle.ts
routes
+layout.svelte
[handle=handle]
(pages)
+layout.server.ts
+page.svelte
edit
+page.svelte
p
[[page]]
+page.svelte
copy
+page.svelte
edit
+page.svelte
[[page]]
+layout.server.ts
+page.svelte
copy
+page.svelte
edit
+page.svelte
api
lastfm
+server.ts
p
[[page]]
+layout.server.ts
+page.svelte
copy
+page.svelte
edit
+page.svelte
+1
-1
package.json
···
5
5
"type": "module",
6
6
"scripts": {
7
7
"dev": "vite dev",
8
8
-
"build": "vite build",
8
8
+
"build": "NODE_OPTIONS='--max-old-space-size=4096' vite build",
9
9
"preview": "pnpm run build && wrangler dev",
10
10
"prepare": "svelte-kit sync || echo ''",
11
11
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
+9
-1
src/lib/cards/index.ts
···
42
42
import { KickstarterCardDefinition } from './social/KickstarterCard';
43
43
import { NpmxLikesCardDefinition } from './social/NpmxLikesCard';
44
44
import { NpmxLikesLeaderboardCardDefinition } from './social/NpmxLikesLeaderboardCard';
45
45
+
import { LastFMRecentTracksCardDefinition } from './media/LastFMCard/LastFMRecentTracksCard';
46
46
+
import { LastFMTopTracksCardDefinition } from './media/LastFMCard/LastFMTopTracksCard';
47
47
+
import { LastFMTopAlbumsCardDefinition } from './media/LastFMCard/LastFMTopAlbumsCard';
48
48
+
import { LastFMProfileCardDefinition } from './media/LastFMCard/LastFMProfileCard';
45
49
// import { Model3DCardDefinition } from './visual/Model3DCard';
46
50
47
51
export const AllCardDefinitions = [
···
88
92
ProductHuntCardDefinition,
89
93
KickstarterCardDefinition,
90
94
NpmxLikesCardDefinition,
91
91
-
NpmxLikesLeaderboardCardDefinition
95
95
+
NpmxLikesLeaderboardCardDefinition,
96
96
+
LastFMRecentTracksCardDefinition,
97
97
+
LastFMTopTracksCardDefinition,
98
98
+
LastFMTopAlbumsCardDefinition,
99
99
+
LastFMProfileCardDefinition
92
100
] as const;
93
101
94
102
export const CardDefinitionsByType = AllCardDefinitions.reduce(
+60
src/lib/cards/media/LastFMCard/CreateLastFMCardModal.svelte
···
1
1
+
<script lang="ts">
2
2
+
import { Button, Input, Modal, Subheading } from '@foxui/core';
3
3
+
import type { CreationModalComponentProps } from '../../types';
4
4
+
5
5
+
let { item = $bindable(), oncreate, oncancel }: CreationModalComponentProps = $props();
6
6
+
7
7
+
let errorMessage = $state('');
8
8
+
</script>
9
9
+
10
10
+
<Modal open={true} closeButton={false}>
11
11
+
<form
12
12
+
onsubmit={() => {
13
13
+
let input = item.cardData.href?.trim();
14
14
+
if (!input) return;
15
15
+
16
16
+
let username: string | undefined;
17
17
+
18
18
+
try {
19
19
+
const parsed = new URL(input);
20
20
+
if (/^(www\.)?last\.fm$/.test(parsed.hostname)) {
21
21
+
const segments = parsed.pathname.split('/').filter(Boolean);
22
22
+
if (segments.length >= 2 && segments[0] === 'user') {
23
23
+
username = segments[1];
24
24
+
}
25
25
+
}
26
26
+
} catch {
27
27
+
if (/^[a-zA-Z0-9_-]{2,15}$/.test(input)) {
28
28
+
username = input;
29
29
+
}
30
30
+
}
31
31
+
32
32
+
if (!username) {
33
33
+
errorMessage = 'Please enter a valid Last.fm username or profile URL';
34
34
+
return;
35
35
+
}
36
36
+
37
37
+
item.cardData.lastfmUsername = username;
38
38
+
item.cardData.href = `https://www.last.fm/user/${username}`;
39
39
+
40
40
+
oncreate?.();
41
41
+
}}
42
42
+
class="flex flex-col gap-2"
43
43
+
>
44
44
+
<Subheading>Enter a Last.fm username or profile URL</Subheading>
45
45
+
<Input
46
46
+
bind:value={item.cardData.href}
47
47
+
placeholder="username or https://www.last.fm/user/username"
48
48
+
class="mt-4"
49
49
+
/>
50
50
+
51
51
+
{#if errorMessage}
52
52
+
<p class="mt-2 text-sm text-red-600">{errorMessage}</p>
53
53
+
{/if}
54
54
+
55
55
+
<div class="mt-4 flex justify-end gap-2">
56
56
+
<Button onclick={oncancel} variant="ghost">Cancel</Button>
57
57
+
<Button type="submit">Create</Button>
58
58
+
</div>
59
59
+
</form>
60
60
+
</Modal>
+50
src/lib/cards/media/LastFMCard/LastFMAlbumArt.svelte
···
1
1
+
<script lang="ts">
2
2
+
let {
3
3
+
images,
4
4
+
alt = '',
5
5
+
size = 'medium'
6
6
+
}: { images?: { '#text': string; size: string }[]; alt?: string; size?: string } = $props();
7
7
+
8
8
+
let isLoading = $state(true);
9
9
+
let hasError = $state(false);
10
10
+
11
11
+
const imageUrl = $derived.by(() => {
12
12
+
if (!images || images.length === 0) return '';
13
13
+
const preferred = ['extralarge', 'large', 'medium', 'small'];
14
14
+
for (const pref of preferred) {
15
15
+
const img = images.find((i) => i.size === pref);
16
16
+
if (img?.['#text']) return img['#text'];
17
17
+
}
18
18
+
return images[images.length - 1]?.['#text'] || '';
19
19
+
});
20
20
+
</script>
21
21
+
22
22
+
{#if !imageUrl || hasError}
23
23
+
<div
24
24
+
class="bg-base-200 dark:bg-base-700 accent:bg-accent-700/50 flex h-full w-full items-center justify-center rounded-lg"
25
25
+
>
26
26
+
<svg
27
27
+
class="text-base-500 dark:text-base-400 accent:text-accent-200 h-5 w-5"
28
28
+
fill="currentColor"
29
29
+
viewBox="0 0 20 20"
30
30
+
>
31
31
+
<path
32
32
+
d="M18 3a1 1 0 00-1.196-.98l-10 2A1 1 0 006 5v9.114A4.369 4.369 0 005 14c-1.657 0-3 .895-3 2s1.343 2 3 2 3-.895 3-2V7.82l8-1.6v5.894A4.37 4.37 0 0015 12c-1.657 0-3 .895-3 2s1.343 2 3 2 3-.895 3-2V3z"
33
33
+
/>
34
34
+
</svg>
35
35
+
</div>
36
36
+
{:else}
37
37
+
{#if isLoading}
38
38
+
<div class="bg-base-200 dark:bg-base-800 h-full w-full animate-pulse rounded-lg"></div>
39
39
+
{/if}
40
40
+
<img
41
41
+
src={imageUrl}
42
42
+
{alt}
43
43
+
class="h-full w-full rounded-lg object-cover {isLoading && 'hidden'}"
44
44
+
onload={() => (isLoading = false)}
45
45
+
onerror={() => {
46
46
+
isLoading = false;
47
47
+
hasError = true;
48
48
+
}}
49
49
+
/>
50
50
+
{/if}
+36
src/lib/cards/media/LastFMCard/LastFMPeriodSettings.svelte
···
1
1
+
<script lang="ts">
2
2
+
import type { SettingsComponentProps } from '../../types';
3
3
+
import { Label } from '@foxui/core';
4
4
+
5
5
+
let { item = $bindable() }: SettingsComponentProps = $props();
6
6
+
7
7
+
const periodOptions = [
8
8
+
{ value: '7day', label: '7 Days' },
9
9
+
{ value: '1month', label: '1 Month' },
10
10
+
{ value: '3month', label: '3 Months' },
11
11
+
{ value: '6month', label: '6 Months' },
12
12
+
{ value: '12month', label: '12 Months' },
13
13
+
{ value: 'overall', label: 'All Time' }
14
14
+
];
15
15
+
16
16
+
let period = $derived(item.cardData.period ?? '7day');
17
17
+
</script>
18
18
+
19
19
+
<div class="flex flex-col gap-2">
20
20
+
<Label>Time Period</Label>
21
21
+
<div class="flex flex-wrap gap-2">
22
22
+
{#each periodOptions as opt (opt.value)}
23
23
+
<button
24
24
+
class={[
25
25
+
'rounded-xl border px-3 py-2 text-sm transition-colors',
26
26
+
period === opt.value
27
27
+
? 'bg-accent-500 border-accent-500 text-white'
28
28
+
: 'bg-base-100 dark:bg-base-800 border-base-300 dark:border-base-700 text-base-900 dark:text-base-100 hover:border-accent-400'
29
29
+
]}
30
30
+
onclick={() => (item.cardData.period = opt.value)}
31
31
+
>
32
32
+
{opt.label}
33
33
+
</button>
34
34
+
{/each}
35
35
+
</div>
36
36
+
</div>
+113
src/lib/cards/media/LastFMCard/LastFMProfileCard/LastFMProfileCard.svelte
···
1
1
+
<script lang="ts">
2
2
+
import { onMount } from 'svelte';
3
3
+
import { siLastdotfm } from 'simple-icons';
4
4
+
import { getAdditionalUserData } from '$lib/website/context';
5
5
+
import type { ContentComponentProps } from '../../../types';
6
6
+
import { qrOverlay } from '$lib/components/qr/qrOverlay.svelte';
7
7
+
8
8
+
interface UserInfo {
9
9
+
name: string;
10
10
+
realname: string;
11
11
+
url: string;
12
12
+
image: { '#text': string; size: string }[];
13
13
+
playcount: string;
14
14
+
registered: { unixtime: string };
15
15
+
}
16
16
+
17
17
+
let { item, isEditing }: ContentComponentProps = $props();
18
18
+
19
19
+
const data = getAdditionalUserData();
20
20
+
const cacheKey = $derived(`lastfmProfile:${item.cardData.lastfmUsername}`);
21
21
+
22
22
+
// svelte-ignore state_referenced_locally
23
23
+
let userInfo = $state(data[cacheKey] as UserInfo | undefined);
24
24
+
25
25
+
onMount(async () => {
26
26
+
if (userInfo) return;
27
27
+
if (!item.cardData.lastfmUsername) return;
28
28
+
29
29
+
try {
30
30
+
const response = await fetch(
31
31
+
`/api/lastfm?method=user.getInfo&user=${encodeURIComponent(item.cardData.lastfmUsername)}`
32
32
+
);
33
33
+
if (response.ok) {
34
34
+
const result = await response.json();
35
35
+
userInfo = result?.user;
36
36
+
data[cacheKey] = userInfo;
37
37
+
}
38
38
+
} catch (error) {
39
39
+
console.error('Failed to fetch Last.fm profile:', error);
40
40
+
}
41
41
+
});
42
42
+
43
43
+
const profileUrl = $derived(`https://www.last.fm/user/${item.cardData.lastfmUsername}`);
44
44
+
45
45
+
const avatarUrl = $derived.by(() => {
46
46
+
if (!userInfo?.image) return '';
47
47
+
const preferred = ['extralarge', 'large', 'medium'];
48
48
+
for (const pref of preferred) {
49
49
+
const img = userInfo.image.find((i) => i.size === pref);
50
50
+
if (img?.['#text']) return img['#text'];
51
51
+
}
52
52
+
return '';
53
53
+
});
54
54
+
55
55
+
const memberSince = $derived.by(() => {
56
56
+
if (!userInfo?.registered?.unixtime) return '';
57
57
+
const date = new Date(parseInt(userInfo.registered.unixtime) * 1000);
58
58
+
return date.toLocaleDateString('en-US', { month: 'long', year: 'numeric' });
59
59
+
});
60
60
+
</script>
61
61
+
62
62
+
<div class="h-full overflow-hidden p-4">
63
63
+
<div class="flex h-full flex-col justify-between">
64
64
+
<div class="flex items-center gap-3">
65
65
+
<div
66
66
+
class="fill-base-950 accent:fill-white size-6 shrink-0 dark:fill-white [&_svg]:size-full"
67
67
+
>
68
68
+
{@html siLastdotfm.svg}
69
69
+
</div>
70
70
+
<span class="truncate text-2xl font-bold">
71
71
+
{item.cardData.lastfmUsername}
72
72
+
</span>
73
73
+
</div>
74
74
+
75
75
+
{#if userInfo}
76
76
+
<div class="flex items-center gap-4">
77
77
+
{#if avatarUrl}
78
78
+
<img src={avatarUrl} alt={userInfo.name} class="size-12 rounded-full object-cover" />
79
79
+
{/if}
80
80
+
<div class="min-w-0 flex-1">
81
81
+
<div class="text-lg font-semibold">
82
82
+
{parseInt(userInfo.playcount).toLocaleString()} scrobbles
83
83
+
</div>
84
84
+
{#if memberSince}
85
85
+
<div class="text-sm opacity-60">
86
86
+
Since {memberSince}
87
87
+
</div>
88
88
+
{/if}
89
89
+
</div>
90
90
+
</div>
91
91
+
{:else}
92
92
+
<div class="text-sm opacity-60">Loading profile...</div>
93
93
+
{/if}
94
94
+
</div>
95
95
+
</div>
96
96
+
97
97
+
{#if !isEditing}
98
98
+
<a
99
99
+
href={profileUrl}
100
100
+
class="absolute inset-0 h-full w-full"
101
101
+
target="_blank"
102
102
+
rel="noopener noreferrer"
103
103
+
use:qrOverlay={{
104
104
+
context: {
105
105
+
title: item.cardData.lastfmUsername,
106
106
+
icon: siLastdotfm.svg,
107
107
+
iconColor: '#' + siLastdotfm.hex
108
108
+
}
109
109
+
}}
110
110
+
>
111
111
+
<span class="sr-only">View on Last.fm</span>
112
112
+
</a>
113
113
+
{/if}
+40
src/lib/cards/media/LastFMCard/LastFMProfileCard/index.ts
···
1
1
+
import type { CardDefinition } from '../../../types';
2
2
+
import CreateLastFMCardModal from '../CreateLastFMCardModal.svelte';
3
3
+
import LastFMProfileCard from './LastFMProfileCard.svelte';
4
4
+
5
5
+
export const LastFMProfileCardDefinition = {
6
6
+
type: 'lastfmProfile',
7
7
+
contentComponent: LastFMProfileCard,
8
8
+
creationModalComponent: CreateLastFMCardModal,
9
9
+
createNew: (card) => {
10
10
+
card.w = 4;
11
11
+
card.mobileW = 8;
12
12
+
card.h = 2;
13
13
+
card.mobileH = 3;
14
14
+
},
15
15
+
loadData: async (items) => {
16
16
+
const allData: Record<string, unknown> = {};
17
17
+
for (const item of items) {
18
18
+
const username = item.cardData.lastfmUsername;
19
19
+
if (!username) continue;
20
20
+
try {
21
21
+
const response = await fetch(
22
22
+
`https://blento.app/api/lastfm?method=user.getInfo&user=${encodeURIComponent(username)}`
23
23
+
);
24
24
+
if (!response.ok) continue;
25
25
+
const text = await response.text();
26
26
+
const result = JSON.parse(text);
27
27
+
allData[`lastfmProfile:${username}`] = result?.user;
28
28
+
} catch (error) {
29
29
+
console.error('Failed to fetch Last.fm profile:', error);
30
30
+
}
31
31
+
}
32
32
+
return allData;
33
33
+
},
34
34
+
minW: 2,
35
35
+
minH: 2,
36
36
+
name: 'Last.fm Profile',
37
37
+
keywords: ['music', 'scrobble', 'profile', 'lastfm', 'last.fm'],
38
38
+
groups: ['Media'],
39
39
+
icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="size-4"><path stroke-linecap="round" stroke-linejoin="round" d="m9 9 10.5-3m0 6.553v3.75a2.25 2.25 0 0 1-1.632 2.163l-1.32.377a1.803 1.803 0 1 1-.99-3.467l2.31-.66a2.25 2.25 0 0 0 1.632-2.163Zm0 0V2.25L9 5.25v10.303m0 0v3.75a2.25 2.25 0 0 1-1.632 2.163l-1.32.377a1.803 1.803 0 0 1-.99-3.467l2.31-.66A2.25 2.25 0 0 0 9 15.553Z" /></svg>`
40
40
+
} as CardDefinition & { type: 'lastfmProfile' };
+103
src/lib/cards/media/LastFMCard/LastFMRecentTracksCard/LastFMRecentTracksCard.svelte
···
1
1
+
<script lang="ts">
2
2
+
import { onMount } from 'svelte';
3
3
+
import { getAdditionalUserData } from '$lib/website/context';
4
4
+
import type { ContentComponentProps } from '../../../types';
5
5
+
import LastFMAlbumArt from '../LastFMAlbumArt.svelte';
6
6
+
import { RelativeTime } from '@foxui/time';
7
7
+
8
8
+
interface Track {
9
9
+
name: string;
10
10
+
artist: { '#text': string };
11
11
+
album: { '#text': string };
12
12
+
image: { '#text': string; size: string }[];
13
13
+
url: string;
14
14
+
date?: { uts: string };
15
15
+
'@attr'?: { nowplaying: string };
16
16
+
}
17
17
+
18
18
+
let { item }: ContentComponentProps = $props();
19
19
+
20
20
+
const data = getAdditionalUserData();
21
21
+
const cacheKey = $derived(`lastfmRecentTracks:${item.cardData.lastfmUsername}`);
22
22
+
23
23
+
// svelte-ignore state_referenced_locally
24
24
+
let tracks = $state(data[cacheKey] as Track[] | undefined);
25
25
+
let error = $state(false);
26
26
+
27
27
+
onMount(async () => {
28
28
+
if (tracks) return;
29
29
+
if (!item.cardData.lastfmUsername) return;
30
30
+
31
31
+
try {
32
32
+
const response = await fetch(
33
33
+
`/api/lastfm?method=user.getRecentTracks&user=${encodeURIComponent(item.cardData.lastfmUsername)}&limit=50`
34
34
+
);
35
35
+
if (response.ok) {
36
36
+
const result = await response.json();
37
37
+
tracks = result?.recenttracks?.track ?? [];
38
38
+
data[cacheKey] = tracks;
39
39
+
} else {
40
40
+
error = true;
41
41
+
}
42
42
+
} catch {
43
43
+
error = true;
44
44
+
}
45
45
+
});
46
46
+
</script>
47
47
+
48
48
+
<div class="z-10 flex h-full w-full flex-col gap-3 overflow-y-scroll p-4">
49
49
+
{#if tracks && tracks.length > 0}
50
50
+
{#each tracks as track, i (track.url + i)}
51
51
+
<a
52
52
+
href={track.url}
53
53
+
target="_blank"
54
54
+
rel="noopener noreferrer"
55
55
+
class="flex w-full items-center gap-3"
56
56
+
>
57
57
+
<div class="size-10 shrink-0">
58
58
+
<LastFMAlbumArt images={track.image} alt={track.album?.['#text']} />
59
59
+
</div>
60
60
+
<div class="min-w-0 flex-1">
61
61
+
<div class="inline-flex w-full max-w-full justify-between gap-2">
62
62
+
<div
63
63
+
class="text-accent-500 accent:text-accent-950 min-w-0 flex-1 shrink truncate font-semibold"
64
64
+
>
65
65
+
{track.name}
66
66
+
</div>
67
67
+
{#if track['@attr']?.nowplaying === 'true'}
68
68
+
<div class="flex shrink-0 items-center gap-1 text-xs text-green-500">
69
69
+
<span class="inline-block size-2 animate-pulse rounded-full bg-green-500"></span>
70
70
+
Now
71
71
+
</div>
72
72
+
{:else if track.date?.uts}
73
73
+
<div class="shrink-0 text-xs">
74
74
+
<RelativeTime date={new Date(parseInt(track.date.uts) * 1000)} locale="en-US" /> ago
75
75
+
</div>
76
76
+
{/if}
77
77
+
</div>
78
78
+
<div class="my-1 min-w-0 truncate text-xs whitespace-nowrap">
79
79
+
{track.artist?.['#text']}
80
80
+
</div>
81
81
+
</div>
82
82
+
</a>
83
83
+
{/each}
84
84
+
{:else if error}
85
85
+
<div
86
86
+
class="text-base-500 dark:text-base-400 accent:text-white/60 flex h-full items-center justify-center text-center text-sm"
87
87
+
>
88
88
+
Failed to load tracks.
89
89
+
</div>
90
90
+
{:else if tracks}
91
91
+
<div
92
92
+
class="text-base-500 dark:text-base-400 accent:text-white/60 flex h-full items-center justify-center text-center text-sm"
93
93
+
>
94
94
+
No recent tracks found.
95
95
+
</div>
96
96
+
{:else}
97
97
+
<div
98
98
+
class="text-base-500 dark:text-base-400 accent:text-white/60 flex h-full items-center justify-center text-center text-sm"
99
99
+
>
100
100
+
Loading tracks...
101
101
+
</div>
102
102
+
{/if}
103
103
+
</div>
+70
src/lib/cards/media/LastFMCard/LastFMRecentTracksCard/index.ts
···
1
1
+
import type { CardDefinition } from '../../../types';
2
2
+
import CreateLastFMCardModal from '../CreateLastFMCardModal.svelte';
3
3
+
import LastFMRecentTracksCard from './LastFMRecentTracksCard.svelte';
4
4
+
5
5
+
export const LastFMRecentTracksCardDefinition = {
6
6
+
type: 'lastfmRecentTracks',
7
7
+
contentComponent: LastFMRecentTracksCard,
8
8
+
creationModalComponent: CreateLastFMCardModal,
9
9
+
createNew: (card) => {
10
10
+
card.w = 4;
11
11
+
card.mobileW = 8;
12
12
+
card.h = 3;
13
13
+
card.mobileH = 6;
14
14
+
},
15
15
+
loadData: async (items) => {
16
16
+
const allData: Record<string, unknown> = {};
17
17
+
for (const item of items) {
18
18
+
const username = item.cardData.lastfmUsername;
19
19
+
if (!username) continue;
20
20
+
try {
21
21
+
const response = await fetch(
22
22
+
`https://blento.app/api/lastfm?method=user.getRecentTracks&user=${encodeURIComponent(username)}&limit=50`
23
23
+
);
24
24
+
if (!response.ok) continue;
25
25
+
const text = await response.text();
26
26
+
const result = JSON.parse(text);
27
27
+
allData[`lastfmRecentTracks:${username}`] = result?.recenttracks?.track ?? [];
28
28
+
} catch (error) {
29
29
+
console.error('Failed to fetch Last.fm recent tracks:', error);
30
30
+
}
31
31
+
}
32
32
+
return allData;
33
33
+
},
34
34
+
onUrlHandler: (url, item) => {
35
35
+
const username = getLastFMUsername(url);
36
36
+
if (!username) return null;
37
37
+
38
38
+
item.cardData.lastfmUsername = username;
39
39
+
item.cardData.href = `https://www.last.fm/user/${username}`;
40
40
+
item.w = 4;
41
41
+
item.mobileW = 8;
42
42
+
item.h = 3;
43
43
+
item.mobileH = 6;
44
44
+
item.cardType = 'lastfmRecentTracks';
45
45
+
return item;
46
46
+
},
47
47
+
urlHandlerPriority: 5,
48
48
+
minW: 3,
49
49
+
minH: 2,
50
50
+
canHaveLabel: true,
51
51
+
name: 'Last.fm Recent Tracks',
52
52
+
keywords: ['music', 'scrobble', 'listening', 'songs', 'lastfm', 'last.fm'],
53
53
+
groups: ['Media'],
54
54
+
icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="size-4"><path stroke-linecap="round" stroke-linejoin="round" d="m9 9 10.5-3m0 6.553v3.75a2.25 2.25 0 0 1-1.632 2.163l-1.32.377a1.803 1.803 0 1 1-.99-3.467l2.31-.66a2.25 2.25 0 0 0 1.632-2.163Zm0 0V2.25L9 5.25v10.303m0 0v3.75a2.25 2.25 0 0 1-1.632 2.163l-1.32.377a1.803 1.803 0 0 1-.99-3.467l2.31-.66A2.25 2.25 0 0 0 9 15.553Z" /></svg>`
55
55
+
} as CardDefinition & { type: 'lastfmRecentTracks' };
56
56
+
57
57
+
function getLastFMUsername(url: string | undefined): string | undefined {
58
58
+
if (!url) return;
59
59
+
try {
60
60
+
const parsed = new URL(url);
61
61
+
if (!/^(www\.)?last\.fm$/.test(parsed.hostname)) return undefined;
62
62
+
const segments = parsed.pathname.split('/').filter(Boolean);
63
63
+
if (segments.length >= 2 && segments[0] === 'user') {
64
64
+
return segments[1];
65
65
+
}
66
66
+
return undefined;
67
67
+
} catch {
68
68
+
return undefined;
69
69
+
}
70
70
+
}
+103
src/lib/cards/media/LastFMCard/LastFMTopAlbumsCard/LastFMTopAlbumsCard.svelte
···
1
1
+
<script lang="ts">
2
2
+
import { onMount } from 'svelte';
3
3
+
import type { ContentComponentProps } from '../../../types';
4
4
+
import { getAdditionalUserData } from '$lib/website/context';
5
5
+
import ImageGrid from '$lib/components/ImageGrid.svelte';
6
6
+
7
7
+
interface Album {
8
8
+
name: string;
9
9
+
playcount: string;
10
10
+
url: string;
11
11
+
artist: { name: string; url: string };
12
12
+
image: { '#text': string; size: string }[];
13
13
+
}
14
14
+
15
15
+
let { item }: ContentComponentProps = $props();
16
16
+
17
17
+
const data = getAdditionalUserData();
18
18
+
19
19
+
let period = $derived(item.cardData.period ?? '7day');
20
20
+
let layout: 'grid' | 'cinema' = $derived(item.cardData.layout ?? 'grid');
21
21
+
const cacheKey = $derived(`lastfmTopAlbums:${item.cardData.lastfmUsername}:${period}`);
22
22
+
23
23
+
// svelte-ignore state_referenced_locally
24
24
+
let albums = $state(data[cacheKey] as Album[] | undefined);
25
25
+
let loading = $state(false);
26
26
+
let error = $state(false);
27
27
+
28
28
+
async function fetchAlbums() {
29
29
+
if (!item.cardData.lastfmUsername) return;
30
30
+
loading = true;
31
31
+
32
32
+
try {
33
33
+
const response = await fetch(
34
34
+
`/api/lastfm?method=user.getTopAlbums&user=${encodeURIComponent(item.cardData.lastfmUsername)}&period=${period}&limit=50`
35
35
+
);
36
36
+
if (response.ok) {
37
37
+
const result = await response.json();
38
38
+
albums = result?.topalbums?.album ?? [];
39
39
+
data[cacheKey] = albums;
40
40
+
} else {
41
41
+
error = true;
42
42
+
}
43
43
+
} catch {
44
44
+
error = true;
45
45
+
} finally {
46
46
+
loading = false;
47
47
+
}
48
48
+
}
49
49
+
50
50
+
onMount(() => {
51
51
+
if (!albums) fetchAlbums();
52
52
+
});
53
53
+
54
54
+
$effect(() => {
55
55
+
const _period = period;
56
56
+
const cached = data[cacheKey] as Album[] | undefined;
57
57
+
if (cached) {
58
58
+
albums = cached;
59
59
+
} else {
60
60
+
fetchAlbums();
61
61
+
}
62
62
+
});
63
63
+
64
64
+
function getImageUrl(album: Album): string | null {
65
65
+
if (!album.image || album.image.length === 0) return null;
66
66
+
const preferred = ['extralarge', 'large', 'medium', 'small'];
67
67
+
for (const pref of preferred) {
68
68
+
const img = album.image.find((i) => i.size === pref);
69
69
+
if (img?.['#text']) return img['#text'];
70
70
+
}
71
71
+
return album.image[album.image.length - 1]?.['#text'] || null;
72
72
+
}
73
73
+
74
74
+
let gridItems = $derived(
75
75
+
(albums ?? []).map((album) => ({
76
76
+
imageUrl: getImageUrl(album),
77
77
+
link: album.url,
78
78
+
label: `${album.name} - ${album.artist.name}`
79
79
+
}))
80
80
+
);
81
81
+
</script>
82
82
+
83
83
+
{#if error}
84
84
+
<div class="flex h-full w-full items-center justify-center">
85
85
+
<span class="text-base-500 dark:text-base-400 accent:text-white/60 text-sm">
86
86
+
Failed to load albums.
87
87
+
</span>
88
88
+
</div>
89
89
+
{:else if albums && gridItems.length > 0}
90
90
+
<ImageGrid items={gridItems} {layout} tooltip />
91
91
+
{:else if loading || !albums}
92
92
+
<div class="flex h-full w-full items-center justify-center">
93
93
+
<span class="text-base-500 dark:text-base-400 accent:text-white/60 text-sm">
94
94
+
Loading albums...
95
95
+
</span>
96
96
+
</div>
97
97
+
{:else}
98
98
+
<div class="flex h-full w-full items-center justify-center">
99
99
+
<span class="text-base-500 dark:text-base-400 accent:text-white/60 text-sm">
100
100
+
No top albums found.
101
101
+
</span>
102
102
+
</div>
103
103
+
{/if}
+63
src/lib/cards/media/LastFMCard/LastFMTopAlbumsCard/LastFMTopAlbumsCardSettings.svelte
···
1
1
+
<script lang="ts">
2
2
+
import type { SettingsComponentProps } from '../../../types';
3
3
+
import { Label } from '@foxui/core';
4
4
+
5
5
+
let { item = $bindable() }: SettingsComponentProps = $props();
6
6
+
7
7
+
const periodOptions = [
8
8
+
{ value: '7day', label: '7 Days' },
9
9
+
{ value: '1month', label: '1 Month' },
10
10
+
{ value: '3month', label: '3 Months' },
11
11
+
{ value: '6month', label: '6 Months' },
12
12
+
{ value: '12month', label: '12 Months' },
13
13
+
{ value: 'overall', label: 'All Time' }
14
14
+
];
15
15
+
16
16
+
const layoutOptions = [
17
17
+
{ value: 'grid', label: 'Grid' },
18
18
+
{ value: 'cinema', label: 'Cinema' }
19
19
+
];
20
20
+
21
21
+
let period = $derived(item.cardData.period ?? '7day');
22
22
+
let layout = $derived(item.cardData.layout ?? 'grid');
23
23
+
</script>
24
24
+
25
25
+
<div class="flex flex-col gap-4">
26
26
+
<div class="flex flex-col gap-2">
27
27
+
<Label>Time Period</Label>
28
28
+
<div class="flex flex-wrap gap-2">
29
29
+
{#each periodOptions as opt (opt.value)}
30
30
+
<button
31
31
+
class={[
32
32
+
'rounded-xl border px-3 py-2 text-sm transition-colors',
33
33
+
period === opt.value
34
34
+
? 'bg-accent-500 border-accent-500 text-white'
35
35
+
: 'bg-base-100 dark:bg-base-800 border-base-300 dark:border-base-700 text-base-900 dark:text-base-100 hover:border-accent-400'
36
36
+
]}
37
37
+
onclick={() => (item.cardData.period = opt.value)}
38
38
+
>
39
39
+
{opt.label}
40
40
+
</button>
41
41
+
{/each}
42
42
+
</div>
43
43
+
</div>
44
44
+
45
45
+
<div class="flex flex-col gap-2">
46
46
+
<Label>Layout</Label>
47
47
+
<div class="flex gap-2">
48
48
+
{#each layoutOptions as opt (opt.value)}
49
49
+
<button
50
50
+
class={[
51
51
+
'flex-1 rounded-xl border px-3 py-2 text-sm transition-colors',
52
52
+
layout === opt.value
53
53
+
? 'bg-accent-500 border-accent-500 text-white'
54
54
+
: 'bg-base-100 dark:bg-base-800 border-base-300 dark:border-base-700 text-base-900 dark:text-base-100 hover:border-accent-400'
55
55
+
]}
56
56
+
onclick={() => (item.cardData.layout = opt.value)}
57
57
+
>
58
58
+
{opt.label}
59
59
+
</button>
60
60
+
{/each}
61
61
+
</div>
62
62
+
</div>
63
63
+
</div>
+47
src/lib/cards/media/LastFMCard/LastFMTopAlbumsCard/index.ts
···
1
1
+
import type { CardDefinition } from '../../../types';
2
2
+
import CreateLastFMCardModal from '../CreateLastFMCardModal.svelte';
3
3
+
import LastFMTopAlbumsCard from './LastFMTopAlbumsCard.svelte';
4
4
+
import LastFMTopAlbumsCardSettings from './LastFMTopAlbumsCardSettings.svelte';
5
5
+
6
6
+
export const LastFMTopAlbumsCardDefinition = {
7
7
+
type: 'lastfmTopAlbums',
8
8
+
contentComponent: LastFMTopAlbumsCard,
9
9
+
creationModalComponent: CreateLastFMCardModal,
10
10
+
settingsComponent: LastFMTopAlbumsCardSettings,
11
11
+
createNew: (card) => {
12
12
+
card.w = 4;
13
13
+
card.h = 3;
14
14
+
card.mobileW = 8;
15
15
+
card.mobileH = 4;
16
16
+
card.cardData.period = '7day';
17
17
+
},
18
18
+
loadData: async (items) => {
19
19
+
const allData: Record<string, unknown> = {};
20
20
+
for (const item of items) {
21
21
+
const username = item.cardData.lastfmUsername;
22
22
+
const period = item.cardData.period ?? '7day';
23
23
+
if (!username) continue;
24
24
+
try {
25
25
+
const response = await fetch(
26
26
+
`https://blento.app/api/lastfm?method=user.getTopAlbums&user=${encodeURIComponent(username)}&period=${period}&limit=50`
27
27
+
);
28
28
+
if (!response.ok) continue;
29
29
+
const text = await response.text();
30
30
+
const result = JSON.parse(text);
31
31
+
allData[`lastfmTopAlbums:${username}:${period}`] = result?.topalbums?.album ?? [];
32
32
+
} catch (error) {
33
33
+
console.error('Failed to fetch Last.fm top albums:', error);
34
34
+
}
35
35
+
}
36
36
+
return allData;
37
37
+
},
38
38
+
allowSetColor: true,
39
39
+
defaultColor: 'base',
40
40
+
minW: 2,
41
41
+
minH: 2,
42
42
+
canHaveLabel: true,
43
43
+
name: 'Last.fm Top Albums',
44
44
+
keywords: ['music', 'scrobble', 'albums', 'lastfm', 'last.fm', 'top'],
45
45
+
groups: ['Media'],
46
46
+
icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="size-4"><path stroke-linecap="round" stroke-linejoin="round" d="m9 9 10.5-3m0 6.553v3.75a2.25 2.25 0 0 1-1.632 2.163l-1.32.377a1.803 1.803 0 1 1-.99-3.467l2.31-.66a2.25 2.25 0 0 0 1.632-2.163Zm0 0V2.25L9 5.25v10.303m0 0v3.75a2.25 2.25 0 0 1-1.632 2.163l-1.32.377a1.803 1.803 0 0 1-.99-3.467l2.31-.66A2.25 2.25 0 0 0 9 15.553Z" /></svg>`
47
47
+
} as CardDefinition & { type: 'lastfmTopAlbums' };
+117
src/lib/cards/media/LastFMCard/LastFMTopTracksCard/LastFMTopTracksCard.svelte
···
1
1
+
<script lang="ts">
2
2
+
import { onMount } from 'svelte';
3
3
+
import { getAdditionalUserData } from '$lib/website/context';
4
4
+
import type { ContentComponentProps } from '../../../types';
5
5
+
import LastFMAlbumArt from '../LastFMAlbumArt.svelte';
6
6
+
7
7
+
interface Track {
8
8
+
name: string;
9
9
+
playcount: string;
10
10
+
artist: { name: string; url: string };
11
11
+
image: { '#text': string; size: string }[];
12
12
+
url: string;
13
13
+
}
14
14
+
15
15
+
let { item }: ContentComponentProps = $props();
16
16
+
17
17
+
const data = getAdditionalUserData();
18
18
+
19
19
+
let period = $derived(item.cardData.period ?? '7day');
20
20
+
const cacheKey = $derived(`lastfmTopTracks:${item.cardData.lastfmUsername}:${period}`);
21
21
+
22
22
+
// svelte-ignore state_referenced_locally
23
23
+
let tracks = $state(data[cacheKey] as Track[] | undefined);
24
24
+
let error = $state(false);
25
25
+
let loading = $state(false);
26
26
+
27
27
+
async function fetchTracks() {
28
28
+
if (!item.cardData.lastfmUsername) return;
29
29
+
loading = true;
30
30
+
31
31
+
try {
32
32
+
const response = await fetch(
33
33
+
`/api/lastfm?method=user.getTopTracks&user=${encodeURIComponent(item.cardData.lastfmUsername)}&period=${period}&limit=50`
34
34
+
);
35
35
+
if (response.ok) {
36
36
+
const result = await response.json();
37
37
+
tracks = result?.toptracks?.track ?? [];
38
38
+
data[cacheKey] = tracks;
39
39
+
} else {
40
40
+
error = true;
41
41
+
}
42
42
+
} catch {
43
43
+
error = true;
44
44
+
} finally {
45
45
+
loading = false;
46
46
+
}
47
47
+
}
48
48
+
49
49
+
onMount(() => {
50
50
+
if (!tracks) fetchTracks();
51
51
+
});
52
52
+
53
53
+
$effect(() => {
54
54
+
const _period = period;
55
55
+
const cached = data[cacheKey] as Track[] | undefined;
56
56
+
if (cached) {
57
57
+
tracks = cached;
58
58
+
} else {
59
59
+
fetchTracks();
60
60
+
}
61
61
+
});
62
62
+
</script>
63
63
+
64
64
+
<div class="z-10 flex h-full w-full flex-col gap-3 overflow-y-scroll p-4">
65
65
+
{#if tracks && tracks.length > 0}
66
66
+
{#each tracks as track, i (track.url)}
67
67
+
<a
68
68
+
href={track.url}
69
69
+
target="_blank"
70
70
+
rel="noopener noreferrer"
71
71
+
class="flex w-full items-center gap-3"
72
72
+
>
73
73
+
<div
74
74
+
class="text-base-400 dark:text-base-500 accent:text-white/40 w-5 shrink-0 text-right text-xs font-bold"
75
75
+
>
76
76
+
{i + 1}
77
77
+
</div>
78
78
+
<div class="size-10 shrink-0">
79
79
+
<LastFMAlbumArt images={track.image} alt={track.name} />
80
80
+
</div>
81
81
+
<div class="min-w-0 flex-1">
82
82
+
<div class="inline-flex w-full max-w-full justify-between gap-2">
83
83
+
<div
84
84
+
class="text-accent-500 accent:text-accent-950 min-w-0 flex-1 shrink truncate font-semibold"
85
85
+
>
86
86
+
{track.name}
87
87
+
</div>
88
88
+
<div class="shrink-0 text-xs">
89
89
+
{parseInt(track.playcount).toLocaleString()} plays
90
90
+
</div>
91
91
+
</div>
92
92
+
<div class="my-1 min-w-0 truncate text-xs whitespace-nowrap">
93
93
+
{track.artist?.name}
94
94
+
</div>
95
95
+
</div>
96
96
+
</a>
97
97
+
{/each}
98
98
+
{:else if error}
99
99
+
<div
100
100
+
class="text-base-500 dark:text-base-400 accent:text-white/60 flex h-full items-center justify-center text-center text-sm"
101
101
+
>
102
102
+
Failed to load tracks.
103
103
+
</div>
104
104
+
{:else if tracks || loading}
105
105
+
<div
106
106
+
class="text-base-500 dark:text-base-400 accent:text-white/60 flex h-full items-center justify-center text-center text-sm"
107
107
+
>
108
108
+
{tracks?.length === 0 ? 'No top tracks found.' : 'Loading tracks...'}
109
109
+
</div>
110
110
+
{:else}
111
111
+
<div
112
112
+
class="text-base-500 dark:text-base-400 accent:text-white/60 flex h-full items-center justify-center text-center text-sm"
113
113
+
>
114
114
+
Loading tracks...
115
115
+
</div>
116
116
+
{/if}
117
117
+
</div>
+45
src/lib/cards/media/LastFMCard/LastFMTopTracksCard/index.ts
···
1
1
+
import type { CardDefinition } from '../../../types';
2
2
+
import CreateLastFMCardModal from '../CreateLastFMCardModal.svelte';
3
3
+
import LastFMPeriodSettings from '../LastFMPeriodSettings.svelte';
4
4
+
import LastFMTopTracksCard from './LastFMTopTracksCard.svelte';
5
5
+
6
6
+
export const LastFMTopTracksCardDefinition = {
7
7
+
type: 'lastfmTopTracks',
8
8
+
contentComponent: LastFMTopTracksCard,
9
9
+
creationModalComponent: CreateLastFMCardModal,
10
10
+
settingsComponent: LastFMPeriodSettings,
11
11
+
createNew: (card) => {
12
12
+
card.w = 4;
13
13
+
card.mobileW = 8;
14
14
+
card.h = 3;
15
15
+
card.mobileH = 6;
16
16
+
card.cardData.period = '7day';
17
17
+
},
18
18
+
loadData: async (items) => {
19
19
+
const allData: Record<string, unknown> = {};
20
20
+
for (const item of items) {
21
21
+
const username = item.cardData.lastfmUsername;
22
22
+
const period = item.cardData.period ?? '7day';
23
23
+
if (!username) continue;
24
24
+
try {
25
25
+
const response = await fetch(
26
26
+
`https://blento.app/api/lastfm?method=user.getTopTracks&user=${encodeURIComponent(username)}&period=${period}&limit=50`
27
27
+
);
28
28
+
if (!response.ok) continue;
29
29
+
const text = await response.text();
30
30
+
const result = JSON.parse(text);
31
31
+
allData[`lastfmTopTracks:${username}:${period}`] = result?.toptracks?.track ?? [];
32
32
+
} catch (error) {
33
33
+
console.error('Failed to fetch Last.fm top tracks:', error);
34
34
+
}
35
35
+
}
36
36
+
return allData;
37
37
+
},
38
38
+
minW: 3,
39
39
+
minH: 2,
40
40
+
canHaveLabel: true,
41
41
+
name: 'Last.fm Top Tracks',
42
42
+
keywords: ['music', 'scrobble', 'songs', 'lastfm', 'last.fm', 'top'],
43
43
+
groups: ['Media'],
44
44
+
icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor" class="size-4"><path stroke-linecap="round" stroke-linejoin="round" d="m9 9 10.5-3m0 6.553v3.75a2.25 2.25 0 0 1-1.632 2.163l-1.32.377a1.803 1.803 0 1 1-.99-3.467l2.31-.66a2.25 2.25 0 0 0 1.632-2.163Zm0 0V2.25L9 5.25v10.303m0 0v3.75a2.25 2.25 0 0 1-1.632 2.163l-1.32.377a1.803 1.803 0 0 1-.99-3.467l2.31-.66A2.25 2.25 0 0 0 9 15.553Z" /></svg>`
45
45
+
} as CardDefinition & { type: 'lastfmTopTracks' };
+14
-135
src/lib/cards/social/GitHubContributorsCard/GitHubContributorsCard.svelte
···
1
1
<script lang="ts">
2
2
import { onMount } from 'svelte';
3
3
import type { ContentComponentProps } from '../../types';
4
4
-
import { getAdditionalUserData, getCanEdit, getIsMobile } from '$lib/website/context';
4
4
+
import { getAdditionalUserData, getCanEdit } from '$lib/website/context';
5
5
import type { GitHubContributor, GitHubContributorsLoadedData } from '.';
6
6
+
import ImageGrid from '$lib/components/ImageGrid.svelte';
6
7
7
8
let { item }: ContentComponentProps = $props();
8
9
9
9
-
const isMobile = getIsMobile();
10
10
const canEdit = getCanEdit();
11
11
const additionalData = getAdditionalUserData();
12
12
···
53
53
}
54
54
}
55
55
56
56
-
let containerWidth = $state(0);
57
57
-
let containerHeight = $state(0);
58
58
-
59
59
-
let totalItems = $derived(namedContributors.length);
60
60
-
61
61
-
const GAP = 6;
62
62
-
const MIN_SIZE = 16;
63
63
-
const MAX_SIZE = 120;
64
64
-
65
65
-
function cinemaCapacity(size: number, availW: number, availH: number): number {
66
66
-
const colsWide = Math.floor((availW + GAP) / (size + GAP));
67
67
-
if (colsWide < 1) return 0;
68
68
-
const colsNarrow = Math.max(1, colsWide - 1);
69
69
-
const maxRows = Math.floor((availH + GAP) / (size + GAP));
70
70
-
let capacity = 0;
71
71
-
// Pattern: narrow, wide, narrow, wide... (row 0 is narrow)
72
72
-
for (let r = 0; r < maxRows; r++) {
73
73
-
capacity += r % 2 === 0 ? colsNarrow : colsWide;
74
74
-
}
75
75
-
return capacity;
76
76
-
}
77
77
-
78
78
-
function gridCapacity(size: number, availW: number, availH: number): number {
79
79
-
const cols = Math.floor((availW + GAP) / (size + GAP));
80
80
-
const rows = Math.floor((availH + GAP) / (size + GAP));
81
81
-
return cols * rows;
82
82
-
}
83
83
-
84
84
-
let computedSize = $derived.by(() => {
85
85
-
if (!containerWidth || !containerHeight || totalItems === 0) return 40;
86
86
-
87
87
-
let lo = MIN_SIZE;
88
88
-
let hi = MAX_SIZE;
89
89
-
const capacityFn = layout === 'cinema' ? cinemaCapacity : gridCapacity;
90
90
-
91
91
-
while (lo <= hi) {
92
92
-
const mid = Math.floor((lo + hi) / 2);
93
93
-
const availW = containerWidth - (layout === 'cinema' ? mid / 2 : 0);
94
94
-
const availH = containerHeight - (layout === 'cinema' ? mid / 2 : 0);
95
95
-
if (availW <= 0 || availH <= 0) {
96
96
-
hi = mid - 1;
97
97
-
continue;
98
98
-
}
99
99
-
if (capacityFn(mid, availW, availH) >= totalItems) {
100
100
-
lo = mid + 1;
101
101
-
} else {
102
102
-
hi = mid - 1;
103
103
-
}
104
104
-
}
105
105
-
106
106
-
return Math.max(MIN_SIZE, hi);
107
107
-
});
108
108
-
109
109
-
let padding = $derived(layout === 'cinema' ? computedSize / 4 : 0);
110
110
-
111
111
-
let rows = $derived.by(() => {
112
112
-
const availW = containerWidth - (layout === 'cinema' ? computedSize / 4 : 0);
113
113
-
if (availW <= 0) return [] as GitHubContributor[][];
114
114
-
115
115
-
const colsWide = Math.floor((availW + GAP) / (computedSize + GAP));
116
116
-
const colsNarrow = layout === 'cinema' ? Math.max(1, colsWide - 1) : colsWide;
117
117
-
118
118
-
// Calculate row sizes from bottom up, then reverse for incomplete row at top
119
119
-
const rowSizes: number[] = [];
120
120
-
let remaining = namedContributors.length;
121
121
-
let rowNum = 0;
122
122
-
while (remaining > 0) {
123
123
-
const cols = layout === 'cinema' && rowNum % 2 === 0 ? colsNarrow : colsWide;
124
124
-
rowSizes.push(Math.min(cols, remaining));
125
125
-
remaining -= cols;
126
126
-
rowNum++;
127
127
-
}
128
128
-
rowSizes.reverse();
129
129
-
130
130
-
// Fill rows with contributors in order
131
131
-
const result: GitHubContributor[][] = [];
132
132
-
let idx = 0;
133
133
-
for (const size of rowSizes) {
134
134
-
result.push(namedContributors.slice(idx, idx + size));
135
135
-
idx += size;
136
136
-
}
137
137
-
return result;
138
138
-
});
139
139
-
140
140
-
let textSize = $derived(
141
141
-
computedSize < 24 ? 'text-[10px]' : computedSize < 40 ? 'text-xs' : 'text-sm'
56
56
+
let gridItems = $derived(
57
57
+
namedContributors.map((c) => ({
58
58
+
imageUrl: c.avatarUrl,
59
59
+
link: `https://github.com/${c.username}`,
60
60
+
label: c.username
61
61
+
}))
142
62
);
143
143
-
144
144
-
let shapeClass = $derived(shape === 'circle' ? 'rounded-full' : 'rounded-lg');
145
63
</script>
146
64
147
147
-
<div
148
148
-
class="flex h-full w-full items-center justify-center overflow-hidden px-2"
149
149
-
bind:clientWidth={containerWidth}
150
150
-
bind:clientHeight={containerHeight}
151
151
-
>
152
152
-
{#if !owner || !repo}
153
153
-
{#if canEdit()}
65
65
+
{#if !owner || !repo}
66
66
+
{#if canEdit()}
67
67
+
<div class="flex h-full w-full items-center justify-center">
154
68
<span class="text-base-400 dark:text-base-500 accent:text-accent-300 text-sm">
155
69
Enter a repository
156
70
</span>
157
157
-
{/if}
158
158
-
{:else if totalItems > 0}
159
159
-
<div style="padding: {padding}px;">
160
160
-
<div class="flex flex-col items-center" style="gap: {GAP}px;">
161
161
-
{#each rows as row, rowIdx (rowIdx)}
162
162
-
<div class="flex justify-center" style="gap: {GAP}px;">
163
163
-
{#each row as contributor (contributor.username)}
164
164
-
<a
165
165
-
href="https://github.com/{contributor.username}"
166
166
-
target="_blank"
167
167
-
rel="noopener noreferrer"
168
168
-
class="accent:ring-accent-500 block {shapeClass} ring-2 ring-white transition-transform hover:scale-110 dark:ring-neutral-900"
169
169
-
>
170
170
-
{#if contributor.avatarUrl}
171
171
-
<img
172
172
-
src={contributor.avatarUrl}
173
173
-
alt={contributor.username}
174
174
-
class="{shapeClass} object-cover"
175
175
-
style="width: {computedSize}px; height: {computedSize}px;"
176
176
-
/>
177
177
-
{:else}
178
178
-
<div
179
179
-
class="bg-base-200 dark:bg-base-700 accent:bg-accent-400 flex items-center justify-center {shapeClass}"
180
180
-
style="width: {computedSize}px; height: {computedSize}px;"
181
181
-
>
182
182
-
<span
183
183
-
class="text-base-500 dark:text-base-400 accent:text-accent-100 {textSize} font-medium"
184
184
-
>
185
185
-
{contributor.username.charAt(0).toUpperCase()}
186
186
-
</span>
187
187
-
</div>
188
188
-
{/if}
189
189
-
</a>
190
190
-
{/each}
191
191
-
</div>
192
192
-
{/each}
193
193
-
</div>
194
71
</div>
195
72
{/if}
196
196
-
</div>
73
73
+
{:else}
74
74
+
<ImageGrid items={gridItems} {layout} {shape} tooltip />
75
75
+
{/if}
+1
-1
src/lib/cards/social/NpmxLikesLeaderboardCard/NpmxLikesLeaderboardCard.svelte
···
91
91
{/each}
92
92
</div>
93
93
<div
94
94
-
class="pointer-events-none absolute inset-x-0 bottom-0 z-10 h-12 bg-linear-to-t from-base-200 from-40% to-transparent dark:from-base-950 accent:from-accent-500"
94
94
+
class="from-base-200 dark:from-base-950 accent:from-accent-500 pointer-events-none absolute inset-x-0 bottom-0 z-10 h-12 bg-linear-to-t from-40% to-transparent"
95
95
></div>
96
96
<div
97
97
class="text-base-500 dark:text-base-400 accent:text-white/60 bg-base-200 dark:bg-base-950/50 accent:bg-accent-500/20 relative z-10 flex shrink-0 items-center justify-center gap-3 px-4 pb-3 text-xs"
+180
src/lib/components/ImageGrid.svelte
···
1
1
+
<script lang="ts">
2
2
+
import { Tooltip } from 'bits-ui';
3
3
+
4
4
+
export type ImageGridItem = {
5
5
+
imageUrl: string | null;
6
6
+
link: string;
7
7
+
label: string;
8
8
+
};
9
9
+
10
10
+
let {
11
11
+
items,
12
12
+
layout = 'grid',
13
13
+
shape = 'square',
14
14
+
tooltip = false
15
15
+
}: {
16
16
+
items: ImageGridItem[];
17
17
+
layout?: 'grid' | 'cinema';
18
18
+
shape?: 'square' | 'circle';
19
19
+
tooltip?: boolean;
20
20
+
} = $props();
21
21
+
22
22
+
let containerWidth = $state(0);
23
23
+
let containerHeight = $state(0);
24
24
+
25
25
+
let totalItems = $derived(items.length);
26
26
+
27
27
+
const GAP = 6;
28
28
+
const MIN_SIZE = 16;
29
29
+
const MAX_SIZE = 120;
30
30
+
31
31
+
function cinemaCapacity(size: number, availW: number, availH: number): number {
32
32
+
const colsWide = Math.floor((availW + GAP) / (size + GAP));
33
33
+
if (colsWide < 1) return 0;
34
34
+
const colsNarrow = Math.max(1, colsWide - 1);
35
35
+
const maxRows = Math.floor((availH + GAP) / (size + GAP));
36
36
+
let capacity = 0;
37
37
+
for (let r = 0; r < maxRows; r++) {
38
38
+
capacity += r % 2 === 0 ? colsNarrow : colsWide;
39
39
+
}
40
40
+
return capacity;
41
41
+
}
42
42
+
43
43
+
function gridCapacity(size: number, availW: number, availH: number): number {
44
44
+
const cols = Math.floor((availW + GAP) / (size + GAP));
45
45
+
const rows = Math.floor((availH + GAP) / (size + GAP));
46
46
+
return cols * rows;
47
47
+
}
48
48
+
49
49
+
let computedSize = $derived.by(() => {
50
50
+
if (!containerWidth || !containerHeight || totalItems === 0) return 40;
51
51
+
52
52
+
let lo = MIN_SIZE;
53
53
+
let hi = MAX_SIZE;
54
54
+
const capacityFn = layout === 'cinema' ? cinemaCapacity : gridCapacity;
55
55
+
56
56
+
while (lo <= hi) {
57
57
+
const mid = Math.floor((lo + hi) / 2);
58
58
+
const availW = containerWidth - (layout === 'cinema' ? mid / 2 : 0);
59
59
+
const availH = containerHeight - (layout === 'cinema' ? mid / 2 : 0);
60
60
+
if (availW <= 0 || availH <= 0) {
61
61
+
hi = mid - 1;
62
62
+
continue;
63
63
+
}
64
64
+
if (capacityFn(mid, availW, availH) >= totalItems) {
65
65
+
lo = mid + 1;
66
66
+
} else {
67
67
+
hi = mid - 1;
68
68
+
}
69
69
+
}
70
70
+
71
71
+
return Math.max(MIN_SIZE, hi);
72
72
+
});
73
73
+
74
74
+
let padding = $derived(layout === 'cinema' ? computedSize / 4 : 0);
75
75
+
76
76
+
let rows = $derived.by(() => {
77
77
+
const availW = containerWidth - (layout === 'cinema' ? computedSize / 4 : 0);
78
78
+
if (availW <= 0) return [] as ImageGridItem[][];
79
79
+
80
80
+
const colsWide = Math.floor((availW + GAP) / (computedSize + GAP));
81
81
+
const colsNarrow = layout === 'cinema' ? Math.max(1, colsWide - 1) : colsWide;
82
82
+
83
83
+
const rowSizes: number[] = [];
84
84
+
let remaining = items.length;
85
85
+
let rowNum = 0;
86
86
+
while (remaining > 0) {
87
87
+
const cols = layout === 'cinema' && rowNum % 2 === 0 ? colsNarrow : colsWide;
88
88
+
rowSizes.push(Math.min(cols, remaining));
89
89
+
remaining -= cols;
90
90
+
rowNum++;
91
91
+
}
92
92
+
rowSizes.reverse();
93
93
+
94
94
+
const result: ImageGridItem[][] = [];
95
95
+
let idx = 0;
96
96
+
for (const size of rowSizes) {
97
97
+
result.push(items.slice(idx, idx + size));
98
98
+
idx += size;
99
99
+
}
100
100
+
return result;
101
101
+
});
102
102
+
103
103
+
let textSize = $derived(
104
104
+
computedSize < 24 ? 'text-[10px]' : computedSize < 40 ? 'text-xs' : 'text-sm'
105
105
+
);
106
106
+
107
107
+
let shapeClass = $derived(shape === 'circle' ? 'rounded-full' : 'rounded-lg');
108
108
+
</script>
109
109
+
110
110
+
{#snippet gridItem(item: ImageGridItem)}
111
111
+
{#if item.imageUrl}
112
112
+
<img
113
113
+
src={item.imageUrl}
114
114
+
alt={item.label}
115
115
+
class="{shapeClass} object-cover"
116
116
+
style="width: {computedSize}px; height: {computedSize}px;"
117
117
+
/>
118
118
+
{:else}
119
119
+
<div
120
120
+
class="bg-base-200 dark:bg-base-700 accent:bg-accent-400 flex items-center justify-center {shapeClass}"
121
121
+
style="width: {computedSize}px; height: {computedSize}px;"
122
122
+
>
123
123
+
<span class="text-base-500 dark:text-base-400 accent:text-accent-100 {textSize} font-medium">
124
124
+
{item.label.charAt(0).toUpperCase()}
125
125
+
</span>
126
126
+
</div>
127
127
+
{/if}
128
128
+
{/snippet}
129
129
+
130
130
+
<div
131
131
+
class="flex h-full w-full items-center justify-center overflow-hidden px-2"
132
132
+
bind:clientWidth={containerWidth}
133
133
+
bind:clientHeight={containerHeight}
134
134
+
>
135
135
+
{#if totalItems > 0}
136
136
+
<div style="padding: {padding}px;">
137
137
+
<div class="flex flex-col items-center" style="gap: {GAP}px;">
138
138
+
{#each rows as row, rowIdx (rowIdx)}
139
139
+
<div class="flex justify-center" style="gap: {GAP}px;">
140
140
+
{#each row as item (item.link)}
141
141
+
{#if tooltip}
142
142
+
<Tooltip.Root>
143
143
+
<Tooltip.Trigger>
144
144
+
<a
145
145
+
href={item.link}
146
146
+
target="_blank"
147
147
+
rel="noopener noreferrer"
148
148
+
class="accent:ring-accent-500 block {shapeClass} ring-2 ring-white transition-transform hover:scale-110 dark:ring-neutral-900"
149
149
+
>
150
150
+
{@render gridItem(item)}
151
151
+
</a>
152
152
+
</Tooltip.Trigger>
153
153
+
<Tooltip.Portal>
154
154
+
<Tooltip.Content
155
155
+
side="top"
156
156
+
sideOffset={4}
157
157
+
class="bg-base-900 dark:bg-base-800 text-base-100 z-50 rounded-lg px-3 py-1.5 text-xs font-medium shadow-md"
158
158
+
>
159
159
+
{item.label}
160
160
+
</Tooltip.Content>
161
161
+
</Tooltip.Portal>
162
162
+
</Tooltip.Root>
163
163
+
{:else}
164
164
+
<a
165
165
+
href={item.link}
166
166
+
target="_blank"
167
167
+
rel="noopener noreferrer"
168
168
+
class="accent:ring-accent-500 block {shapeClass} ring-2 ring-white transition-transform hover:scale-110 dark:ring-neutral-900"
169
169
+
title={item.label}
170
170
+
>
171
171
+
{@render gridItem(item)}
172
172
+
</a>
173
173
+
{/if}
174
174
+
{/each}
175
175
+
</div>
176
176
+
{/each}
177
177
+
</div>
178
178
+
</div>
179
179
+
{/if}
180
180
+
</div>
+17
-2
src/lib/website/ThemeScript.svelte
···
10
10
} = $props();
11
11
12
12
const allAccentColors = [
13
13
-
'red', 'orange', 'amber', 'yellow', 'lime', 'green', 'emerald', 'teal',
14
14
-
'cyan', 'sky', 'blue', 'indigo', 'violet', 'purple', 'fuchsia', 'pink', 'rose'
13
13
+
'red',
14
14
+
'orange',
15
15
+
'amber',
16
16
+
'yellow',
17
17
+
'lime',
18
18
+
'green',
19
19
+
'emerald',
20
20
+
'teal',
21
21
+
'cyan',
22
22
+
'sky',
23
23
+
'blue',
24
24
+
'indigo',
25
25
+
'violet',
26
26
+
'purple',
27
27
+
'fuchsia',
28
28
+
'pink',
29
29
+
'rose'
15
30
];
16
31
const allBaseColors = ['gray', 'stone', 'zinc', 'neutral', 'slate'];
17
32
+2
-1
src/params/handle.ts
···
1
1
+
import { isActorIdentifier } from '@atcute/lexicons/syntax';
1
2
import type { ParamMatcher } from '@sveltejs/kit';
2
3
3
4
export const match = ((param: string) => {
4
4
-
return param.includes('.') || param.startsWith('did:');
5
5
+
return isActorIdentifier(param);
5
6
}) satisfies ParamMatcher;
+4
-1
src/routes/+layout.svelte
···
1
1
<script lang="ts">
2
2
import '../app.css';
3
3
4
4
+
import { Tooltip } from 'bits-ui';
4
5
import { ThemeToggle, Toaster, toast } from '@foxui/core';
5
6
import { onMount } from 'svelte';
6
7
import { initClient } from '$lib/atproto';
···
28
29
});
29
30
</script>
30
31
31
31
-
{@render children()}
32
32
+
<Tooltip.Provider delayDuration={300}>
33
33
+
{@render children()}
34
34
+
</Tooltip.Provider>
32
35
33
36
<ThemeToggle class="fixed top-2 left-2 z-10" />
34
37
<Toaster />
+13
src/routes/[handle=handle]/(pages)/+layout.server.ts
···
1
1
+
import { loadData } from '$lib/website/load';
2
2
+
import { env } from '$env/dynamic/private';
3
3
+
import { error } from '@sveltejs/kit';
4
4
+
import type { UserCache } from '$lib/types';
5
5
+
import type { Handle } from '@atcute/lexicons';
6
6
+
7
7
+
export async function load({ params, platform }) {
8
8
+
if (env.PUBLIC_IS_SELFHOSTED) error(404);
9
9
+
10
10
+
const cache = platform?.env?.USER_DATA_CACHE as unknown;
11
11
+
12
12
+
return await loadData(params.handle as Handle, cache as UserCache, false, params.page);
13
13
+
}
+13
src/routes/[handle=handle]/(pages)/+page.svelte
···
1
1
+
<script lang="ts">
2
2
+
import { refreshData } from '$lib/helper.js';
3
3
+
import Website from '$lib/website/Website.svelte';
4
4
+
import { onMount } from 'svelte';
5
5
+
6
6
+
let { data } = $props();
7
7
+
8
8
+
onMount(() => {
9
9
+
refreshData(data);
10
10
+
});
11
11
+
</script>
12
12
+
13
13
+
<Website {data} />
+6
src/routes/[handle=handle]/(pages)/edit/+page.svelte
···
1
1
+
<script lang="ts">
2
2
+
import EditableWebsite from '$lib/website/EditableWebsite.svelte';
3
3
+
let { data } = $props();
4
4
+
</script>
5
5
+
6
6
+
<EditableWebsite {data} />
+13
src/routes/[handle=handle]/(pages)/p/[[page]]/+page.svelte
···
1
1
+
<script lang="ts">
2
2
+
import { refreshData } from '$lib/helper.js';
3
3
+
import Website from '$lib/website/Website.svelte';
4
4
+
import { onMount } from 'svelte';
5
5
+
6
6
+
let { data } = $props();
7
7
+
8
8
+
onMount(() => {
9
9
+
refreshData(data);
10
10
+
});
11
11
+
</script>
12
12
+
13
13
+
<Website {data} />
+252
src/routes/[handle=handle]/(pages)/p/[[page]]/copy/+page.svelte
···
1
1
+
<script lang="ts">
2
2
+
import {
3
3
+
putRecord,
4
4
+
deleteRecord,
5
5
+
listRecords,
6
6
+
uploadBlob,
7
7
+
getCDNImageBlobUrl
8
8
+
} from '$lib/atproto/methods';
9
9
+
import { user } from '$lib/atproto/auth.svelte';
10
10
+
import { goto } from '$app/navigation';
11
11
+
import * as TID from '@atcute/tid';
12
12
+
import { Button } from '@foxui/core';
13
13
+
import { loginModalState } from '$lib/atproto/UI/LoginModal.svelte';
14
14
+
15
15
+
let { data } = $props();
16
16
+
17
17
+
let destinationPage = $state('');
18
18
+
let copying = $state(false);
19
19
+
let error = $state('');
20
20
+
let success = $state(false);
21
21
+
22
22
+
const sourceHandle = $derived(data.handle);
23
23
+
24
24
+
const sourcePage = $derived(
25
25
+
data.page === 'blento.self' ? 'main' : data.page.replace('blento.', '')
26
26
+
);
27
27
+
const sourceCards = $derived(data.cards);
28
28
+
29
29
+
// Re-upload blobs from source repo to current user's repo
30
30
+
async function reuploadBlobs(obj: any, sourceDid: string): Promise<void> {
31
31
+
if (!obj || typeof obj !== 'object') return;
32
32
+
33
33
+
for (const key of Object.keys(obj)) {
34
34
+
const value = obj[key];
35
35
+
36
36
+
if (value && typeof value === 'object') {
37
37
+
// Check if this is a blob reference
38
38
+
if (value.$type === 'blob' && value.ref?.$link) {
39
39
+
try {
40
40
+
// Get the blob URL from source repo
41
41
+
const blobUrl = getCDNImageBlobUrl({ did: sourceDid, blob: value });
42
42
+
if (!blobUrl) continue;
43
43
+
44
44
+
// Fetch the blob via proxy to avoid CORS
45
45
+
const response = await fetch(`/api/image-proxy?url=${encodeURIComponent(blobUrl)}`);
46
46
+
if (!response.ok) {
47
47
+
console.error('Failed to fetch blob:', blobUrl);
48
48
+
continue;
49
49
+
}
50
50
+
51
51
+
// Upload to current user's repo
52
52
+
const blob = await response.blob();
53
53
+
const newBlobRef = await uploadBlob({ blob });
54
54
+
55
55
+
if (newBlobRef) {
56
56
+
// Replace with new blob reference
57
57
+
obj[key] = newBlobRef;
58
58
+
}
59
59
+
} catch (err) {
60
60
+
console.error('Failed to re-upload blob:', err);
61
61
+
}
62
62
+
} else {
63
63
+
// Recursively check nested objects
64
64
+
await reuploadBlobs(value, sourceDid);
65
65
+
}
66
66
+
}
67
67
+
}
68
68
+
}
69
69
+
70
70
+
async function copyPage() {
71
71
+
if (!user.isLoggedIn || !user.did) {
72
72
+
error = 'You must be logged in to copy pages';
73
73
+
return;
74
74
+
}
75
75
+
76
76
+
copying = true;
77
77
+
error = '';
78
78
+
79
79
+
try {
80
80
+
const targetPage =
81
81
+
destinationPage.trim() === '' ? 'blento.self' : `blento.${destinationPage.trim()}`;
82
82
+
83
83
+
// Fetch existing cards from destination page and delete them
84
84
+
const existingCards = await listRecords({
85
85
+
did: user.did,
86
86
+
collection: 'app.blento.card'
87
87
+
});
88
88
+
89
89
+
const cardsToDelete = existingCards.filter(
90
90
+
(card: { value: { page?: string } }) => card.value.page === targetPage
91
91
+
);
92
92
+
93
93
+
// Delete existing cards from destination page
94
94
+
const deletePromises = cardsToDelete.map((card: { uri: string }) => {
95
95
+
const rkey = card.uri.split('/').pop()!;
96
96
+
return deleteRecord({
97
97
+
collection: 'app.blento.card',
98
98
+
rkey
99
99
+
});
100
100
+
});
101
101
+
102
102
+
await Promise.all(deletePromises);
103
103
+
104
104
+
// Copy each card with a new ID to the destination page
105
105
+
// Re-upload blobs from source repo to current user's repo
106
106
+
for (const card of sourceCards) {
107
107
+
const newCard = {
108
108
+
...structuredClone(card),
109
109
+
id: TID.now(),
110
110
+
page: targetPage,
111
111
+
updatedAt: new Date().toISOString(),
112
112
+
version: 2
113
113
+
};
114
114
+
115
115
+
// Re-upload any blobs in cardData
116
116
+
await reuploadBlobs(newCard.cardData, data.did);
117
117
+
118
118
+
await putRecord({
119
119
+
collection: 'app.blento.card',
120
120
+
rkey: newCard.id,
121
121
+
record: newCard
122
122
+
});
123
123
+
}
124
124
+
125
125
+
const userHandle = user.profile?.handle ?? data.handle;
126
126
+
127
127
+
// Copy publication data if it exists
128
128
+
if (data.publication) {
129
129
+
const publicationCopy = structuredClone(data.publication) as Record<string, unknown>;
130
130
+
131
131
+
// Re-upload any blobs in publication (e.g., icon)
132
132
+
await reuploadBlobs(publicationCopy, data.did);
133
133
+
134
134
+
// Update the URL to point to the user's page
135
135
+
publicationCopy.url = `https://blento.app/${userHandle}`;
136
136
+
if (targetPage !== 'blento.self') {
137
137
+
publicationCopy.url += '/' + targetPage.replace('blento.', '');
138
138
+
}
139
139
+
140
140
+
// Save to appropriate collection based on destination page type
141
141
+
if (targetPage === 'blento.self') {
142
142
+
await putRecord({
143
143
+
collection: 'site.standard.publication',
144
144
+
rkey: targetPage,
145
145
+
record: publicationCopy
146
146
+
});
147
147
+
} else {
148
148
+
await putRecord({
149
149
+
collection: 'app.blento.page',
150
150
+
rkey: targetPage,
151
151
+
record: publicationCopy
152
152
+
});
153
153
+
}
154
154
+
}
155
155
+
156
156
+
// Refresh the logged-in user's cache
157
157
+
await fetch(`/${userHandle}/api/refresh`);
158
158
+
159
159
+
success = true;
160
160
+
161
161
+
// Redirect to the logged-in user's destination page edit
162
162
+
const destPath = destinationPage.trim() === '' ? '' : `/${destinationPage.trim()}`;
163
163
+
setTimeout(() => {
164
164
+
goto(`/${userHandle}${destPath}/edit`);
165
165
+
}, 1000);
166
166
+
} catch (e) {
167
167
+
error = e instanceof Error ? e.message : 'Failed to copy page';
168
168
+
} finally {
169
169
+
copying = false;
170
170
+
}
171
171
+
}
172
172
+
</script>
173
173
+
174
174
+
<div class="bg-base-50 dark:bg-base-900 flex min-h-screen items-center justify-center p-4">
175
175
+
<div class="bg-base-100 dark:bg-base-800 w-full max-w-md rounded-2xl p-6 shadow-lg">
176
176
+
{#if user.isLoggedIn}
177
177
+
<h1 class="text-base-900 dark:text-base-50 mb-6 text-2xl font-bold">Copy Page</h1>
178
178
+
179
179
+
<div class="mb-4">
180
180
+
<div class="text-base-700 dark:text-base-300 mb-1 block text-sm font-medium">
181
181
+
Source Page
182
182
+
</div>
183
183
+
<div
184
184
+
class="bg-base-200 dark:bg-base-700 text-base-900 dark:text-base-100 rounded-lg px-3 py-2"
185
185
+
>
186
186
+
{sourceHandle}/{sourcePage || 'main'}
187
187
+
</div>
188
188
+
<p class="text-base-500 mt-1 text-sm">{sourceCards.length} cards</p>
189
189
+
</div>
190
190
+
191
191
+
<div class="mb-6">
192
192
+
<label
193
193
+
for="destination"
194
194
+
class="text-base-700 dark:text-base-300 mb-1 block text-sm font-medium"
195
195
+
>
196
196
+
Destination Page (on your profile: {user.profile?.handle})
197
197
+
</label>
198
198
+
<input
199
199
+
id="destination"
200
200
+
type="text"
201
201
+
bind:value={destinationPage}
202
202
+
placeholder="Leave empty for main page"
203
203
+
class="bg-base-50 dark:bg-base-700 border-base-300 dark:border-base-600 text-base-900 dark:text-base-100 focus:ring-accent-500 w-full rounded-lg border px-3 py-2 focus:ring-2 focus:outline-none"
204
204
+
/>
205
205
+
</div>
206
206
+
207
207
+
{#if error}
208
208
+
<div
209
209
+
class="mb-4 rounded-lg bg-red-100 p-3 text-red-700 dark:bg-red-900/30 dark:text-red-400"
210
210
+
>
211
211
+
{error}
212
212
+
</div>
213
213
+
{/if}
214
214
+
215
215
+
{#if success}
216
216
+
<div
217
217
+
class="mb-4 rounded-lg bg-green-100 p-3 text-green-700 dark:bg-green-900/30 dark:text-green-400"
218
218
+
>
219
219
+
Page copied successfully! Redirecting...
220
220
+
</div>
221
221
+
{/if}
222
222
+
223
223
+
<div class="flex gap-3">
224
224
+
<a
225
225
+
href="/{data.handle}/{sourcePage === 'main' ? '' : sourcePage}"
226
226
+
class="bg-base-200 hover:bg-base-300 dark:bg-base-700 dark:hover:bg-base-600 text-base-700 dark:text-base-300 flex-1 rounded-lg px-4 py-2 text-center font-medium transition-colors"
227
227
+
>
228
228
+
Cancel
229
229
+
</a>
230
230
+
<button
231
231
+
onclick={copyPage}
232
232
+
disabled={copying || success}
233
233
+
class="bg-accent-500 hover:bg-accent-600 flex-1 rounded-lg px-4 py-2 font-medium text-white transition-colors disabled:cursor-not-allowed disabled:opacity-50"
234
234
+
>
235
235
+
{#if copying}
236
236
+
Copying...
237
237
+
{:else}
238
238
+
Copy {sourceCards.length} cards
239
239
+
{/if}
240
240
+
</button>
241
241
+
</div>
242
242
+
{:else}
243
243
+
<h1 class="text-base-900 dark:text-base-50 mb-6 text-2xl font-bold">
244
244
+
You must be signed in to copy a page!
245
245
+
</h1>
246
246
+
247
247
+
<div class="flex w-full justify-center">
248
248
+
<Button size="lg" onclick={() => loginModalState.show()}>Login</Button>
249
249
+
</div>
250
250
+
{/if}
251
251
+
</div>
252
252
+
</div>
+6
src/routes/[handle=handle]/(pages)/p/[[page]]/edit/+page.svelte
···
1
1
+
<script lang="ts">
2
2
+
import EditableWebsite from '$lib/website/EditableWebsite.svelte';
3
3
+
let { data } = $props();
4
4
+
</script>
5
5
+
6
6
+
<EditableWebsite {data} />
-13
src/routes/[handle=handle]/[[page]]/+layout.server.ts
···
1
1
-
import { loadData } from '$lib/website/load';
2
2
-
import { env } from '$env/dynamic/private';
3
3
-
import { error } from '@sveltejs/kit';
4
4
-
import type { UserCache } from '$lib/types';
5
5
-
import type { Handle } from '@atcute/lexicons';
6
6
-
7
7
-
export async function load({ params, platform }) {
8
8
-
if (env.PUBLIC_IS_SELFHOSTED) error(404);
9
9
-
10
10
-
const cache = platform?.env?.USER_DATA_CACHE as unknown;
11
11
-
12
12
-
return await loadData(params.handle as Handle, cache as UserCache, false, params.page);
13
13
-
}
-13
src/routes/[handle=handle]/[[page]]/+page.svelte
···
1
1
-
<script lang="ts">
2
2
-
import { refreshData } from '$lib/helper.js';
3
3
-
import Website from '$lib/website/Website.svelte';
4
4
-
import { onMount } from 'svelte';
5
5
-
6
6
-
let { data } = $props();
7
7
-
8
8
-
onMount(() => {
9
9
-
refreshData(data);
10
10
-
});
11
11
-
</script>
12
12
-
13
13
-
<Website {data} />
-252
src/routes/[handle=handle]/[[page]]/copy/+page.svelte
···
1
1
-
<script lang="ts">
2
2
-
import {
3
3
-
putRecord,
4
4
-
deleteRecord,
5
5
-
listRecords,
6
6
-
uploadBlob,
7
7
-
getCDNImageBlobUrl
8
8
-
} from '$lib/atproto/methods';
9
9
-
import { user } from '$lib/atproto/auth.svelte';
10
10
-
import { goto } from '$app/navigation';
11
11
-
import * as TID from '@atcute/tid';
12
12
-
import { Button } from '@foxui/core';
13
13
-
import { loginModalState } from '$lib/atproto/UI/LoginModal.svelte';
14
14
-
15
15
-
let { data } = $props();
16
16
-
17
17
-
let destinationPage = $state('');
18
18
-
let copying = $state(false);
19
19
-
let error = $state('');
20
20
-
let success = $state(false);
21
21
-
22
22
-
const sourceHandle = $derived(data.handle);
23
23
-
24
24
-
const sourcePage = $derived(
25
25
-
data.page === 'blento.self' ? 'main' : data.page.replace('blento.', '')
26
26
-
);
27
27
-
const sourceCards = $derived(data.cards);
28
28
-
29
29
-
// Re-upload blobs from source repo to current user's repo
30
30
-
async function reuploadBlobs(obj: any, sourceDid: string): Promise<void> {
31
31
-
if (!obj || typeof obj !== 'object') return;
32
32
-
33
33
-
for (const key of Object.keys(obj)) {
34
34
-
const value = obj[key];
35
35
-
36
36
-
if (value && typeof value === 'object') {
37
37
-
// Check if this is a blob reference
38
38
-
if (value.$type === 'blob' && value.ref?.$link) {
39
39
-
try {
40
40
-
// Get the blob URL from source repo
41
41
-
const blobUrl = getCDNImageBlobUrl({ did: sourceDid, blob: value });
42
42
-
if (!blobUrl) continue;
43
43
-
44
44
-
// Fetch the blob via proxy to avoid CORS
45
45
-
const response = await fetch(`/api/image-proxy?url=${encodeURIComponent(blobUrl)}`);
46
46
-
if (!response.ok) {
47
47
-
console.error('Failed to fetch blob:', blobUrl);
48
48
-
continue;
49
49
-
}
50
50
-
51
51
-
// Upload to current user's repo
52
52
-
const blob = await response.blob();
53
53
-
const newBlobRef = await uploadBlob({ blob });
54
54
-
55
55
-
if (newBlobRef) {
56
56
-
// Replace with new blob reference
57
57
-
obj[key] = newBlobRef;
58
58
-
}
59
59
-
} catch (err) {
60
60
-
console.error('Failed to re-upload blob:', err);
61
61
-
}
62
62
-
} else {
63
63
-
// Recursively check nested objects
64
64
-
await reuploadBlobs(value, sourceDid);
65
65
-
}
66
66
-
}
67
67
-
}
68
68
-
}
69
69
-
70
70
-
async function copyPage() {
71
71
-
if (!user.isLoggedIn || !user.did) {
72
72
-
error = 'You must be logged in to copy pages';
73
73
-
return;
74
74
-
}
75
75
-
76
76
-
copying = true;
77
77
-
error = '';
78
78
-
79
79
-
try {
80
80
-
const targetPage =
81
81
-
destinationPage.trim() === '' ? 'blento.self' : `blento.${destinationPage.trim()}`;
82
82
-
83
83
-
// Fetch existing cards from destination page and delete them
84
84
-
const existingCards = await listRecords({
85
85
-
did: user.did,
86
86
-
collection: 'app.blento.card'
87
87
-
});
88
88
-
89
89
-
const cardsToDelete = existingCards.filter(
90
90
-
(card: { value: { page?: string } }) => card.value.page === targetPage
91
91
-
);
92
92
-
93
93
-
// Delete existing cards from destination page
94
94
-
const deletePromises = cardsToDelete.map((card: { uri: string }) => {
95
95
-
const rkey = card.uri.split('/').pop()!;
96
96
-
return deleteRecord({
97
97
-
collection: 'app.blento.card',
98
98
-
rkey
99
99
-
});
100
100
-
});
101
101
-
102
102
-
await Promise.all(deletePromises);
103
103
-
104
104
-
// Copy each card with a new ID to the destination page
105
105
-
// Re-upload blobs from source repo to current user's repo
106
106
-
for (const card of sourceCards) {
107
107
-
const newCard = {
108
108
-
...structuredClone(card),
109
109
-
id: TID.now(),
110
110
-
page: targetPage,
111
111
-
updatedAt: new Date().toISOString(),
112
112
-
version: 2
113
113
-
};
114
114
-
115
115
-
// Re-upload any blobs in cardData
116
116
-
await reuploadBlobs(newCard.cardData, data.did);
117
117
-
118
118
-
await putRecord({
119
119
-
collection: 'app.blento.card',
120
120
-
rkey: newCard.id,
121
121
-
record: newCard
122
122
-
});
123
123
-
}
124
124
-
125
125
-
const userHandle = user.profile?.handle ?? data.handle;
126
126
-
127
127
-
// Copy publication data if it exists
128
128
-
if (data.publication) {
129
129
-
const publicationCopy = structuredClone(data.publication) as Record<string, unknown>;
130
130
-
131
131
-
// Re-upload any blobs in publication (e.g., icon)
132
132
-
await reuploadBlobs(publicationCopy, data.did);
133
133
-
134
134
-
// Update the URL to point to the user's page
135
135
-
publicationCopy.url = `https://blento.app/${userHandle}`;
136
136
-
if (targetPage !== 'blento.self') {
137
137
-
publicationCopy.url += '/' + targetPage.replace('blento.', '');
138
138
-
}
139
139
-
140
140
-
// Save to appropriate collection based on destination page type
141
141
-
if (targetPage === 'blento.self') {
142
142
-
await putRecord({
143
143
-
collection: 'site.standard.publication',
144
144
-
rkey: targetPage,
145
145
-
record: publicationCopy
146
146
-
});
147
147
-
} else {
148
148
-
await putRecord({
149
149
-
collection: 'app.blento.page',
150
150
-
rkey: targetPage,
151
151
-
record: publicationCopy
152
152
-
});
153
153
-
}
154
154
-
}
155
155
-
156
156
-
// Refresh the logged-in user's cache
157
157
-
await fetch(`/${userHandle}/api/refresh`);
158
158
-
159
159
-
success = true;
160
160
-
161
161
-
// Redirect to the logged-in user's destination page edit
162
162
-
const destPath = destinationPage.trim() === '' ? '' : `/${destinationPage.trim()}`;
163
163
-
setTimeout(() => {
164
164
-
goto(`/${userHandle}${destPath}/edit`);
165
165
-
}, 1000);
166
166
-
} catch (e) {
167
167
-
error = e instanceof Error ? e.message : 'Failed to copy page';
168
168
-
} finally {
169
169
-
copying = false;
170
170
-
}
171
171
-
}
172
172
-
</script>
173
173
-
174
174
-
<div class="bg-base-50 dark:bg-base-900 flex min-h-screen items-center justify-center p-4">
175
175
-
<div class="bg-base-100 dark:bg-base-800 w-full max-w-md rounded-2xl p-6 shadow-lg">
176
176
-
{#if user.isLoggedIn}
177
177
-
<h1 class="text-base-900 dark:text-base-50 mb-6 text-2xl font-bold">Copy Page</h1>
178
178
-
179
179
-
<div class="mb-4">
180
180
-
<div class="text-base-700 dark:text-base-300 mb-1 block text-sm font-medium">
181
181
-
Source Page
182
182
-
</div>
183
183
-
<div
184
184
-
class="bg-base-200 dark:bg-base-700 text-base-900 dark:text-base-100 rounded-lg px-3 py-2"
185
185
-
>
186
186
-
{sourceHandle}/{sourcePage || 'main'}
187
187
-
</div>
188
188
-
<p class="text-base-500 mt-1 text-sm">{sourceCards.length} cards</p>
189
189
-
</div>
190
190
-
191
191
-
<div class="mb-6">
192
192
-
<label
193
193
-
for="destination"
194
194
-
class="text-base-700 dark:text-base-300 mb-1 block text-sm font-medium"
195
195
-
>
196
196
-
Destination Page (on your profile: {user.profile?.handle})
197
197
-
</label>
198
198
-
<input
199
199
-
id="destination"
200
200
-
type="text"
201
201
-
bind:value={destinationPage}
202
202
-
placeholder="Leave empty for main page"
203
203
-
class="bg-base-50 dark:bg-base-700 border-base-300 dark:border-base-600 text-base-900 dark:text-base-100 focus:ring-accent-500 w-full rounded-lg border px-3 py-2 focus:ring-2 focus:outline-none"
204
204
-
/>
205
205
-
</div>
206
206
-
207
207
-
{#if error}
208
208
-
<div
209
209
-
class="mb-4 rounded-lg bg-red-100 p-3 text-red-700 dark:bg-red-900/30 dark:text-red-400"
210
210
-
>
211
211
-
{error}
212
212
-
</div>
213
213
-
{/if}
214
214
-
215
215
-
{#if success}
216
216
-
<div
217
217
-
class="mb-4 rounded-lg bg-green-100 p-3 text-green-700 dark:bg-green-900/30 dark:text-green-400"
218
218
-
>
219
219
-
Page copied successfully! Redirecting...
220
220
-
</div>
221
221
-
{/if}
222
222
-
223
223
-
<div class="flex gap-3">
224
224
-
<a
225
225
-
href="/{data.handle}/{sourcePage === 'main' ? '' : sourcePage}"
226
226
-
class="bg-base-200 hover:bg-base-300 dark:bg-base-700 dark:hover:bg-base-600 text-base-700 dark:text-base-300 flex-1 rounded-lg px-4 py-2 text-center font-medium transition-colors"
227
227
-
>
228
228
-
Cancel
229
229
-
</a>
230
230
-
<button
231
231
-
onclick={copyPage}
232
232
-
disabled={copying || success}
233
233
-
class="bg-accent-500 hover:bg-accent-600 flex-1 rounded-lg px-4 py-2 font-medium text-white transition-colors disabled:cursor-not-allowed disabled:opacity-50"
234
234
-
>
235
235
-
{#if copying}
236
236
-
Copying...
237
237
-
{:else}
238
238
-
Copy {sourceCards.length} cards
239
239
-
{/if}
240
240
-
</button>
241
241
-
</div>
242
242
-
{:else}
243
243
-
<h1 class="text-base-900 dark:text-base-50 mb-6 text-2xl font-bold">
244
244
-
You must be signed in to copy a page!
245
245
-
</h1>
246
246
-
247
247
-
<div class="flex w-full justify-center">
248
248
-
<Button size="lg" onclick={() => loginModalState.show()}>Login</Button>
249
249
-
</div>
250
250
-
{/if}
251
251
-
</div>
252
252
-
</div>
-6
src/routes/[handle=handle]/[[page]]/edit/+page.svelte
···
1
1
-
<script lang="ts">
2
2
-
import EditableWebsite from '$lib/website/EditableWebsite.svelte';
3
3
-
let { data } = $props();
4
4
-
</script>
5
5
-
6
6
-
<EditableWebsite {data} />
+89
src/routes/api/lastfm/+server.ts
···
1
1
+
import { json } from '@sveltejs/kit';
2
2
+
import type { RequestHandler } from './$types';
3
3
+
import { env } from '$env/dynamic/private';
4
4
+
5
5
+
const LASTFM_API_URL = 'https://ws.audioscrobbler.com/2.0/';
6
6
+
7
7
+
const ALLOWED_METHODS = [
8
8
+
'user.getRecentTracks',
9
9
+
'user.getTopTracks',
10
10
+
'user.getTopAlbums',
11
11
+
'user.getInfo'
12
12
+
];
13
13
+
14
14
+
const CACHE_TTL: Record<string, number> = {
15
15
+
'user.getRecentTracks': 15 * 60 * 1000,
16
16
+
'user.getTopTracks': 60 * 60 * 1000,
17
17
+
'user.getTopAlbums': 60 * 60 * 1000,
18
18
+
'user.getInfo': 12 * 60 * 60 * 1000
19
19
+
};
20
20
+
21
21
+
export const GET: RequestHandler = async ({ url, platform }) => {
22
22
+
const method = url.searchParams.get('method');
23
23
+
const user = url.searchParams.get('user');
24
24
+
const period = url.searchParams.get('period') || '7day';
25
25
+
const limit = url.searchParams.get('limit') || '50';
26
26
+
27
27
+
if (!method || !user) {
28
28
+
return json({ error: 'Missing method or user parameter' }, { status: 400 });
29
29
+
}
30
30
+
31
31
+
if (!ALLOWED_METHODS.includes(method)) {
32
32
+
return json({ error: 'Method not allowed' }, { status: 400 });
33
33
+
}
34
34
+
35
35
+
const cacheKey = `#lastfm:${method}:${user}:${period}:${limit}`;
36
36
+
const cachedData = await platform?.env?.USER_DATA_CACHE?.get(cacheKey);
37
37
+
38
38
+
if (cachedData) {
39
39
+
const parsed = JSON.parse(cachedData);
40
40
+
const ttl = CACHE_TTL[method] || 60 * 60 * 1000;
41
41
+
42
42
+
if (Date.now() - (parsed._cachedAt || 0) < ttl) {
43
43
+
return json(parsed);
44
44
+
}
45
45
+
}
46
46
+
47
47
+
const apiKey = env?.LASTFM_API_KEY;
48
48
+
if (!apiKey) {
49
49
+
return json({ error: 'Last.fm API key not configured' }, { status: 500 });
50
50
+
}
51
51
+
52
52
+
try {
53
53
+
const params = new URLSearchParams({
54
54
+
method,
55
55
+
user,
56
56
+
api_key: apiKey,
57
57
+
format: 'json',
58
58
+
limit
59
59
+
});
60
60
+
61
61
+
if (method === 'user.getTopTracks' || method === 'user.getTopAlbums') {
62
62
+
params.set('period', period);
63
63
+
}
64
64
+
65
65
+
const response = await fetch(`${LASTFM_API_URL}?${params}`);
66
66
+
67
67
+
if (!response.ok) {
68
68
+
return json(
69
69
+
{ error: 'Failed to fetch Last.fm data: ' + response.statusText },
70
70
+
{ status: response.status }
71
71
+
);
72
72
+
}
73
73
+
74
74
+
const data = await response.json();
75
75
+
76
76
+
if (data.error) {
77
77
+
return json({ error: data.message || 'Last.fm API error' }, { status: 400 });
78
78
+
}
79
79
+
80
80
+
data._cachedAt = Date.now();
81
81
+
82
82
+
await platform?.env?.USER_DATA_CACHE?.put(cacheKey, JSON.stringify(data));
83
83
+
84
84
+
return json(data);
85
85
+
} catch (error) {
86
86
+
console.error('Error fetching Last.fm data:', error);
87
87
+
return json({ error: 'Failed to fetch Last.fm data' }, { status: 500 });
88
88
+
}
89
89
+
};
+25
src/routes/p/[[page]]/+layout.server.ts
···
1
1
+
import { loadData } from '$lib/website/load';
2
2
+
import { env } from '$env/dynamic/public';
3
3
+
import type { UserCache } from '$lib/types';
4
4
+
import type { Did, Handle } from '@atcute/lexicons';
5
5
+
6
6
+
export async function load({ params, platform, request }) {
7
7
+
const cache = platform?.env?.USER_DATA_CACHE as unknown;
8
8
+
9
9
+
const handle = env.PUBLIC_HANDLE;
10
10
+
11
11
+
const kv = platform?.env?.CUSTOM_DOMAINS;
12
12
+
13
13
+
const customDomain = request.headers.get('X-Custom-Domain')?.toLocaleLowerCase();
14
14
+
15
15
+
if (kv && customDomain) {
16
16
+
try {
17
17
+
const did = await kv.get(customDomain);
18
18
+
return await loadData(did as Did, cache as UserCache, false, params.page);
19
19
+
} catch {
20
20
+
console.error('failed');
21
21
+
}
22
22
+
}
23
23
+
24
24
+
return await loadData(handle as Handle, cache as UserCache, false, params.page);
25
25
+
}
+13
src/routes/p/[[page]]/+page.svelte
···
1
1
+
<script lang="ts">
2
2
+
import { refreshData } from '$lib/helper.js';
3
3
+
import Website from '$lib/website/Website.svelte';
4
4
+
import { onMount } from 'svelte';
5
5
+
6
6
+
let { data } = $props();
7
7
+
8
8
+
onMount(() => {
9
9
+
refreshData(data);
10
10
+
});
11
11
+
</script>
12
12
+
13
13
+
<Website {data} />
+252
src/routes/p/[[page]]/copy/+page.svelte
···
1
1
+
<script lang="ts">
2
2
+
import {
3
3
+
putRecord,
4
4
+
deleteRecord,
5
5
+
listRecords,
6
6
+
uploadBlob,
7
7
+
getCDNImageBlobUrl
8
8
+
} from '$lib/atproto/methods';
9
9
+
import { user } from '$lib/atproto/auth.svelte';
10
10
+
import { goto } from '$app/navigation';
11
11
+
import * as TID from '@atcute/tid';
12
12
+
import { Button } from '@foxui/core';
13
13
+
import { loginModalState } from '$lib/atproto/UI/LoginModal.svelte';
14
14
+
15
15
+
let { data } = $props();
16
16
+
17
17
+
let destinationPage = $state('');
18
18
+
let copying = $state(false);
19
19
+
let error = $state('');
20
20
+
let success = $state(false);
21
21
+
22
22
+
const sourceHandle = $derived(data.handle);
23
23
+
24
24
+
const sourcePage = $derived(
25
25
+
data.page === 'blento.self' ? 'main' : data.page.replace('blento.', '')
26
26
+
);
27
27
+
const sourceCards = $derived(data.cards);
28
28
+
29
29
+
// Re-upload blobs from source repo to current user's repo
30
30
+
async function reuploadBlobs(obj: any, sourceDid: string): Promise<void> {
31
31
+
if (!obj || typeof obj !== 'object') return;
32
32
+
33
33
+
for (const key of Object.keys(obj)) {
34
34
+
const value = obj[key];
35
35
+
36
36
+
if (value && typeof value === 'object') {
37
37
+
// Check if this is a blob reference
38
38
+
if (value.$type === 'blob' && value.ref?.$link) {
39
39
+
try {
40
40
+
// Get the blob URL from source repo
41
41
+
const blobUrl = getCDNImageBlobUrl({ did: sourceDid, blob: value });
42
42
+
if (!blobUrl) continue;
43
43
+
44
44
+
// Fetch the blob via proxy to avoid CORS
45
45
+
const response = await fetch(`/api/image-proxy?url=${encodeURIComponent(blobUrl)}`);
46
46
+
if (!response.ok) {
47
47
+
console.error('Failed to fetch blob:', blobUrl);
48
48
+
continue;
49
49
+
}
50
50
+
51
51
+
// Upload to current user's repo
52
52
+
const blob = await response.blob();
53
53
+
const newBlobRef = await uploadBlob({ blob });
54
54
+
55
55
+
if (newBlobRef) {
56
56
+
// Replace with new blob reference
57
57
+
obj[key] = newBlobRef;
58
58
+
}
59
59
+
} catch (err) {
60
60
+
console.error('Failed to re-upload blob:', err);
61
61
+
}
62
62
+
} else {
63
63
+
// Recursively check nested objects
64
64
+
await reuploadBlobs(value, sourceDid);
65
65
+
}
66
66
+
}
67
67
+
}
68
68
+
}
69
69
+
70
70
+
async function copyPage() {
71
71
+
if (!user.isLoggedIn || !user.did) {
72
72
+
error = 'You must be logged in to copy pages';
73
73
+
return;
74
74
+
}
75
75
+
76
76
+
copying = true;
77
77
+
error = '';
78
78
+
79
79
+
try {
80
80
+
const targetPage =
81
81
+
destinationPage.trim() === '' ? 'blento.self' : `blento.${destinationPage.trim()}`;
82
82
+
83
83
+
// Fetch existing cards from destination page and delete them
84
84
+
const existingCards = await listRecords({
85
85
+
did: user.did,
86
86
+
collection: 'app.blento.card'
87
87
+
});
88
88
+
89
89
+
const cardsToDelete = existingCards.filter(
90
90
+
(card: { value: { page?: string } }) => card.value.page === targetPage
91
91
+
);
92
92
+
93
93
+
// Delete existing cards from destination page
94
94
+
const deletePromises = cardsToDelete.map((card: { uri: string }) => {
95
95
+
const rkey = card.uri.split('/').pop()!;
96
96
+
return deleteRecord({
97
97
+
collection: 'app.blento.card',
98
98
+
rkey
99
99
+
});
100
100
+
});
101
101
+
102
102
+
await Promise.all(deletePromises);
103
103
+
104
104
+
// Copy each card with a new ID to the destination page
105
105
+
// Re-upload blobs from source repo to current user's repo
106
106
+
for (const card of sourceCards) {
107
107
+
const newCard = {
108
108
+
...structuredClone(card),
109
109
+
id: TID.now(),
110
110
+
page: targetPage,
111
111
+
updatedAt: new Date().toISOString(),
112
112
+
version: 2
113
113
+
};
114
114
+
115
115
+
// Re-upload any blobs in cardData
116
116
+
await reuploadBlobs(newCard.cardData, data.did);
117
117
+
118
118
+
await putRecord({
119
119
+
collection: 'app.blento.card',
120
120
+
rkey: newCard.id,
121
121
+
record: newCard
122
122
+
});
123
123
+
}
124
124
+
125
125
+
const userHandle = user.profile?.handle ?? data.handle;
126
126
+
127
127
+
// Copy publication data if it exists
128
128
+
if (data.publication) {
129
129
+
const publicationCopy = structuredClone(data.publication) as Record<string, unknown>;
130
130
+
131
131
+
// Re-upload any blobs in publication (e.g., icon)
132
132
+
await reuploadBlobs(publicationCopy, data.did);
133
133
+
134
134
+
// Update the URL to point to the user's page
135
135
+
publicationCopy.url = `https://blento.app/${userHandle}`;
136
136
+
if (targetPage !== 'blento.self') {
137
137
+
publicationCopy.url += '/' + targetPage.replace('blento.', '');
138
138
+
}
139
139
+
140
140
+
// Save to appropriate collection based on destination page type
141
141
+
if (targetPage === 'blento.self') {
142
142
+
await putRecord({
143
143
+
collection: 'site.standard.publication',
144
144
+
rkey: targetPage,
145
145
+
record: publicationCopy
146
146
+
});
147
147
+
} else {
148
148
+
await putRecord({
149
149
+
collection: 'app.blento.page',
150
150
+
rkey: targetPage,
151
151
+
record: publicationCopy
152
152
+
});
153
153
+
}
154
154
+
}
155
155
+
156
156
+
// Refresh the logged-in user's cache
157
157
+
await fetch(`/${userHandle}/api/refresh`);
158
158
+
159
159
+
success = true;
160
160
+
161
161
+
// Redirect to the logged-in user's destination page edit
162
162
+
const destPath = destinationPage.trim() === '' ? '' : `/${destinationPage.trim()}`;
163
163
+
setTimeout(() => {
164
164
+
goto(`/${userHandle}${destPath}/edit`);
165
165
+
}, 1000);
166
166
+
} catch (e) {
167
167
+
error = e instanceof Error ? e.message : 'Failed to copy page';
168
168
+
} finally {
169
169
+
copying = false;
170
170
+
}
171
171
+
}
172
172
+
</script>
173
173
+
174
174
+
<div class="bg-base-50 dark:bg-base-900 flex min-h-screen items-center justify-center p-4">
175
175
+
<div class="bg-base-100 dark:bg-base-800 w-full max-w-md rounded-2xl p-6 shadow-lg">
176
176
+
{#if user.isLoggedIn}
177
177
+
<h1 class="text-base-900 dark:text-base-50 mb-6 text-2xl font-bold">Copy Page</h1>
178
178
+
179
179
+
<div class="mb-4">
180
180
+
<div class="text-base-700 dark:text-base-300 mb-1 block text-sm font-medium">
181
181
+
Source Page
182
182
+
</div>
183
183
+
<div
184
184
+
class="bg-base-200 dark:bg-base-700 text-base-900 dark:text-base-100 rounded-lg px-3 py-2"
185
185
+
>
186
186
+
{sourceHandle}/{sourcePage || 'main'}
187
187
+
</div>
188
188
+
<p class="text-base-500 mt-1 text-sm">{sourceCards.length} cards</p>
189
189
+
</div>
190
190
+
191
191
+
<div class="mb-6">
192
192
+
<label
193
193
+
for="destination"
194
194
+
class="text-base-700 dark:text-base-300 mb-1 block text-sm font-medium"
195
195
+
>
196
196
+
Destination Page (on your profile: {user.profile?.handle})
197
197
+
</label>
198
198
+
<input
199
199
+
id="destination"
200
200
+
type="text"
201
201
+
bind:value={destinationPage}
202
202
+
placeholder="Leave empty for main page"
203
203
+
class="bg-base-50 dark:bg-base-700 border-base-300 dark:border-base-600 text-base-900 dark:text-base-100 focus:ring-accent-500 w-full rounded-lg border px-3 py-2 focus:ring-2 focus:outline-none"
204
204
+
/>
205
205
+
</div>
206
206
+
207
207
+
{#if error}
208
208
+
<div
209
209
+
class="mb-4 rounded-lg bg-red-100 p-3 text-red-700 dark:bg-red-900/30 dark:text-red-400"
210
210
+
>
211
211
+
{error}
212
212
+
</div>
213
213
+
{/if}
214
214
+
215
215
+
{#if success}
216
216
+
<div
217
217
+
class="mb-4 rounded-lg bg-green-100 p-3 text-green-700 dark:bg-green-900/30 dark:text-green-400"
218
218
+
>
219
219
+
Page copied successfully! Redirecting...
220
220
+
</div>
221
221
+
{/if}
222
222
+
223
223
+
<div class="flex gap-3">
224
224
+
<a
225
225
+
href="/{data.handle}/{sourcePage === 'main' ? '' : sourcePage}"
226
226
+
class="bg-base-200 hover:bg-base-300 dark:bg-base-700 dark:hover:bg-base-600 text-base-700 dark:text-base-300 flex-1 rounded-lg px-4 py-2 text-center font-medium transition-colors"
227
227
+
>
228
228
+
Cancel
229
229
+
</a>
230
230
+
<button
231
231
+
onclick={copyPage}
232
232
+
disabled={copying || success}
233
233
+
class="bg-accent-500 hover:bg-accent-600 flex-1 rounded-lg px-4 py-2 font-medium text-white transition-colors disabled:cursor-not-allowed disabled:opacity-50"
234
234
+
>
235
235
+
{#if copying}
236
236
+
Copying...
237
237
+
{:else}
238
238
+
Copy {sourceCards.length} cards
239
239
+
{/if}
240
240
+
</button>
241
241
+
</div>
242
242
+
{:else}
243
243
+
<h1 class="text-base-900 dark:text-base-50 mb-6 text-2xl font-bold">
244
244
+
You must be signed in to copy a page!
245
245
+
</h1>
246
246
+
247
247
+
<div class="flex w-full justify-center">
248
248
+
<Button size="lg" onclick={() => loginModalState.show()}>Login</Button>
249
249
+
</div>
250
250
+
{/if}
251
251
+
</div>
252
252
+
</div>
+6
src/routes/p/[[page]]/edit/+page.svelte
···
1
1
+
<script lang="ts">
2
2
+
import EditableWebsite from '$lib/website/EditableWebsite.svelte';
3
3
+
let { data } = $props();
4
4
+
</script>
5
5
+
6
6
+
<EditableWebsite {data} />