Skip to content
Merged
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ Server will start on port 3000 (or use PORT environment variable to customize)
- `VITE_GA_ID`: Optional GA4 measurement ID for the Vite web app. Example: `G-XXXXXXXXXX`. If unset, production builds use the project's default ID in `src/analytics.ts`. Development builds send nothing.
- Events: `page_view`, `search` (`search_scope`: `single`/`group`/`all`, `library_count`), `search_complete` (`library_count`, `failed_count`, `result_count`, `available_count`, `duration_ms`), `search_cancel` (`library_count`, `completed_count`, `duration_ms`), `my_library_select`
- Entry source: open the app with `?ref=<source>` (e.g. `?ref=ext` for the Chrome extension, `?ref=bm` for the bookmarklet; lowercase letters, digits, `-`, `_`, up to 20 chars). The first `page_view` gets `utm_source=<source>` in `page_location`, so GA4 shows it as the session source. `page_view` and `search` also carry `entry_ref`; register it as an event-scoped custom dimension in GA4 to break down searches by source.
- Bookmarklet: after choosing a library, the bottom of the page shows a "동네 도서관에서 찾기" button to drag to the bookmarks bar. On any site, select a book title (or type one when nothing is selected) and click it to open a search in that library with `?ref=bm`. The library is baked into the bookmarklet because it runs on other sites and cannot read this site's storage; without a chosen library no bookmarklet is offered, since a title-only link searches every library.
- Bookmarklet: the bottom of the page shows a "동네 도서관에서 찾기" button to drag to the bookmarks bar. On any site, select a book title (or type one when nothing is selected) and click it to open `/?title=<title>&ref=bm`. When the app is opened with `ref` but no `library`, it searches the user's "내 도서관" (up to 5 recently searched libraries, stored in this site's localStorage) instead of every library; with no saved libraries it only fills in the title. Older bookmarklets that include `library` keep searching that library.

## Library Regions

Expand Down
3 changes: 2 additions & 1 deletion src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ const App = () => {
resetFilters,
addToHistory,
addToMyLibraries: addMyLibrary,
myLibraries,
});

