From 6fe38a39cf855f2ab6586cf4ccc0506ab8f035a4 Mon Sep 17 00:00:00 2001 From: afrontend Date: Wed, 11 Nov 2026 22:43:51 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=EB=B6=81=EB=A7=88=ED=81=B4=EB=A6=BF?= =?UTF-8?q?=EC=9D=80=20=EB=8F=84=EC=84=9C=EA=B4=80=20=EC=97=86=EC=9D=B4=20?= =?UTF-8?q?=EC=97=B4=EA=B3=A0=20=EB=82=B4=20=EB=8F=84=EC=84=9C=EA=B4=80?= =?UTF-8?q?=EC=97=90=EC=84=9C=20=EA=B2=80=EC=83=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 북마클릿이 도서관을 넣지 않는다. 하나만 끌어다 놓으면 되고 도서관을 바꿔도 다시 만들 필요가 없다 - ref 가 있고 library 가 없으면 전체 대신 내 도서관(최대 5곳)을 검색한다 - 내 도서관이 없으면 제목만 채우고 검색하지 않는다 - 예전 북마클릿(library 포함)은 그대로 그 도서관을 검색한다 --- README.md | 2 +- src/App.tsx | 3 +- src/components/BookmarkletHelp.test.tsx | 17 +++----- src/components/BookmarkletHelp.tsx | 52 ++++++++++--------------- src/hooks/useSearchManager.test.ts | 31 +++++++++++++++ src/hooks/useSearchManager.ts | 14 ++++++- src/utils/bookmarklet.test.ts | 18 ++++----- src/utils/bookmarklet.ts | 6 +-- src/utils/url.ts | 4 +- 9 files changed, 85 insertions(+), 62 deletions(-) diff --git a/README.md b/README.md index 5526c70..a932c67 100644 --- a/README.md +++ b/README.md @@ -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=` (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=` 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=&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 diff --git a/src/App.tsx b/src/App.tsx index 33dc226..77273c1 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -71,6 +71,7 @@ const App = () => { resetFilters, addToHistory, addToMyLibraries: addMyLibrary, + myLibraries, }); const handleModuleChange = useCallback( @@ -197,7 +198,7 @@ const App = () => { } /> </div> - <BookmarkletHelp libraryName={libraryName !== DEFAULT_LIBRARY ? libraryName : undefined} /> + <BookmarkletHelp /> </div> <ScrollToTopButton /> </div> diff --git a/src/components/BookmarkletHelp.test.tsx b/src/components/BookmarkletHelp.test.tsx index 2fdb539..1b6e747 100644 --- a/src/components/BookmarkletHelp.test.tsx +++ b/src/components/BookmarkletHelp.test.tsx @@ -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")); diff --git a/src/components/BookmarkletHelp.tsx b/src/components/BookmarkletHelp.tsx index b868e40..96591a0 100644 --- a/src/components/BookmarkletHelp.tsx +++ b/src/components/BookmarkletHelp.tsx @@ -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> ); }; diff --git a/src/hooks/useSearchManager.test.ts b/src/hooks/useSearchManager.test.ts index 01676f3..44e9f94 100644 --- a/src/hooks/useSearchManager.test.ts +++ b/src/hooks/useSearchManager.test.ts @@ -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)); diff --git a/src/hooks/useSearchManager.ts b/src/hooks/useSearchManager.ts index dc206c4..dec8ea3 100644 --- a/src/hooks/useSearchManager.ts +++ b/src/hooks/useSearchManager.ts @@ -13,6 +13,8 @@ export const useSearchManager = (params: { addToHistory: (query: string) => void; /** 도서관 하나를 골라 검색했을 때 그 도서관을 "내 도서관"에 남긴다 */ addToMyLibraries?: (libraryName: string) => void; + /** "내 도서관" 이름. 북마클릿·확장이 도서관 없이 열면 이 도서관들을 검색한다 */ + myLibraries?: string[]; }) => { const { libraryNames, @@ -22,6 +24,7 @@ export const useSearchManager = (params: { resetFilters, addToHistory, addToMyLibraries, + myLibraries = [], } = params; const initialParams = getUrlParams(); @@ -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; diff --git a/src/utils/bookmarklet.test.ts b/src/utils/bookmarklet.test.ts index fa0ea58..318f630 100644 --- a/src/utils/bookmarklet.test.ts +++ b/src/utils/bookmarklet.test.ts @@ -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"); }); @@ -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); }); }); diff --git a/src/utils/bookmarklet.ts b/src/utils/bookmarklet.ts index ab6d389..9a5a1cf 100644 --- a/src/utils/bookmarklet.ts +++ b/src/utils/bookmarklet.ts @@ -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)}`; }; diff --git a/src/utils/url.ts b/src/utils/url.ts index e8f3dc4..f924921 100644 --- a/src/utils/url.ts +++ b/src/utils/url.ts @@ -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, }; };