your personal website on atproto - mirror
blento.app
1import type { Item, WebsiteData } from './types';
2import { COLUMNS, margin, mobileMargin } from '$lib';
3import { CardDefinitionsByType } from './cards';
4import { deleteRecord, getImageBlobUrl, putRecord, uploadBlob } from '$lib/atproto';
5import { toast } from '@foxui/core';
6import * as TID from '@atcute/tid';
7
8export function clamp(value: number, min: number, max: number): number {
9 return Math.min(Math.max(value, min), max);
10}
11
12export const colors = [
13 'bg-red-500',
14 'bg-orange-500',
15 'bg-amber-500',
16 'bg-yellow-500',
17 'bg-lime-500',
18 'bg-green-500',
19 'bg-emerald-500',
20 'bg-teal-500',
21 'bg-cyan-500',
22 'bg-sky-500',
23 'bg-blue-500',
24 'bg-indigo-500',
25 'bg-violet-500',
26 'bg-purple-500',
27 'bg-fuchsia-500',
28 'bg-pink-500',
29 'bg-rose-500'
30];
31
32export const overlaps = (a: Item, b: Item, mobile: boolean = false) => {
33 if (a === b) return false;
34 if (mobile) {
35 return (
36 a.mobileX < b.mobileX + b.mobileW &&
37 a.mobileX + a.mobileW > b.mobileX &&
38 a.mobileY < b.mobileY + b.mobileH &&
39 a.mobileY + a.mobileH > b.mobileY
40 );
41 }
42 return a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;
43};
44
45export function fixCollisions(
46 items: Item[],
47 movedItem: Item,
48 mobile: boolean = false,
49 skipCompact: boolean = false
50) {
51 const clampX = (item: Item) => {
52 if (mobile) item.mobileX = clamp(item.mobileX, 0, COLUMNS - item.mobileW);
53 else item.x = clamp(item.x, 0, COLUMNS - item.w);
54 };
55
56 // Push `target` down until it no longer overlaps with any item (including movedItem),
57 // while keeping target.x fixed. Any item we collide with gets pushed down first (cascade).
58 const pushDownCascade = (target: Item, blocker: Item) => {
59 // Keep x fixed always when pushing down
60 const fixedX = mobile ? target.mobileX : target.x;
61
62 // We need target to move just below `blocker`
63 const desiredY = mobile ? blocker.mobileY + blocker.mobileH : blocker.y + blocker.h;
64 if (!mobile && target.y < desiredY) target.y = desiredY;
65 if (mobile && target.mobileY < desiredY) target.mobileY = desiredY;
66
67 // Now resolve any collisions that creates by pushing those items down first
68 // Repeat until target is clean.
69 while (true) {
70 const hit = items.find((it) => it !== target && overlaps(target, it, mobile));
71 if (!hit) break;
72
73 // push the hit item down first (cascade), keeping its x fixed
74 pushDownCascade(hit, target);
75
76 // after moving the hit item, target.x must remain fixed
77 if (mobile) target.mobileX = fixedX;
78 else target.x = fixedX;
79 }
80 };
81
82 // Ensure moved item is in bounds
83 clampX(movedItem);
84
85 // Find all items colliding with movedItem, and push them down in a stable order:
86 // top-to-bottom so you get the nice chain reaction (0,0 -> 0,1 -> 0,2).
87 const colliders = items
88 .filter((it) => it !== movedItem && overlaps(movedItem, it, mobile))
89 .toSorted((a, b) =>
90 mobile ? a.mobileY - b.mobileY || a.mobileX - b.mobileX : a.y - b.y || a.x - b.x
91 );
92
93 for (const it of colliders) {
94 // keep x clamped, but do NOT change x during push (we rely on fixed x)
95 clampX(it);
96
97 // push it down just below movedItem; cascade handles the rest
98 pushDownCascade(it, movedItem);
99
100 // enforce "x stays the same" during pushing (clamp already applied)
101 if (mobile) it.mobileX = clamp(it.mobileX, 0, COLUMNS - it.mobileW);
102 else it.x = clamp(it.x, 0, COLUMNS - it.w);
103 }
104
105 if (!skipCompact) {
106 compactItems(items, mobile);
107 }
108}
109
110// Fix all collisions between items (not just one moved item)
111// Items higher on the page have priority and stay in place
112export function fixAllCollisions(items: Item[], mobile: boolean = false) {
113 // Sort by Y position (top-to-bottom, then left-to-right)
114 // Items at the top have priority and won't be moved
115 const sortedItems = items.toSorted((a, b) =>
116 mobile ? a.mobileY - b.mobileY || a.mobileX - b.mobileX : a.y - b.y || a.x - b.x
117 );
118
119 // Process each item and push it down if it overlaps with any item above it
120 for (let i = 0; i < sortedItems.length; i++) {
121 const item = sortedItems[i];
122
123 // Clamp X to valid range
124 if (mobile) {
125 item.mobileX = clamp(item.mobileX, 0, COLUMNS - item.mobileW);
126 } else {
127 item.x = clamp(item.x, 0, COLUMNS - item.w);
128 }
129
130 // Check for collisions with all items that come before (higher priority)
131 let hasCollision = true;
132 while (hasCollision) {
133 hasCollision = false;
134 for (let j = 0; j < i; j++) {
135 const other = sortedItems[j];
136 if (overlaps(item, other, mobile)) {
137 // Push item down below the colliding item
138 if (mobile) {
139 item.mobileY = other.mobileY + other.mobileH;
140 } else {
141 item.y = other.y + other.h;
142 }
143 hasCollision = true;
144 break; // Restart collision check from the beginning
145 }
146 }
147 }
148 }
149
150 compactItems(items, mobile);
151}
152
153// Move all items up as far as possible without collisions
154export function compactItems(items: Item[], mobile: boolean = false) {
155 // Sort by Y position (top-to-bottom) so upper items settle first.
156 const sortedItems = items.toSorted((a, b) =>
157 mobile ? a.mobileY - b.mobileY || a.mobileX - b.mobileX : a.y - b.y || a.x - b.x
158 );
159
160 for (const item of sortedItems) {
161 // Try moving item up row by row until we hit y=0 or a collision
162 while (true) {
163 const currentY = mobile ? item.mobileY : item.y;
164 if (currentY <= 0) break;
165
166 // Temporarily move up by 1
167 if (mobile) item.mobileY -= 1;
168 else item.y -= 1;
169
170 // Check for collision with any other item
171 const hasCollision = items.some((other) => other !== item && overlaps(item, other, mobile));
172
173 if (hasCollision) {
174 // Revert the move
175 if (mobile) item.mobileY += 1;
176 else item.y += 1;
177 break;
178 }
179 // No collision, keep the new position and try moving up again
180 }
181 }
182}
183
184// Simulate where an item would end up after fixCollisions + compaction
185export function simulateFinalPosition(
186 items: Item[],
187 movedItem: Item,
188 newX: number,
189 newY: number,
190 mobile: boolean = false
191): { x: number; y: number } {
192 // Deep clone positions for simulation
193 const clonedItems: Item[] = items.map((item) => ({
194 ...item,
195 x: item.x,
196 y: item.y,
197 mobileX: item.mobileX,
198 mobileY: item.mobileY
199 }));
200
201 const clonedMovedItem = clonedItems.find((item) => item.id === movedItem.id);
202 if (!clonedMovedItem) return { x: newX, y: newY };
203
204 // Set the new position
205 if (mobile) {
206 clonedMovedItem.mobileX = newX;
207 clonedMovedItem.mobileY = newY;
208 } else {
209 clonedMovedItem.x = newX;
210 clonedMovedItem.y = newY;
211 }
212
213 // Run fixCollisions on the cloned data
214 fixCollisions(clonedItems, clonedMovedItem, mobile);
215
216 // Return the final position of the moved item
217 return mobile
218 ? { x: clonedMovedItem.mobileX, y: clonedMovedItem.mobileY }
219 : { x: clonedMovedItem.x, y: clonedMovedItem.y };
220}
221
222export function sortItems(a: Item, b: Item) {
223 return a.y * COLUMNS + a.x - b.y * COLUMNS - b.x;
224}
225
226export function cardsEqual(a: Item, b: Item) {
227 return (
228 a.id === b.id &&
229 a.cardType === b.cardType &&
230 JSON.stringify(a.cardData) === JSON.stringify(b.cardData) &&
231 a.w === b.w &&
232 a.h === b.h &&
233 a.mobileW === b.mobileW &&
234 a.mobileH === b.mobileH &&
235 a.x === b.x &&
236 a.y === b.y &&
237 a.mobileX === b.mobileX &&
238 a.mobileY === b.mobileY &&
239 a.color === b.color &&
240 a.page === b.page
241 );
242}
243
244export function setPositionOfNewItem(newItem: Item, items: Item[]) {
245 let foundPosition = false;
246 while (!foundPosition) {
247 for (newItem.x = 0; newItem.x <= COLUMNS - newItem.w; newItem.x++) {
248 const collision = items.find((item) => overlaps(newItem, item));
249 if (!collision) {
250 foundPosition = true;
251 break;
252 }
253 }
254 if (!foundPosition) newItem.y += 1;
255 }
256
257 let foundMobilePosition = false;
258 while (!foundMobilePosition) {
259 for (newItem.mobileX = 0; newItem.mobileX <= COLUMNS - newItem.mobileW; newItem.mobileX += 1) {
260 const collision = items.find((item) => overlaps(newItem, item, true));
261
262 if (!collision) {
263 foundMobilePosition = true;
264 break;
265 }
266 }
267 if (!foundMobilePosition) newItem.mobileY! += 1;
268 }
269}
270
271export async function refreshData(data: { updatedAt?: number; handle: string }) {
272 const TEN_MINUTES = 10 * 60 * 1000;
273 const now = Date.now();
274
275 if (now - (data.updatedAt || 0) > TEN_MINUTES) {
276 try {
277 await fetch('/' + data.handle + '/api/refresh');
278 console.log('successfully refreshed data', data.handle);
279 } catch (error) {
280 console.error('error refreshing data', error);
281 }
282 } else {
283 console.log('data still fresh, skipping refreshing', data.handle);
284 }
285}
286
287export function getName(data: WebsiteData): string {
288 return (data.publication?.name ?? data.profile.displayName) || data.handle;
289}
290
291export function getDescription(data: WebsiteData): string {
292 return data.publication?.description ?? data.profile.description ?? '';
293}
294
295export function getHideProfileSection(data: WebsiteData): boolean {
296 if (data?.publication?.preferences?.hideProfileSection !== undefined)
297 return data?.publication?.preferences?.hideProfileSection;
298
299 if (data?.publication?.preferences?.hideProfile !== undefined)
300 return data?.publication?.preferences?.hideProfile;
301
302 return data.page !== 'blento.self';
303}
304
305export function isTyping() {
306 const active = document.activeElement;
307
308 const isEditable =
309 active instanceof HTMLInputElement ||
310 active instanceof HTMLTextAreaElement ||
311 // @ts-expect-error this fine
312 active?.isContentEditable;
313
314 return isEditable;
315}
316
317export function validateLink(
318 link: string | undefined,
319 tryAdding: boolean = true
320): string | undefined {
321 if (!link) return;
322 try {
323 new URL(link);
324
325 return link;
326 } catch (e) {
327 if (!tryAdding) return;
328
329 try {
330 link = 'https://' + link;
331 new URL(link);
332
333 return link;
334 } catch (e) {
335 return;
336 }
337 }
338}
339
340export function compressImage(file: File | Blob, maxSize: number = 900 * 1024): Promise<Blob> {
341 return new Promise((resolve, reject) => {
342 const img = new Image();
343 const reader = new FileReader();
344
345 reader.onload = (e) => {
346 if (!e.target?.result) {
347 return reject(new Error('Failed to read file.'));
348 }
349 img.src = e.target.result as string;
350 };
351
352 reader.onerror = (err) => reject(err);
353 reader.readAsDataURL(file);
354
355 img.onload = () => {
356 const maxDimension = 2048;
357
358 // If image is already small enough, return original
359 if (file.size <= maxSize) {
360 console.log('skipping compression+resizing, already small enough');
361 return resolve(file);
362 }
363
364 let width = img.width;
365 let height = img.height;
366
367 if (width > maxDimension || height > maxDimension) {
368 if (width > height) {
369 height = Math.round((maxDimension / width) * height);
370 width = maxDimension;
371 } else {
372 width = Math.round((maxDimension / height) * width);
373 height = maxDimension;
374 }
375 }
376
377 // Create a canvas to draw the image
378 const canvas = document.createElement('canvas');
379 canvas.width = width;
380 canvas.height = height;
381 const ctx = canvas.getContext('2d');
382 if (!ctx) return reject(new Error('Failed to get canvas context.'));
383 ctx.drawImage(img, 0, 0, width, height);
384
385 // Use WebP for both compression and transparency support
386 let quality = 0.9;
387
388 function attemptCompression() {
389 canvas.toBlob(
390 (blob) => {
391 if (!blob) {
392 return reject(new Error('Compression failed.'));
393 }
394 if (blob.size <= maxSize || quality < 0.3) {
395 resolve(blob);
396 } else {
397 quality -= 0.1;
398 attemptCompression();
399 }
400 },
401 'image/webp',
402 quality
403 );
404 }
405
406 attemptCompression();
407 };
408
409 img.onerror = (err) => reject(err);
410 });
411}
412
413export async function savePage(
414 data: WebsiteData,
415 currentItems: Item[],
416 originalPublication: string
417) {
418 const promises = [];
419 // find all cards that have been updated (where items differ from originalItems)
420 for (let item of currentItems) {
421 const originalItem = data.cards.find((i) => cardsEqual(i, item));
422
423 if (!originalItem) {
424 console.log('updated or new item', item);
425 item.updatedAt = new Date().toISOString();
426 // run optional upload function for this card type
427 const cardDef = CardDefinitionsByType[item.cardType];
428
429 if (cardDef?.upload) {
430 item = await cardDef?.upload(item);
431 }
432
433 item.page = data.page;
434 item.version = 2;
435
436 promises.push(
437 putRecord({
438 collection: 'app.blento.card',
439 rkey: item.id,
440 record: item
441 })
442 );
443 }
444 }
445
446 // delete items that are in originalItems but not in items
447 for (const originalItem of data.cards) {
448 const item = currentItems.find((i) => i.id === originalItem.id);
449 if (!item) {
450 console.log('deleting item', originalItem);
451 promises.push(deleteRecord({ collection: 'app.blento.card', rkey: originalItem.id }));
452 }
453 }
454
455 if (
456 data.publication?.preferences?.hideProfile !== undefined &&
457 data.publication?.preferences?.hideProfileSection === undefined
458 ) {
459 data.publication.preferences.hideProfileSection = data.publication?.preferences?.hideProfile;
460 }
461
462 if (!originalPublication || originalPublication !== JSON.stringify(data.publication)) {
463 data.publication ??= {
464 name: getName(data),
465 description: getDescription(data),
466 preferences: {
467 hideProfileSection: getHideProfileSection(data)
468 }
469 };
470
471 if (!data.publication.url) {
472 data.publication.url = 'https://blento.app/' + data.handle;
473
474 if (data.page !== 'blento.self') {
475 data.publication.url += '/' + data.page.replace('blento.', '');
476 }
477 }
478 promises.push(
479 putRecord({
480 collection: 'site.standard.publication',
481 rkey: data.page,
482 record: data.publication
483 })
484 );
485
486 console.log('updating or adding publication', data.publication);
487 }
488
489 await Promise.all(promises);
490
491 fetch('/' + data.handle + '/api/refresh').then(() => {
492 console.log('data refreshed!');
493 });
494 console.log('refreshing data');
495
496 toast('Saved', {
497 description: 'Your website has been saved!'
498 });
499}
500
501export function createEmptyCard(page: string) {
502 return {
503 id: TID.now(),
504 x: 0,
505 y: 0,
506 w: 2,
507 h: 2,
508 mobileH: 4,
509 mobileW: 4,
510 mobileX: 0,
511 mobileY: 0,
512 cardType: '',
513 cardData: {},
514 page
515 } as Item;
516}
517
518export function scrollToItem(
519 item: Item,
520 isMobile: boolean,
521 container: HTMLDivElement | undefined,
522 force: boolean = false
523) {
524 // scroll to newly created card only if not fully visible
525 const containerRect = container?.getBoundingClientRect();
526 if (!containerRect) return;
527 const currentMargin = isMobile ? mobileMargin : margin;
528 const currentY = isMobile ? item.mobileY : item.y;
529 const currentH = isMobile ? item.mobileH : item.h;
530 const cellSize = (containerRect.width - currentMargin * 2) / COLUMNS;
531
532 const cardTop = containerRect.top + currentMargin + currentY * cellSize;
533 const cardBottom = containerRect.top + currentMargin + (currentY + currentH) * cellSize;
534
535 const isFullyVisible = cardTop >= 0 && cardBottom <= window.innerHeight;
536
537 if (!isFullyVisible || force) {
538 const bodyRect = document.body.getBoundingClientRect();
539 const offset = containerRect.top - bodyRect.top;
540 window.scrollTo({ top: offset + cellSize * (currentY - 1), behavior: 'smooth' });
541 }
542}
543
544export async function checkAndUploadImage(
545 objectWithImage: Record<string, any>,
546 key: string = 'image'
547) {
548 if (!objectWithImage[key]) return;
549
550 // Already uploaded as blob
551 if (typeof objectWithImage[key] === 'object' && objectWithImage[key].$type === 'blob') {
552 return;
553 }
554
555 if (typeof objectWithImage[key] === 'string') {
556 // Download image from URL via proxy (to avoid CORS) and upload as blob
557 try {
558 const proxyUrl = `/api/image-proxy?url=${encodeURIComponent(objectWithImage[key])}`;
559 const response = await fetch(proxyUrl);
560 if (!response.ok) {
561 console.error('Failed to fetch image:', objectWithImage[key]);
562 return;
563 }
564 const blob = await response.blob();
565 const compressedBlob = await compressImage(blob);
566 objectWithImage[key] = await uploadBlob({ blob: compressedBlob });
567 } catch (error) {
568 console.error('Failed to download and upload image:', error);
569 }
570 return;
571 }
572
573 if (objectWithImage[key]?.blob) {
574 const compressedBlob = await compressImage(objectWithImage[key].blob);
575 objectWithImage[key] = await uploadBlob({ blob: compressedBlob });
576 }
577}
578
579export function getImage(
580 objectWithImage: Record<string, any> | undefined,
581 did: string,
582 key: string = 'image'
583) {
584 if (!objectWithImage?.[key]) return;
585
586 if (objectWithImage[key].objectUrl) return objectWithImage[key].objectUrl;
587
588 if (typeof objectWithImage[key] === 'object' && objectWithImage[key].$type === 'blob') {
589 return getImageBlobUrl({ did, blob: objectWithImage[key] });
590 }
591 return objectWithImage[key];
592}