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, putRecord } 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 // eslint-disable-next-line @typescript-eslint/no-unused-vars
327 } catch (e) {
328 if (!tryAdding) return;
329
330 try {
331 link = 'https://' + link;
332 new URL(link);
333
334 return link;
335 // eslint-disable-next-line @typescript-eslint/no-unused-vars
336 } catch (e) {
337 return;
338 }
339 }
340}
341
342export function compressImage(file: File, maxSize: number = 900 * 1024): Promise<Blob> {
343 return new Promise((resolve, reject) => {
344 const img = new Image();
345 const reader = new FileReader();
346
347 reader.onload = (e) => {
348 if (!e.target?.result) {
349 return reject(new Error('Failed to read file.'));
350 }
351 img.src = e.target.result as string;
352 };
353
354 reader.onerror = (err) => reject(err);
355 reader.readAsDataURL(file);
356
357 img.onload = () => {
358 let width = img.width;
359 let height = img.height;
360 const maxDimension = 2048;
361
362 if (width > maxDimension || height > maxDimension) {
363 if (width > height) {
364 height = Math.round((maxDimension / width) * height);
365 width = maxDimension;
366 } else {
367 width = Math.round((maxDimension / height) * width);
368 height = maxDimension;
369 }
370 }
371
372 // Create a canvas to draw the image
373 const canvas = document.createElement('canvas');
374 canvas.width = width;
375 canvas.height = height;
376 const ctx = canvas.getContext('2d');
377 if (!ctx) return reject(new Error('Failed to get canvas context.'));
378 ctx.drawImage(img, 0, 0, width, height);
379
380 // Function to try compressing at a given quality
381 let quality = 0.8;
382 function attemptCompression() {
383 canvas.toBlob(
384 (blob) => {
385 if (!blob) {
386 return reject(new Error('Compression failed.'));
387 }
388 // If the blob is under our size limit, or quality is too low, resolve it
389 if (blob.size <= maxSize || quality < 0.3) {
390 console.log('Compression successful. Blob size:', blob.size);
391 console.log('Quality:', quality);
392 resolve(blob);
393 } else {
394 // Otherwise, reduce the quality and try again
395 quality -= 0.1;
396 attemptCompression();
397 }
398 },
399 'image/jpeg',
400 quality
401 );
402 }
403
404 attemptCompression();
405 };
406
407 img.onerror = (err) => reject(err);
408 });
409}
410
411export async function savePage(
412 data: WebsiteData,
413 currentItems: Item[],
414 originalPublication: string
415) {
416 const promises = [];
417 // find all cards that have been updated (where items differ from originalItems)
418 for (let item of currentItems) {
419 const originalItem = data.cards.find((i) => cardsEqual(i, item));
420
421 if (!originalItem) {
422 console.log('updated or new item', item);
423 item.updatedAt = new Date().toISOString();
424 // run optional upload function for this card type
425 const cardDef = CardDefinitionsByType[item.cardType];
426
427 if (cardDef?.upload) {
428 item = await cardDef?.upload(item);
429 }
430
431 item.page = data.page;
432 item.version = 2;
433
434 promises.push(
435 putRecord({
436 collection: 'app.blento.card',
437 rkey: item.id,
438 record: item
439 })
440 );
441 }
442 }
443
444 // delete items that are in originalItems but not in items
445 for (const originalItem of data.cards) {
446 const item = currentItems.find((i) => i.id === originalItem.id);
447 if (!item) {
448 console.log('deleting item', originalItem);
449 promises.push(deleteRecord({ collection: 'app.blento.card', rkey: originalItem.id }));
450 }
451 }
452
453 if (
454 data.publication?.preferences?.hideProfile !== undefined &&
455 data.publication?.preferences?.hideProfileSection === undefined
456 ) {
457 data.publication.preferences.hideProfileSection = data.publication?.preferences?.hideProfile;
458 }
459
460 if (!originalPublication || originalPublication !== JSON.stringify(data.publication)) {
461 data.publication ??= {
462 name: getName(data),
463 description: getDescription(data),
464 preferences: {
465 hideProfileSection: getHideProfileSection(data)
466 }
467 };
468
469 if (!data.publication.url) {
470 data.publication.url = 'https://blento.app/' + data.handle;
471
472 if (data.page !== 'blento.self') {
473 data.publication.url += '/' + data.page.replace('blento.', '');
474 }
475 }
476 promises.push(
477 putRecord({
478 collection: 'site.standard.publication',
479 rkey: data.page,
480 record: data.publication
481 })
482 );
483
484 console.log('updating or adding publication', data.publication);
485 }
486
487 await Promise.all(promises);
488
489 fetch('/' + data.handle + '/api/refresh').then(() => {
490 console.log('data refreshed!');
491 });
492 console.log('refreshing data');
493
494 toast('Saved', {
495 description: 'Your website has been saved!'
496 });
497}
498
499export function createEmptyCard(page: string) {
500 return {
501 id: TID.now(),
502 x: 0,
503 y: 0,
504 w: 2,
505 h: 2,
506 mobileH: 4,
507 mobileW: 4,
508 mobileX: 0,
509 mobileY: 0,
510 cardType: '',
511 cardData: {},
512 page
513 } as Item;
514}
515
516export function scrollToItem(
517 item: Item,
518 isMobile: boolean,
519 container: HTMLDivElement | undefined,
520 force: boolean = false
521) {
522 // scroll to newly created card only if not fully visible
523 const containerRect = container?.getBoundingClientRect();
524 if (!containerRect) return;
525 const currentMargin = isMobile ? mobileMargin : margin;
526 const currentY = isMobile ? item.mobileY : item.y;
527 const currentH = isMobile ? item.mobileH : item.h;
528 const cellSize = (containerRect.width - currentMargin * 2) / COLUMNS;
529
530 const cardTop = containerRect.top + currentMargin + currentY * cellSize;
531 const cardBottom = containerRect.top + currentMargin + (currentY + currentH) * cellSize;
532
533 const isFullyVisible = cardTop >= 0 && cardBottom <= window.innerHeight;
534
535 if (!isFullyVisible || force) {
536 const bodyRect = document.body.getBoundingClientRect();
537 const offset = containerRect.top - bodyRect.top;
538 window.scrollTo({ top: offset + cellSize * (currentY - 1), behavior: 'smooth' });
539 }
540}