Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions components/BookmarkButton.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useState } from 'react';
import { type StyleProp, type ViewStyle } from 'react-native';

import { HoverEffect } from '~/common/styleguide';
Expand All @@ -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 (
Expand All @@ -35,7 +44,7 @@ export default function BookmarkButton({ bookmarkId, style, iconStyle }: Bookmar
)}
</HoverEffect>
}>
{isBookmarked ? 'Remove from bookmarks' : 'Add to bookmarks'}
{getTooltipContent()}
</Tooltip>
);
}
58 changes: 58 additions & 0 deletions context/BookmarksContext.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, string>();

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]);
});
});
19 changes: 17 additions & 2 deletions context/BookmarksContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ const COOKIE_MAX_AGE = TimeRange.YEAR;
type BookmarksContextType = {
bookmarkedIds: Set<string>;
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;
};

Expand All @@ -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<string>): 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}=([^;]+)`));
Expand Down Expand Up @@ -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,
};
Expand Down
30 changes: 16 additions & 14 deletions scripts/build-and-score-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
17 changes: 8 additions & 9 deletions scripts/fetch-npm-stat-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -89,17 +90,15 @@ function formatDownloadData(downloadData: Record<string, number>) {
}

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)}`;
}
13 changes: 12 additions & 1 deletion util/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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;
}

Expand Down