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