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