diff --git a/components/BookmarkButton.tsx b/components/BookmarkButton.tsx index 6b921cc72..a2eb9ac60 100644 --- a/components/BookmarkButton.tsx +++ b/components/BookmarkButton.tsx @@ -1,3 +1,4 @@ +import { useState } from 'react'; import { type StyleProp, type ViewStyle } from 'react-native'; import { HoverEffect } from '~/common/styleguide'; @@ -14,10 +15,18 @@ type BookmarkButtonProps = { export default function BookmarkButton({ bookmarkId, style, iconStyle }: BookmarkButtonProps) { const { checkIsBookmarked, toggleBookmark } = useBookmarks(); + const [hasSaveFailed, setSaveFailed] = useState(false); const isBookmarked = checkIsBookmarked(bookmarkId); function handleToggleBookmark() { - toggleBookmark(bookmarkId); + setSaveFailed(!toggleBookmark(bookmarkId)); + } + + function getTooltipContent() { + if (hasSaveFailed) { + return 'Bookmarks limit reached, remove some bookmarks to add more'; + } + return isBookmarked ? 'Remove from bookmarks' : 'Add to bookmarks'; } return ( @@ -35,7 +44,7 @@ export default function BookmarkButton({ bookmarkId, style, iconStyle }: Bookmar )} }> - {isBookmarked ? 'Remove from bookmarks' : 'Add to bookmarks'} + {getTooltipContent()} ); } diff --git a/context/BookmarksContext.test.ts b/context/BookmarksContext.test.ts new file mode 100644 index 000000000..db794818c --- /dev/null +++ b/context/BookmarksContext.test.ts @@ -0,0 +1,58 @@ +import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; + +import { getBookmarksFromCookie, saveBookmarksToCookie } from '~/context/BookmarksContext'; + +// Browsers ignore cookies with name and value longer than 4096 bytes +const COOKIE_SIZE_LIMIT = 4096; + +function installCookieJar() { + const jar = new Map(); + + Object.defineProperty(globalThis, 'document', { + configurable: true, + value: { + get cookie() { + return [...jar].map(([name, value]) => `${name}=${value}`).join('; '); + }, + set cookie(cookie: string) { + const [pair] = cookie.split(';'); + const separatorIndex = pair.indexOf('='); + + if (pair.length > COOKIE_SIZE_LIMIT) { + return; + } + + jar.set(pair.slice(0, separatorIndex), pair.slice(separatorIndex + 1)); + }, + }, + }); +} + +function createPackageNames(count: number) { + return new Set( + Array.from({ length: count }, (_, index) => `@some-scope/react-native-package-${index}`) + ); +} + +describe('saveBookmarksToCookie', () => { + beforeEach(installCookieJar); + + afterEach(() => { + Reflect.deleteProperty(globalThis, 'document'); + }); + + test('saves bookmarks which fit in the cookie', () => { + const bookmarks = createPackageNames(10); + + expect(saveBookmarksToCookie(bookmarks)).toBe(true); + expect(getBookmarksFromCookie()).toEqual([...bookmarks]); + }); + + test('reports a failed save and keeps previous bookmarks when cookie is too large', () => { + const bookmarks = createPackageNames(10); + saveBookmarksToCookie(bookmarks); + + expect(saveBookmarksToCookie(createPackageNames(200))).toBe(false); + expect(getBookmarksFromCookie()).toEqual([...bookmarks]); + }); +}); diff --git a/context/BookmarksContext.tsx b/context/BookmarksContext.tsx index 4ce09a367..a029e7d74 100644 --- a/context/BookmarksContext.tsx +++ b/context/BookmarksContext.tsx @@ -8,7 +8,8 @@ const COOKIE_MAX_AGE = TimeRange.YEAR; type BookmarksContextType = { bookmarkedIds: Set; checkIsBookmarked: (id: string) => boolean; - toggleBookmark: (id: string) => void; + /** Returns `false` when the change could not be saved, e.g. bookmarks cookie size limit was hit. */ + toggleBookmark: (id: string) => boolean; isLoading: boolean; }; @@ -29,6 +30,16 @@ function setCookie(name: string, value: string, maxAge: number) { document.cookie = `${name}=${encodeURIComponent(value)}; path=/; max-age=${maxAge}; SameSite=Lax`; } +/** + * Save bookmarks to the cookie and check that the browser has stored it. Browsers silently + * ignore cookies over the size limit (about 4 KB), which is reached with around 120 bookmarks. + */ +export function saveBookmarksToCookie(ids: Set): boolean { + const serializedIds = JSON.stringify([...ids]); + setCookie(BOOKMARK_COOKIE_NAME, serializedIds, COOKIE_MAX_AGE); + return getCookie(BOOKMARK_COOKIE_NAME) === serializedIds; +} + export function getBookmarksFromCookie(cookieString?: string): string[] { if (typeof cookieString === 'string') { const match = cookieString.match(new RegExp(`(^| )${BOOKMARK_COOKIE_NAME}=([^;]+)`)); @@ -70,8 +81,12 @@ export function BookmarksProvider({ children }: PropsWithChildren) { newSet.add(id); } - setCookie(BOOKMARK_COOKIE_NAME, JSON.stringify([...newSet]), COOKIE_MAX_AGE); + if (!saveBookmarksToCookie(newSet)) { + return false; + } + setBookmarkedIds(newSet); + return true; }, isLoading, }; diff --git a/scripts/build-and-score-data.ts b/scripts/build-and-score-data.ts index 96d0f9b4d..73dece554 100644 --- a/scripts/build-and-score-data.ts +++ b/scripts/build-and-score-data.ts @@ -271,20 +271,22 @@ export async function buildAndScoreData() { const hasEntry = libraries.some(lib => lib.npmPkg === wantedPackageName); const newDataEntry = data.find(entry => entry.npmPkg === wantedPackageName); - const content = hasEntry - ? { - libraries: libraries.map(library => { - if (newDataEntry && library.npmPkg === wantedPackageName) { - return newDataEntry; - } - return library; - }), - topics: sortTopics(topicCounts), - } - : { - libraries: newDataEntry ? [...libraries, newDataEntry] : libraries, - topics: sortTopics(topicCounts), - }; + const updatedLibraries = hasEntry + ? libraries.map(library => { + if (newDataEntry && library.npmPkg === wantedPackageName) { + return newDataEntry; + } + return library; + }) + : newDataEntry + ? [...libraries, newDataEntry] + : libraries; + + // Count topics across all libraries, not only the single refreshed package + const content = { + libraries: updatedLibraries, + topics: sortTopics(getTopicCounts(updatedLibraries)), + }; finalLibraries = content.libraries; fileContent = JSON.stringify(content, null, 2); diff --git a/scripts/fetch-npm-stat-data.ts b/scripts/fetch-npm-stat-data.ts index d9be10ef9..42500364f 100644 --- a/scripts/fetch-npm-stat-data.ts +++ b/scripts/fetch-npm-stat-data.ts @@ -2,6 +2,7 @@ import { fetch } from 'bun'; import { sum } from 'es-toolkit/math'; import { fallbackFetchNpmDownloadData } from '~/scripts/fetch-npm-download-data'; +import { TimeRange } from '~/util/datetime'; import { REQUEST_SLEEP, sleep } from './helpers'; @@ -89,17 +90,15 @@ function formatDownloadData(downloadData: Record) { } function formattedDate(date: Date) { - const year = date.getFullYear(); - const month = String(date.getMonth() + 1).padStart(2, '0'); - const day = String(date.getDate()).padStart(2, '0'); - - return `${year}-${month}-${day}`; + return date.toISOString().slice(0, 10); } function urlForPackages(packagesList: string) { - const now = new Date(); - const fromDate = new Date(now); - fromDate.setMonth(fromDate.getMonth() - 1); + // Use 30 full days ending yesterday, the same period as the npm downloads API `last-month`, + // so the monthly downloads (and the Trending Score) don't depend on the current month length + const now = Date.now(); + const fromDate = new Date(now - TimeRange.MONTH * 1000); + const untilDate = new Date(now - TimeRange.DAY * 1000); - return `https://npm-stat.com/api/download-counts?package=${packagesList}&from=${formattedDate(fromDate)}&until=${formattedDate(now)}`; + return `https://npm-stat.com/api/download-counts?package=${packagesList}&from=${formattedDate(fromDate)}&until=${formattedDate(untilDate)}`; } diff --git a/util/search.ts b/util/search.ts index d008eabdb..166cffb26 100644 --- a/util/search.ts +++ b/util/search.ts @@ -105,6 +105,17 @@ function calculateMatchScore( } } +/** + * Match the whole owner name (so `expo` doesn't match `exponotify`), case-insensitively, + * against the owner from the entry GitHub URL and the current owner reported by GitHub. + */ +function isOwnedBy({ githubUrl, github }: LibraryType, owner: string) { + const ownerName = owner.toLowerCase(); + const libraryOwners = [githubUrl.split('/')[3], github.fullName?.split('/')[0]]; + + return libraryOwners.some(libraryOwner => libraryOwner?.toLowerCase() === ownerName); +} + export function handleFilterLibraries({ libraries, sortBy, @@ -255,7 +266,7 @@ export function handleFilterLibraries({ return false; } - if (owner && !library.githubUrl.startsWith(`https://github.com/${owner}`)) { + if (owner && !isOwnedBy(library, owner)) { return false; }