const handleModuleChange = useCallback(
Expand Down Expand Up @@ -197,7 +198,7 @@ const App = () => {
}
/>
</div>
<BookmarkletHelp libraryName={libraryName !== DEFAULT_LIBRARY ? libraryName : undefined} />
<BookmarkletHelp />
</div>
<ScrollToTopButton />
</div>
Expand Down
17 changes: 5 additions & 12 deletions src/components/BookmarkletHelp.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,17 @@ import userEvent from "@testing-library/user-event";
import { BookmarkletHelp } from "./BookmarkletHelp";

describe("BookmarkletHelp", () => {
it("도서관을 고르지 않으면 북마클릿을 만들지 않는다", () => {
it("도서관 없이 ref=bm 으로 여는 javascript: 링크를 만든다", () => {
render(<BookmarkletHelp />);

expect(screen.queryByTestId("bookmarklet-link")).toBeNull();
expect(screen.getByTestId("bookmarklet-help")).toHaveTextContent("도서관을 하나 고르면");
});

it("고른 도서관을 넣은 javascript: 링크를 만든다", () => {
render(<BookmarkletHelp libraryName="판교도서관" />);

const href = screen.getByTestId("bookmarklet-link").getAttribute("href") ?? "";
const href = decodeURIComponent(screen.getByTestId("bookmarklet-link").getAttribute("href") ?? "");
expect(href.startsWith("javascript:")).toBe(true);
expect(decodeURIComponent(href)).toContain('"판교도서관"');
expect(decodeURIComponent(href)).toContain('"ref","bm"');
expect(href).toContain('"ref","bm"');
expect(href).not.toContain('"library"');
});

it("페이지에서 누르면 끌어다 놓으라고 안내한다", async () => {
render(<BookmarkletHelp libraryName="판교도서관" />);
render(<BookmarkletHelp />);

await userEvent.click(screen.getByTestId("bookmarklet-link"));

Expand Down
52 changes: 20 additions & 32 deletions src/components/BookmarkletHelp.tsx
Original file line number Diff line number Diff line change
@@ -1,48 +1,36 @@
import { useEffect, useRef, useState } from "react";
import { buildBookmarklet } from "../utils/bookmarklet";

interface BookmarkletHelpProps {
/** 지금 고른 도서관. 없으면 북마클릿을 만들지 않는다 (전체 도서관 검색이 되므로) */
libraryName?: string;
}

/** 다른 사이트에서 책 제목을 드래그해 바로 검색하는 북마클릿 안내 */
export const BookmarkletHelp = ({ libraryName }: BookmarkletHelpProps) => {
export const BookmarkletHelp = () => {
const linkRef = useRef<HTMLAnchorElement>(null);
const [clicked, setClicked] = useState(false);

// React 는 javascript: href 를 막으므로 DOM 에 직접 넣는다
useEffect(() => {
if (libraryName && linkRef.current) {
linkRef.current.setAttribute("href", buildBookmarklet(window.location.origin, libraryName));
}
}, [libraryName]);
linkRef.current?.setAttribute("href", buildBookmarklet(window.location.origin));
}, []);

return (
<section className="mt-8 border-t border-gray-200 pt-4 text-sm text-gray-600" data-testid="bookmarklet-help">
<h2 className="font-semibold text-gray-700">다른 사이트에서 바로 찾기</h2>
{libraryName ? (
<>
<p className="mt-1">
아래 버튼을 북마크바로 끌어다 놓으세요. 서점·블로그에서 책 제목을 드래그하고 북마크를 누르면{" "}
{libraryName}에서 검색합니다.
</p>
<a
ref={linkRef}
data-testid="bookmarklet-link"
onClick={(e) => {
e.preventDefault();
setClicked(true);
}}
className="mt-2 inline-block cursor-grab rounded bg-blue-600 px-3 py-1 text-white hover:bg-blue-700"
>
동네 도서관에서 찾기
</a>
{clicked && <p className="mt-1 text-gray-500">여기서 누르지 말고 북마크바로 끌어다 놓으세요.</p>}
</>
) : (
<p className="mt-1">도서관을 하나 고르면, 그 도서관에서 바로 검색하는 북마크 버튼이 여기에 나타납니다.</p>
)}
<p className="mt-1">
아래 버튼을 북마크바로 끌어다 놓으세요. 서점·블로그에서 책 제목을 드래그하고 북마크를 누르면
내 도서관(최근에 검색한 도서관 최대 5곳)에서 찾습니다. 내 도서관이 없으면 제목만 채워 두니 도서관을
고르세요.
</p>
<a
ref={linkRef}
data-testid="bookmarklet-link"
onClick={(e) => {
e.preventDefault();
setClicked(true);
}}
className="mt-2 inline-block cursor-grab rounded bg-blue-600 px-3 py-1 text-white hover:bg-blue-700"
>
동네 도서관에서 찾기
</a>
{clicked && <p className="mt-1 text-gray-500">여기서 누르지 말고 북마크바로 끌어다 놓으세요.</p>}
</section>
);
};
31 changes: 31 additions & 0 deletions src/hooks/useSearchManager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,37 @@ describe("useSearchManager", () => {
);
});

it("북마클릿으로 도서관 없이 들어오면 내 도서관만 검색한다", () => {
vi.mocked(getUrlParams).mockReturnValue({ title: "해리포터", library: DEFAULT_LIBRARY, ref: "bm" });

const params = createMockParams({ myLibraries: ["강남도서관", "없는도서관"] });
const { result } = renderHook(() => useSearchManager(params));

expect(params.performSearch).toHaveBeenCalledWith("해리포터", DEFAULT_LIBRARY, [
{ id: 2, name: "강남도서관" },
]);
expect(result.current.searchText).toBe("해리포터");
});

it("북마클릿으로 들어왔는데 내 도서관이 없으면 제목만 채우고 검색하지 않는다", () => {
vi.mocked(getUrlParams).mockReturnValue({ title: "해리포터", library: DEFAULT_LIBRARY, ref: "bm" });

const params = createMockParams({ myLibraries: [] });
const { result } = renderHook(() => useSearchManager(params));

expect(params.performSearch).not.toHaveBeenCalled();
expect(result.current.searchText).toBe("해리포터");
});

it("ref 가 있어도 도서관이 정해져 있으면 그 도서관을 검색한다", () => {
vi.mocked(getUrlParams).mockReturnValue({ title: "해리포터", library: "강남도서관", ref: "bm" });

const params = createMockParams({ myLibraries: ["서울도서관"] });
renderHook(() => useSearchManager(params));

expect(params.performSearch).toHaveBeenCalledWith("해리포터", "강남도서관", mockLibraries);
});

it("URL에 title이 없으면 자동 검색하지 않는다", () => {
const params = createMockParams();
renderHook(() => useSearchManager(params));
Expand Down
14 changes: 12 additions & 2 deletions src/hooks/useSearchManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ export const useSearchManager = (params: {
addToHistory: (query: string) => void;
/** 도서관 하나를 골라 검색했을 때 그 도서관을 "내 도서관"에 남긴다 */
addToMyLibraries?: (libraryName: string) => void;
/** "내 도서관" 이름. 북마클릿·확장이 도서관 없이 열면 이 도서관들을 검색한다 */
myLibraries?: string[];
}) => {
const {
libraryNames,
Expand All @@ -22,6 +24,7 @@ export const useSearchManager = (params: {
resetFilters,
addToHistory,
addToMyLibraries,
myLibraries = [],
} = params;

const initialParams = getUrlParams();
Expand All @@ -47,13 +50,20 @@ export const useSearchManager = (params: {

useEffect(() => {
if (libraryNames.length > 0 && !initialSearchFiredRef.current) {
const { title, library } = getUrlParams();
const { title, library, ref } = getUrlParams();
if (title) {
initialSearchFiredRef.current = true;
if (ref && library === DEFAULT_LIBRARY) {
// 북마클릿·확장은 도서관을 모른다. 전체(1,342곳) 대신 내 도서관을 검색하고,
// 내 도서관이 없으면 제목만 채워 두고 도서관을 고르게 한다.
const mine = libraryNames.filter((lib) => myLibraries.includes(lib.name));
if (mine.length > 0) performSearch(title, DEFAULT_LIBRARY, mine);
return;
}
performSearch(title, library, libraryNames);
}
}
}, [libraryNames, performSearch]);
}, [libraryNames, performSearch, myLibraries]);

const handleSearch = useCallback(() => {
if (!searchText?.length) return;
Expand Down
18 changes: 8 additions & 10 deletions src/utils/bookmarklet.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,24 @@ import { describe, it, expect, vi, afterEach } from "vitest";
import { buildBookmarklet } from "./bookmarklet";

const run = (href: string) => {
// eslint-disable-next-line @typescript-eslint/no-implied-eval
new Function(decodeURIComponent(href.slice("javascript:".length)))();
};

describe("buildBookmarklet", () => {
afterEach(() => {
vi.restoreAllMocks();
window.getSelection()?.removeAllRanges();
});

it("고른 글자와 도서관, ref=bm 으로 새 탭을 연다", () => {
it("고른 글자와 ref=bm 으로 새 탭을 연다 (도서관은 넣지 않는다)", () => {
const open = vi.spyOn(window, "open").mockReturnValue(null);
vi.spyOn(window, "getSelection").mockReturnValue({ toString: () => " 채식주의자 " } as Selection);

run(buildBookmarklet("https://dongne.onrender.com", "판교도서관"));
run(buildBookmarklet("https://dongne.onrender.com"));

const url = new URL(open.mock.calls[0][0] as string);
expect(url.origin).toBe("https://dongne.onrender.com");
expect(url.searchParams.get("title")).toBe("채식주의자");
expect(url.searchParams.get("library")).toBe("판교도서관");
expect(url.searchParams.get("library")).toBeNull();
expect(url.searchParams.get("ref")).toBe("bm");
expect(open.mock.calls[0][1]).toBe("_blank");
});
Expand All @@ -31,18 +29,18 @@ describe("buildBookmarklet", () => {
vi.spyOn(window, "getSelection").mockReturnValue({ toString: () => "" } as Selection);
const ask = vi.spyOn(window, "prompt").mockReturnValue(null);

run(buildBookmarklet("https://dongne.onrender.com", "판교도서관"));
run(buildBookmarklet("https://dongne.onrender.com"));

expect(ask).toHaveBeenCalled();
expect(open).not.toHaveBeenCalled();
});

it("도서관 이름의 따옴표가 코드를 깨지 않는다", () => {
it("입력한 제목은 100자로 자른다", () => {
const open = vi.spyOn(window, "open").mockReturnValue(null);
vi.spyOn(window, "getSelection").mockReturnValue({ toString: () => "책" } as Selection);
vi.spyOn(window, "getSelection").mockReturnValue({ toString: () => "가".repeat(150) } as Selection);

run(buildBookmarklet("http://localhost:3000", '이상한"도서관\'</script>'));
run(buildBookmarklet("http://localhost:3000"));

expect(new URL(open.mock.calls[0][0] as string).searchParams.get("library")).toBe('이상한"도서관\'</script>');
expect(new URL(open.mock.calls[0][0] as string).searchParams.get("title")).toHaveLength(100);
});
});
6 changes: 3 additions & 3 deletions src/utils/bookmarklet.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
/**
* 북마클릿 코드. 다른 사이트에서 고른 글자(없으면 입력창)로 dongne 검색을 새 탭에 연다.
* 다른 사이트에서 실행되므로 이 사이트의 localStorage 를 읽을 수 없다. 도서관은 만들 때 코드에 넣는다.
* 도서관은 넣지 않는다. 열린 dongne 이 자기 localStorage 의 "내 도서관"으로 검색한다.
*/
export const buildBookmarklet = (origin: string, library: string) => {
const code = `(()=>{let t=String(getSelection()).trim();if(!t)t=prompt("찾을 책 제목")||"";t=t.trim().slice(0,100);if(!t)return;const u=new URL(${JSON.stringify(`${origin}/`)});u.searchParams.set("title",t);u.searchParams.set("library",${JSON.stringify(library)});u.searchParams.set("ref","bm");window.open(u.href,"_blank")})()`;
export const buildBookmarklet = (origin: string) => {
const code = `(()=>{let t=String(getSelection()).trim();if(!t)t=prompt("찾을 책 제목")||"";t=t.trim().slice(0,100);if(!t)return;const u=new URL(${JSON.stringify(`${origin}/`)});u.searchParams.set("title",t);u.searchParams.set("ref","bm");window.open(u.href,"_blank")})()`;
return `javascript:${encodeURIComponent(code)}`;
};
4 changes: 3 additions & 1 deletion src/utils/url.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { DEFAULT_LIBRARY } from "../constants";

// URL parameter helpers
export const getUrlParams = () => {
export const getUrlParams = (): { title: string; library: string; ref?: string } => {
const params = new URLSearchParams(window.location.search);
return {
title: params.get("title") || "",
library: params.get("library") || DEFAULT_LIBRARY,
// 북마클릿·확장 등 다른 곳에서 들어왔는지
ref: params.get("ref") || undefined,
};
};

Expand Down
Loading