@madeinbruno/music-plug 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,14 +3,26 @@
3
3
  글 속 노래 한 곡을, 듣는 사람이 쓰는 음원 앱에서 듣게 하는 플러그예요. [Music plug](https://musicplug.madeinbruno.com)의 듣기 플러그를 다른 사이트에 붙이는 패키지예요.
4
4
 
5
5
  ```
6
- ♪ 밤편지 · 아이유 ← 처음 누르면 Music plug 듣기 플러그가 뜬다
7
- ♪ 밤편지 · 아이유 멜론 · 바꾸기 ← 고른 뒤에는 누르면 바로 멜론에서
6
+ ┌──────────────────────────────────────┐
7
+ │ [앨범] 밤편지 (▶) │ ← 처음 누르면 Music plug 듣기 플러그가 뜬다
8
+ │ 아이유 │
9
+ │ ──────────────────────────────────── │
10
+ │ [멜론] 멜론에서 들어요 바꾸기 │ ← 고른 뒤에는 누르면 바로 멜론에서
11
+ └──────────────────────────────────────┘
8
12
  ```
9
13
 
14
+ 세 겹으로 쓸 수 있어요.
15
+
16
+ | 가져오는 곳 | 무엇 | 언제 |
17
+ |---|---|---|
18
+ | `@madeinbruno/music-plug/player` + `styles.css` | **기본 화면**: 흰 라운드 카드 + 그림자. 어느 사이트에 붙여도 같은 모양 | 보통은 이것 |
19
+ | `@madeinbruno/music-plug/headless` | **동작만** (React 훅). 화면·CSS 없음 | 사이트에 맞춰 직접 그리고 싶을 때 |
20
+ | `@madeinbruno/music-plug` | 함수 (곡 링크 읽기·거르기, 주소 만들기). 서버에서도 | 저장·서버 쪽 |
21
+
10
22
  - 처음 누르면 **듣기 플러그**(Music plug 창)가 떠서 어디서 들을지 골라요: YouTube(기본) · 멜론 · 지니 · 벅스 · FLO · VIBE · Spotify · Apple Music · YouTube Music. YouTube는 유튜브 영상이 있으면 이 페이지에서 바로, 없으면 YouTube로 열어요.
11
23
  - 고르면 그곳에서 이 곡을 열어요 (폰에서는 앱으로). Music plug가 곡을 찾아 보내요: YouTube·YouTube Music은 그 곡을 바로(시작 시각까지), Apple Music은 곡 페이지, 나머지는 그곳의 검색 결과.
12
24
  - 고른 곳은 기억해서 다음부터는 누르면 바로 그곳에서 열어요. 곡 옆의 **바꾸기**로 다시 골라요. madeinbruno.com 아래에서는 Music plug와 같이 기억해요 (쿠키 `mp_service`).
13
- - YouTube를 고르면 글 안에 유튜브 플레이어를 열어요. 읽어 내려가면 왼쪽 아래에 멈추기·다시 듣기 단추가 떠요. 브라우저가 소리 있는 자동재생을 막아서 한 번은 눌러야 나오고, 유튜브 정책상 플레이어는 보이게 둬요.
25
+ - YouTube를 고르면 카드 안에 유튜브 플레이어를 열고 ▶가 ❚❚가 돼요. 읽어 내려가면 왼쪽 아래에 작은 음악 바(▶/❚❚ + 곡 제목)가 떠요. 브라우저가 소리 있는 자동재생을 막아서 한 번은 눌러야 나오고, 유튜브 정책상 플레이어는 보이게 둬요.
14
26
  - 곡 정보를 모르면(유튜브에서 제목을 못 받으면) 다른 곳에서 찾을 수 없어서 이 페이지에서 YouTube로만 틀어요.
15
27
  - **곡은 유튜브 주소뿐 아니라 여러 곳의 곡 링크로 정할 수 있어요** (`songFromUrl`): YouTube · YouTube Music · 멜론 · 지니 · 벅스 · FLO · VIBE · Spotify · Apple Music. 쓰는 사람은 자기가 쓰는 곳의 곡 링크를 넣고, 듣는 사람은 자기가 쓰는 곳에서 들어요. 듣는 사람이 고른 곳이 곡을 정한 링크와 같은 곳이면 찾지 않고 그 링크를 바로 열어요. 유튜브 링크가 아니면 글 안의 플레이어는 없고, YouTube를 고르면 YouTube에서 그 곡을 찾아 열어요.
16
28
 
@@ -45,8 +57,10 @@ export default async function Post({ music }: { music: string }) {
45
57
 
46
58
  | 내보내는 것 | 설명 |
47
59
  |---|---|
48
- | `PlugPlayer` (`/player`) | 곡 한 줄과 듣기 플러그. `song`(제목·가수, 모르면 `null`), `fallbackLabel`, `youtube`(`id`, `start` 초. 있으면 YouTube를 글 안에서, 없으면 YouTube로 연다), `source`(곡을 정한 링크의 `service`·`url`. 듣는 사람이 같은 곳을 고르면 그 링크를 바로 연다), `avoid`(이 요소가 보이면 멈추기 단추를 숨김), `base`(Music plug 주소, 기본 `https://musicplug.madeinbruno.com`) |
60
+ | `PlugPlayer` (`/player`) | 듣기 카드와 듣기 플러그. `song`(제목·가수, 모르면 `null`), `artwork`(앨범 그림, 없으면 Music plug 심볼), `fallbackLabel`, `youtube`(`id`, `start` 초. 있으면 YouTube를 카드 안에서, 없으면 YouTube로 연다), `source`(곡을 정한 링크의 `service`·`url`. 듣는 사람이 같은 곳을 고르면 그 링크를 바로 연다), `links`(곳마다 정해 둔 곡 링크), `avoid`(이 요소가 보이면 작은 음악 바를 숨김), `theme`(`light` 기본 · `dark` · `auto`), `base`(Music plug 주소, 기본 `https://musicplug.madeinbruno.com`) |
49
61
  | `PlugSheet` (`/player`) | 듣기 플러그 창만 따로 |
62
+ | `ServiceMark` (`/player`) | 음원 서비스 로고 (없는 곳은 그 색의 머리글자 동그라미) |
63
+ | `LOGO_PATHS` | 로고 SVG path (24×24). 직접 그릴 때 |
50
64
  | `listenPageUrl(song, youtube?)` | Music plug의 고르는 화면 주소 (`/listen`). 링크로만 걸고 싶을 때. 전에 고른 곳이 있으면 그 화면 없이 바로 그곳으로 가요 |
51
65
  | `listenGoUrl(service, song, youtube?)` | 고른 곳에서 이 곡을 여는 주소 (`/listen/go`) |
52
66
  | `songFromUrl(link)` | 곡 링크 하나로 그 곡을 읽어요 (서버에서): `{ service, url, song, youtube? }`. 유튜브는 oEmbed로 짐작하고, 그 밖의 곳은 Music plug(`/api/song`)가 그곳의 곡 화면에서 읽어 줘요. 곡 링크가 아니면 `null`, 곡을 못 읽으면 `song`이 `null` |
@@ -56,7 +70,55 @@ export default async function Post({ music }: { music: string }) {
56
70
  | `songFromVideo(title, channel)`, `cleanTitle(title)` | 위의 짐작만 따로 ("가수 - 제목", "가수 '제목'", 유튜브 뮤직의 "가수 - Topic" 채널, `(Official MV)` 같은 꼬리표 지우기) |
57
71
  | `SERVICES`, `getService(id)` | 들을 수 있는 곳 |
58
72
 
59
- 곡 줄은 둘러싼 글의 색을 따르고, 듣기 플러그 창은 Music plug 색이에요. 멈추기 단추의 바탕은 `--mp-ground`로 바꿀 수 있어요.
73
+ ## 모양 바꾸기
74
+
75
+ 기본 화면은 사이트의 글꼴·색을 따르지 않고 늘 같은 모양이에요 (흰 카드, 시스템 고딕). 사이트의 단추 스타일도 끼어들지 않게 막아 뒀어요.
76
+ 어두운 사이트에서는 `theme="dark"`나 `theme="auto"`(기기 설정을 따름). 조금만 바꾸고 싶으면 변수를 덮어써요:
77
+
78
+ ```css
79
+ .mp-ui {
80
+ --mp-radius: 12px; /* 카드 둥글기 */
81
+ --mp-accent: #16161a; /* 재생 단추·고른 곳 테두리 */
82
+ --mp-font: inherit; /* 사이트 글꼴을 쓰고 싶으면 */
83
+ /* --mp-bg, --mp-surface, --mp-ink, --mp-sub, --mp-line, --mp-shadow … */
84
+ }
85
+ ```
86
+
87
+ ## 동작만 쓰기 (headless)
88
+
89
+ 화면을 직접 그리고 싶으면 `@madeinbruno/music-plug/headless`의 훅만 쓰면 돼요. `styles.css`도 필요 없어요. 기본 화면도 이 훅으로 만들어서 동작은 똑같아요.
90
+
91
+ ```tsx
92
+ 'use client';
93
+ import { usePlugPlayer } from '@madeinbruno/music-plug/headless';
94
+ import { SERVICES } from '@madeinbruno/music-plug';
95
+
96
+ function MyPlayer({ song, youtube }) {
97
+ const p = usePlugPlayer({ song, youtube, avoid: '.footer' });
98
+ return (
99
+ <div>
100
+ <button onClick={p.listen}>{p.title} · {p.artist}</button>
101
+ {p.current && <button onClick={p.picker.show}>{p.current.name} 바꾸기</button>}
102
+ {p.picker.open && (
103
+ <ul>
104
+ {p.services.map((s) => (
105
+ <li key={s.id}><button onClick={() => p.listenOn(s)}>{s.name}</button></li>
106
+ ))}
107
+ </ul>
108
+ )}
109
+ {/* YouTube를 이 페이지에서: 유튜브 정책상 플레이어는 보이게 둔다 */}
110
+ {p.video.frameProps && <iframe {...p.video.frameProps} />}
111
+ {p.video.offscreen && <button onClick={p.video.toggle}>{p.video.playing ? '❚❚' : '▶'} {p.title}</button>}
112
+ </div>
113
+ );
114
+ }
115
+ ```
116
+
117
+ | 훅 | 주는 것 |
118
+ |---|---|
119
+ | `usePlugPlayer(options)` | `title`, `artist`, `known`, `services`(들을 수 있는 곳), `current`(기억한 곳), `listen()`, `listenOn(service)`, `picker`(`open`, `show`, `close`), `video`(`open`, `playing`, `toggle`, `offscreen`, `frameProps`). 옵션은 `PlugPlayer`와 같아요 (`artwork`·`theme`·`className` 빼고) |
120
+ | `useSongSearch(options)` | `song`, `value`(form에 넣을 JSON), `searching`, `startSearch`, `stopSearch`, `query`, `setQuery`, `results`, `status`(`idle`·`loading`·`empty`·`error`·`matching`), `pick(found)`, `clear()`, `previewing`, `togglePreview(url)`. 옵션: `defaultValue`, `onChange`, `base` |
121
+ | `readChoice()`, `saveChoice(id)` | 듣는 사람이 고른 곳 읽기·기억하기 (madeinbruno.com 아래에서는 Music plug와 같이) |
60
122
 
61
123
  ## 곡 고르기 (쓰는 사람 화면)
62
124
 
@@ -75,8 +137,9 @@ import { readPickedSong } from '@madeinbruno/music-plug';
75
137
  const song = readPickedSong(form.get('musicSong')); // 믿을 수 있는 모양만 남긴다. 없으면 null
76
138
  ```
77
139
 
140
+ - 검색 칸과 결과가 PlugPlayer와 같은 카드 모양이에요 (`theme`도 같아요). 직접 그리려면 `useSongSearch`.
78
141
  - 치면 Music plug(`/api/search`, Apple 목록)에서 찾아 앨범 그림과 함께 보여 주고, ▶로 30초 미리 들을 수 있어요.
79
- - 고르면 Music plug(`/api/match`)가 그 곡의 유튜브 영상을 찾아 같이 담아요 (`youtube.id`). 글 화면에서는 `<PlugPlayer song={...} youtube={song.youtube} source={{ service: 'apple', url: song.apple }} />`처럼 쓰면 YouTube는 글 안에서 무료로, Apple Music은 그 곡으로 바로 열어요.
142
+ - 고르면 Music plug(`/api/match`)가 그 곡의 유튜브 영상을 찾아 같이 담아요 (`youtube.id`). 글 화면에서는 `<PlugPlayer song={...} artwork={song.artwork} youtube={song.youtube} source={{ service: 'apple', url: song.apple }} />`처럼 쓰면 YouTube는 글 안에서 무료로, Apple Music은 그 곡으로 바로 열어요.
80
143
  - 고른 곡: `PickedSong` = `{ title, artist, album?, artwork?, apple?, youtube?: { id } }`. 따로 부르려면 `searchSongs(q)`, `matchYoutube(song)`.
81
144
 
82
145
  ## Music plug 쪽
@@ -0,0 +1,296 @@
1
+ "use client";
2
+
3
+ // src/headless/usePlugPlayer.ts
4
+ import { useEffect, useRef, useState } from "react";
5
+
6
+ // src/services.ts
7
+ var SERVICES = [
8
+ { id: "here", name: "YouTube", color: "#ff0033", initial: "Y" },
9
+ { id: "ytvideo", name: "YouTube", color: "#ff0033", initial: "Y" },
10
+ { id: "melon", name: "\uBA5C\uB860", color: "#00cd3c", initial: "M" },
11
+ { id: "genie", name: "\uC9C0\uB2C8", color: "#2aa8ff", initial: "G" },
12
+ { id: "bugs", name: "\uBC85\uC2A4", color: "#ff5a3c", initial: "B" },
13
+ { id: "flo", name: "FLO", color: "#7a6bff", initial: "F" },
14
+ { id: "vibe", name: "VIBE", color: "#ff4d8d", initial: "V" },
15
+ { id: "spotify", name: "Spotify", color: "#1ed760", initial: "S" },
16
+ { id: "apple", name: "Apple Music", color: "#fa586a", initial: "A" },
17
+ { id: "youtube", name: "YouTube Music", color: "#ff4444", initial: "Y" }
18
+ ];
19
+ function getService(id) {
20
+ return SERVICES.find((s) => s.id === id);
21
+ }
22
+ var MUSIC_PLUG_URL = "https://musicplug.madeinbruno.com";
23
+ function tail(song, youtube) {
24
+ const p = new URLSearchParams();
25
+ if (song?.title) p.set("t", song.title);
26
+ if (song?.artist) p.set("a", song.artist);
27
+ if (youtube?.id) p.set("v", youtube.id);
28
+ if (youtube?.start) p.set("start", String(youtube.start));
29
+ return p.toString();
30
+ }
31
+ function listenGoUrl(service, song, youtube, { base = MUSIC_PLUG_URL, remember = false } = {}) {
32
+ return `${base}/listen/go?s=${service}${remember ? "&remember=1" : ""}&${tail(song, youtube)}`;
33
+ }
34
+
35
+ // src/youtube.ts
36
+ var YT_ORIGIN = "https://www.youtube-nocookie.com";
37
+ function playerState(raw) {
38
+ let data = raw;
39
+ if (typeof raw === "string") {
40
+ try {
41
+ data = JSON.parse(raw);
42
+ } catch {
43
+ return void 0;
44
+ }
45
+ }
46
+ if (!data || typeof data !== "object") return void 0;
47
+ const { event, info } = data;
48
+ if (event === "onStateChange" && typeof info === "number") return info;
49
+ if (info && typeof info === "object" && typeof info.playerState === "number") {
50
+ return info.playerState;
51
+ }
52
+ return void 0;
53
+ }
54
+
55
+ // src/headless/usePlugPlayer.ts
56
+ var KEY = "musicplug.service";
57
+ var SHARED_DOMAIN = "madeinbruno.com";
58
+ var isYoutube = (id) => id === "here" || id === "ytvideo";
59
+ function readChoice() {
60
+ const cookie = document.cookie.match(/(?:^|;\s*)mp_service=([^;]+)/)?.[1];
61
+ let stored = null;
62
+ try {
63
+ stored = localStorage.getItem(KEY);
64
+ } catch {
65
+ }
66
+ return getService(cookie)?.id ?? getService(stored)?.id ?? null;
67
+ }
68
+ function saveChoice(id) {
69
+ try {
70
+ localStorage.setItem(KEY, id);
71
+ } catch {
72
+ }
73
+ const host = location.hostname;
74
+ const shared = host === SHARED_DOMAIN || host.endsWith(`.${SHARED_DOMAIN}`) ? `; domain=.${SHARED_DOMAIN}` : "";
75
+ document.cookie = `mp_service=${id}; path=/; max-age=31536000; samesite=lax${shared}`;
76
+ }
77
+ function usePlugPlayer({ song, fallbackLabel = "\uC74C\uC545 \uB4E3\uAE30", youtube, source, links, avoid, base = MUSIC_PLUG_URL }) {
78
+ const [choice, setChoice] = useState(null);
79
+ const [sheet, setSheet] = useState(false);
80
+ const [open, setOpen] = useState(false);
81
+ const [playing, setPlaying] = useState(false);
82
+ const [offscreen, setOffscreen] = useState(false);
83
+ const frame = useRef(null);
84
+ const heard = useRef(false);
85
+ useEffect(() => setChoice(readChoice()), []);
86
+ const known = Boolean(song?.title);
87
+ const linked = Boolean(links && Object.keys(links).length);
88
+ const services = SERVICES.filter((s) => s.id === "here" ? Boolean(youtube) : s.id === "ytvideo" ? !youtube : known || Boolean(links?.[s.id]));
89
+ const current = services.find((s) => s.id === choice || isYoutube(choice) && isYoutube(s.id)) ?? null;
90
+ function play(s) {
91
+ if (s.id === "here") {
92
+ setOpen(true);
93
+ setPlaying(true);
94
+ return;
95
+ }
96
+ const viaVideo = Boolean(youtube) && (s.id === "ytvideo" || s.id === "youtube");
97
+ const direct = links?.[s.id] ?? (source && source.service === s.id && !viaVideo ? source.url : null);
98
+ window.open(direct ?? listenGoUrl(s.id, song, youtube, { base }), "_blank", "noopener");
99
+ }
100
+ function listenOn(s) {
101
+ saveChoice(s.id);
102
+ setChoice(s.id);
103
+ setSheet(false);
104
+ play(s);
105
+ }
106
+ function listen() {
107
+ if (!known && !linked && youtube) return play(SERVICES[0]);
108
+ if (!known && !linked && source) return void window.open(source.url, "_blank", "noopener");
109
+ if (current) play(current);
110
+ else setSheet(true);
111
+ }
112
+ const post = (msg) => frame.current?.contentWindow?.postMessage(JSON.stringify(msg), YT_ORIGIN);
113
+ const listening = () => post({ event: "listening", id: "mp" });
114
+ useEffect(() => {
115
+ if (!open) return;
116
+ heard.current = false;
117
+ const onMessage = (e) => {
118
+ if (e.origin !== YT_ORIGIN || e.source !== frame.current?.contentWindow) return;
119
+ const state = playerState(e.data);
120
+ if (state === void 0) return;
121
+ heard.current = true;
122
+ if (state === 1) setPlaying(true);
123
+ else if (state !== 3) setPlaying(false);
124
+ };
125
+ window.addEventListener("message", onMessage);
126
+ let tries = 0;
127
+ const retry = window.setInterval(() => {
128
+ if (heard.current || ++tries > 20) window.clearInterval(retry);
129
+ else listening();
130
+ }, 500);
131
+ const onBack = () => document.visibilityState === "visible" && listening();
132
+ document.addEventListener("visibilitychange", onBack);
133
+ window.addEventListener("pageshow", onBack);
134
+ window.addEventListener("focus", onBack);
135
+ return () => {
136
+ window.removeEventListener("message", onMessage);
137
+ window.clearInterval(retry);
138
+ document.removeEventListener("visibilitychange", onBack);
139
+ window.removeEventListener("pageshow", onBack);
140
+ window.removeEventListener("focus", onBack);
141
+ };
142
+ }, [open]);
143
+ useEffect(() => {
144
+ if (!open) return;
145
+ const seen = /* @__PURE__ */ new Map();
146
+ const io = new IntersectionObserver((entries) => {
147
+ for (const e of entries) seen.set(e.target, e.isIntersecting);
148
+ setOffscreen(![...seen.values()].some(Boolean));
149
+ });
150
+ const targets = [frame.current, avoid ? document.querySelector(avoid) : null].filter((el) => el !== null);
151
+ for (const el of targets) {
152
+ seen.set(el, false);
153
+ io.observe(el);
154
+ }
155
+ return () => io.disconnect();
156
+ }, [open, avoid]);
157
+ const title = song?.title || fallbackLabel;
158
+ return {
159
+ title,
160
+ artist: song?.artist ?? "",
161
+ known,
162
+ services,
163
+ current,
164
+ listen,
165
+ listenOn,
166
+ picker: { open: sheet, show: () => setSheet(true), close: () => setSheet(false) },
167
+ video: {
168
+ open,
169
+ playing,
170
+ offscreen: open && offscreen,
171
+ toggle: () => {
172
+ post({ event: "command", func: playing ? "pauseVideo" : "playVideo", args: [] });
173
+ setPlaying(!playing);
174
+ },
175
+ frameProps: open && youtube ? {
176
+ ref: frame,
177
+ src: `${YT_ORIGIN}/embed/${youtube.id}?autoplay=1&playsinline=1&rel=0&enablejsapi=1&origin=${encodeURIComponent(location.origin)}${youtube.start ? `&start=${youtube.start}` : ""}`,
178
+ title,
179
+ allow: "autoplay; encrypted-media; picture-in-picture",
180
+ allowFullScreen: true,
181
+ onLoad: listening
182
+ } : null
183
+ }
184
+ };
185
+ }
186
+
187
+ // src/headless/useSongSearch.ts
188
+ import { useEffect as useEffect2, useRef as useRef2, useState as useState2 } from "react";
189
+
190
+ // src/picked.ts
191
+ async function searchSongs(query, { base = MUSIC_PLUG_URL, signal } = {}) {
192
+ const res = await fetch(`${base}/api/search?q=${encodeURIComponent(query)}`, { signal });
193
+ const data = await res.json().catch(() => null);
194
+ if (!res.ok || !data?.songs) throw new Error(data?.error ?? "\uC9C0\uAE08\uC740 \uCC3E\uC9C0 \uBABB\uD588\uC5B4\uC694");
195
+ return data.songs;
196
+ }
197
+ async function matchYoutube(song, { base = MUSIC_PLUG_URL } = {}) {
198
+ try {
199
+ const res = await fetch(`${base}/api/match?t=${encodeURIComponent(song.title)}&a=${encodeURIComponent(song.artist)}`);
200
+ const data = await res.json();
201
+ return typeof data.youtube === "string" && /^[\w-]{11}$/.test(data.youtube) ? data.youtube : null;
202
+ } catch {
203
+ return null;
204
+ }
205
+ }
206
+
207
+ // src/headless/useSongSearch.ts
208
+ function useSongSearch({ defaultValue = null, onChange, base = MUSIC_PLUG_URL } = {}) {
209
+ const [song, setSong] = useState2(defaultValue);
210
+ const [searching, setSearching] = useState2(!defaultValue);
211
+ const [query, setQuery] = useState2("");
212
+ const [results, setResults] = useState2([]);
213
+ const [status, setStatus] = useState2("idle");
214
+ const [previewing, setPreviewing] = useState2(null);
215
+ const audio = useRef2(null);
216
+ useEffect2(() => {
217
+ const q = query.trim();
218
+ if (!q) {
219
+ setResults([]);
220
+ setStatus("idle");
221
+ return;
222
+ }
223
+ const ctrl = new AbortController();
224
+ const timer = window.setTimeout(async () => {
225
+ setStatus("loading");
226
+ try {
227
+ const found = await searchSongs(q, { base, signal: ctrl.signal });
228
+ setResults(found);
229
+ setStatus(found.length ? "idle" : "empty");
230
+ } catch {
231
+ if (!ctrl.signal.aborted) setStatus("error");
232
+ }
233
+ }, 350);
234
+ return () => {
235
+ window.clearTimeout(timer);
236
+ ctrl.abort();
237
+ };
238
+ }, [query, base]);
239
+ useEffect2(() => () => audio.current?.pause(), []);
240
+ function stopPreview() {
241
+ audio.current?.pause();
242
+ setPreviewing(null);
243
+ }
244
+ function togglePreview(url) {
245
+ if (!audio.current) {
246
+ audio.current = new Audio();
247
+ audio.current.onended = () => setPreviewing(null);
248
+ }
249
+ if (previewing === url) return stopPreview();
250
+ audio.current.src = url;
251
+ void audio.current.play().catch(() => setPreviewing(null));
252
+ setPreviewing(url);
253
+ }
254
+ function set(next) {
255
+ setSong(next);
256
+ onChange?.(next);
257
+ }
258
+ async function pick(found) {
259
+ stopPreview();
260
+ const { preview: _preview, ...rest } = found;
261
+ void _preview;
262
+ setStatus("matching");
263
+ const youtube = await matchYoutube(found, { base });
264
+ set({ ...rest, ...youtube ? { youtube: { id: youtube } } : {} });
265
+ setSearching(false);
266
+ setQuery("");
267
+ setResults([]);
268
+ setStatus("idle");
269
+ }
270
+ return {
271
+ song,
272
+ value: song ? JSON.stringify(song) : "",
273
+ searching: searching || !song,
274
+ startSearch: () => setSearching(true),
275
+ stopSearch: () => {
276
+ stopPreview();
277
+ setSearching(false);
278
+ setQuery("");
279
+ },
280
+ query,
281
+ setQuery,
282
+ results,
283
+ status,
284
+ pick,
285
+ clear: () => set(null),
286
+ previewing,
287
+ togglePreview
288
+ };
289
+ }
290
+
291
+ export {
292
+ readChoice,
293
+ saveChoice,
294
+ usePlugPlayer,
295
+ useSongSearch
296
+ };
@@ -0,0 +1,2 @@
1
+ export { P as PlugPlayerOptions, e as PlugPlayerState, S as SongSearchOptions, f as SongSearchState, g as SongSearchStatus, r as readChoice, s as saveChoice, u as usePlugPlayer, d as useSongSearch } from './index-CxM1NkLk.js';
2
+ import 'react';
@@ -0,0 +1,13 @@
1
+ "use client";
2
+ import {
3
+ readChoice,
4
+ saveChoice,
5
+ usePlugPlayer,
6
+ useSongSearch
7
+ } from "./chunk-3HM3NTBS.js";
8
+ export {
9
+ readChoice,
10
+ saveChoice,
11
+ usePlugPlayer,
12
+ useSongSearch
13
+ };
@@ -0,0 +1,160 @@
1
+ import { RefObject } from 'react';
2
+
3
+ /**
4
+ * 들을 수 있는 곳. 앱 Music plug(apps/music-plug/src/server/listen.ts)의 목록과 이름(id)이 같다.
5
+ * 고른 곳은 쿠키 mp_service에 두고, madeinbruno.com 아래에서는 Music plug와 같이 쓴다.
6
+ * - here: YouTube를 이 페이지에서 바로 (글 안에 유튜브 플레이어를 연다). 화면에는 그냥 'YouTube'로 보인다
7
+ * - ytvideo: YouTube (앱·사이트)
8
+ * - youtube: YouTube Music (Music plug의 이름을 따른다)
9
+ */
10
+ type ServiceId = 'here' | 'ytvideo' | 'melon' | 'genie' | 'bugs' | 'flo' | 'vibe' | 'spotify' | 'apple' | 'youtube';
11
+ type Service = {
12
+ id: ServiceId;
13
+ name: string;
14
+ color: string;
15
+ initial: string;
16
+ };
17
+
18
+ /** 한 곡. 다른 음원 앱에서 찾을 때 "제목 가수"로 찾는다 */
19
+ type Song = {
20
+ title: string;
21
+ artist: string;
22
+ };
23
+
24
+ /**
25
+ * 곳마다 직접 정해 둔 곡 링크 (예: { melon: 'https://www.melon.com/song/detail.htm?songId=…', apple: '…' }).
26
+ * 곡을 못 찾아 곡까지 가지 않는 곳이 있을 때, 쓰는 사람이 그곳의 곡 링크를 직접 정해 둔다. 정해 둔 곳은 찾지 않고 그 링크를 연다.
27
+ */
28
+ type SongLinks = Partial<Record<ServiceId, string>>;
29
+
30
+ /**
31
+ * 듣기 플러그의 동작만 (화면 없이). 기본 화면(PlugPlayer)도 이 훅으로 만든다.
32
+ * 직접 그리고 싶으면 이 훅이 주는 값과 함수로 원하는 모양을 만들면 된다.
33
+ *
34
+ * - listen(): 곡을 누른 것. 고른 곳이 있으면 바로 그곳에서, 없으면 picker.show()가 필요하다는 뜻으로 picker.open이 true가 된다.
35
+ * - listenOn(service): 이곳에서 듣기 (고른 곳으로 기억한다).
36
+ * - video: YouTube를 이 페이지에서 틀 때. video.open이면 <iframe {...video.frameProps} />를 보이게 둔다 (유튜브 정책상 플레이어는 보여야 한다).
37
+ * video.toggle()로 멈추고 다시 튼다. video.playing은 플레이어에서 직접 멈추거나 브라우저를 나가 저절로 멈춰도 따라간다.
38
+ * video.offscreen은 플레이어도, avoid로 준 요소도 화면에 없을 때 true (떠 있는 작은 음악 바를 보일 때).
39
+ */
40
+ type PlugPlayerOptions = {
41
+ /** 곡 제목·가수. 모르면 null */
42
+ song: Song | null;
43
+ /** 곡을 모를 때 보일 이름 (기본: '음악 듣기') */
44
+ fallbackLabel?: string;
45
+ /** 유튜브 영상. 있으면 YouTube를 고를 때 이 페이지에서 바로 틀고, 없으면 YouTube로 연다 */
46
+ youtube?: {
47
+ id: string;
48
+ start?: number;
49
+ };
50
+ /** 이 곡을 정한 곡 링크 (songFromUrl이 준 service·url). 듣는 사람이 같은 곳을 고르면 그 링크를 바로 연다 */
51
+ source?: {
52
+ service: ServiceId;
53
+ url: string;
54
+ };
55
+ /** 곳마다 직접 정해 둔 곡 링크. 듣는 사람이 그곳을 고르면 찾지 않고 이 링크를 연다 (source보다 먼저) */
56
+ links?: SongLinks | null;
57
+ /** 이 요소가 화면에 보이면 video.offscreen을 false로 (예: 페이지 맨 아래 푸터 '.footer') */
58
+ avoid?: string;
59
+ /** Music plug 주소 (기본 https://musicplug.madeinbruno.com) */
60
+ base?: string;
61
+ };
62
+ type PlugPlayerState = {
63
+ /** 곡 제목 (모르면 fallbackLabel) */
64
+ title: string;
65
+ /** 가수 (모르면 '') */
66
+ artist: string;
67
+ /** 곡을 아는지 (모르면 다른 곳에서 찾을 수 없어 YouTube나 곡 링크로만 연다) */
68
+ known: boolean;
69
+ /** 이 곡을 들을 수 있는 곳 */
70
+ services: Service[];
71
+ /** 기억해 둔 곳 (이 곡에서 쓸 수 있을 때만) */
72
+ current: Service | null;
73
+ /** 곡을 눌렀을 때 */
74
+ listen: () => void;
75
+ /** 이곳에서 듣기 (기억한다) */
76
+ listenOn: (service: Service) => void;
77
+ /** 어디서 들을지 고르는 창 */
78
+ picker: {
79
+ open: boolean;
80
+ show: () => void;
81
+ close: () => void;
82
+ };
83
+ video: {
84
+ open: boolean;
85
+ playing: boolean;
86
+ toggle: () => void;
87
+ offscreen: boolean;
88
+ frameProps: {
89
+ ref: RefObject<HTMLIFrameElement | null>;
90
+ src: string;
91
+ title: string;
92
+ allow: string;
93
+ allowFullScreen: boolean;
94
+ onLoad: () => void;
95
+ } | null;
96
+ };
97
+ };
98
+ /** 기억한 곳. Music plug에서 바꿨을 수도 있으니 같이 쓰는 쿠키를 먼저 본다 */
99
+ declare function readChoice(): ServiceId | null;
100
+ /** 고른 곳 기억하기 (이 브라우저, madeinbruno.com 아래에서는 Music plug와 같이) */
101
+ declare function saveChoice(id: ServiceId): void;
102
+ declare function usePlugPlayer({ song, fallbackLabel, youtube, source, links, avoid, base }: PlugPlayerOptions): PlugPlayerState;
103
+
104
+ /**
105
+ * 곡 고르기(SongField)로 고른 곡. 글에 그대로 저장한다.
106
+ * - youtube: 고를 때 Music plug가 찾아 준 유튜브 영상 (있으면 글 안에서 무료로 바로 튼다)
107
+ * - apple: Apple Music 곡 주소 (듣는 사람이 Apple Music을 고르면 찾지 않고 바로 연다)
108
+ */
109
+ type PickedSong = {
110
+ title: string;
111
+ artist: string;
112
+ album?: string;
113
+ artwork?: string;
114
+ apple?: string;
115
+ youtube?: {
116
+ id: string;
117
+ };
118
+ };
119
+ /** 곡 검색 결과 한 줄 (미리 듣기는 고르는 동안만 쓴다) */
120
+ type FoundSong = Omit<PickedSong, 'youtube'> & {
121
+ preview?: string;
122
+ };
123
+
124
+ /**
125
+ * 곡 고르기의 동작만 (화면 없이). 기본 화면(SongField)도 이 훅으로 만든다.
126
+ *
127
+ * - query를 바꾸면 잠시 기다렸다가 Music plug(/api/search)에서 찾아 results에 넣는다.
128
+ * - pick(found)로 고르면 Music plug(/api/match)가 유튜브 영상을 찾아 같이 담는다 (status가 잠시 'matching').
129
+ * - togglePreview(url)로 30초 미리 듣기 (한 곡씩).
130
+ * - form에 넣을 값은 value (고른 곡 JSON, 없으면 ''). 저장할 때 readPickedSong으로 읽는다.
131
+ */
132
+ type SongSearchOptions = {
133
+ defaultValue?: PickedSong | null;
134
+ /** 고르거나 뺄 때마다 */
135
+ onChange?: (song: PickedSong | null) => void;
136
+ /** Music plug 주소 (기본 https://musicplug.madeinbruno.com) */
137
+ base?: string;
138
+ };
139
+ type SongSearchStatus = 'idle' | 'loading' | 'empty' | 'error' | 'matching';
140
+ type SongSearchState = {
141
+ song: PickedSong | null;
142
+ /** form에 넣을 값 (JSON, 없으면 '') */
143
+ value: string;
144
+ /** 다시 찾는 중인지 (고른 곡이 없으면 늘 true) */
145
+ searching: boolean;
146
+ startSearch: () => void;
147
+ stopSearch: () => void;
148
+ query: string;
149
+ setQuery: (q: string) => void;
150
+ results: FoundSong[];
151
+ status: SongSearchStatus;
152
+ pick: (found: FoundSong) => Promise<void>;
153
+ clear: () => void;
154
+ /** 지금 미리 듣는 곡의 preview 주소 */
155
+ previewing: string | null;
156
+ togglePreview: (url: string) => void;
157
+ };
158
+ declare function useSongSearch({ defaultValue, onChange, base }?: SongSearchOptions): SongSearchState;
159
+
160
+ export { type PlugPlayerOptions as P, type SongSearchOptions as S, type Song as a, type Service as b, type ServiceId as c, useSongSearch as d, type PlugPlayerState as e, type SongSearchState as f, type SongSearchStatus as g, readChoice as r, saveChoice as s, usePlugPlayer as u };
package/dist/index.d.ts CHANGED
@@ -112,6 +112,8 @@ declare const LINKABLE_SERVICES: ServiceId[];
112
112
  */
113
113
  declare function cleanSongLinks(input: unknown): SongLinks | null;
114
114
 
115
+ declare const LOGO_PATHS: Partial<Record<ServiceId, string>>;
116
+
115
117
  /**
116
118
  * 곡 고르기(SongField)로 고른 곡. 글에 그대로 저장한다.
117
119
  * - youtube: 고를 때 Music plug가 찾아 준 유튜브 영상 (있으면 글 안에서 무료로 바로 튼다)
@@ -146,4 +148,4 @@ declare function matchYoutube(song: {
146
148
  base?: string | undefined;
147
149
  }): Promise<string | null>;
148
150
 
149
- export { type FoundSong, LINKABLE_SERVICES, MUSIC_PLUG_URL, type PickedSong, SERVICES, type Service, type ServiceId, type Song, type SongLink, type SongLinks, cleanSongLinks, cleanTitle, getService, linkService, listenGoUrl, listenPageUrl, matchYoutube, readPickedSong, searchSongs, songFromUrl, songFromVideo, songFromYoutube, songQuery, youtubeId, youtubeStart };
151
+ export { type FoundSong, LINKABLE_SERVICES, LOGO_PATHS, MUSIC_PLUG_URL, type PickedSong, SERVICES, type Service, type ServiceId, type Song, type SongLink, type SongLinks, cleanSongLinks, cleanTitle, getService, linkService, listenGoUrl, listenPageUrl, matchYoutube, readPickedSong, searchSongs, songFromUrl, songFromVideo, songFromYoutube, songQuery, youtubeId, youtubeStart };
package/dist/index.js CHANGED
@@ -159,6 +159,16 @@ function cleanSongLinks(input) {
159
159
  return Object.keys(out).length ? out : null;
160
160
  }
161
161
 
162
+ // src/logos.ts
163
+ var YT = "M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z";
164
+ var LOGO_PATHS = {
165
+ here: YT,
166
+ ytvideo: YT,
167
+ spotify: "M12 0C5.4 0 0 5.4 0 12s5.4 12 12 12 12-5.4 12-12S18.66 0 12 0zm5.521 17.34c-.24.359-.66.48-1.021.24-2.82-1.74-6.36-2.101-10.561-1.141-.418.122-.779-.179-.899-.539-.12-.421.18-.78.54-.9 4.56-1.021 8.52-.6 11.64 1.32.42.18.479.659.301 1.02zm1.44-3.3c-.301.42-.841.6-1.262.3-3.239-1.98-8.159-2.58-11.939-1.38-.479.12-1.02-.12-1.14-.6-.12-.48.12-1.021.6-1.141C9.6 9.9 15 10.561 18.72 12.84c.361.181.54.78.241 1.2zm.12-3.36C15.24 8.4 8.82 8.16 5.16 9.301c-.6.179-1.2-.181-1.38-.721-.18-.601.18-1.2.72-1.381 4.26-1.26 11.28-1.02 15.721 1.621.539.3.719 1.02.419 1.56-.299.421-1.02.599-1.559.3z",
168
+ apple: "M23.994 6.124a9.23 9.23 0 00-.24-2.19c-.317-1.31-1.062-2.31-2.18-3.043a5.022 5.022 0 00-1.877-.726 10.496 10.496 0 00-1.564-.15c-.04-.003-.083-.01-.124-.013H5.986c-.152.01-.303.017-.455.026-.747.043-1.49.123-2.193.4-1.336.53-2.3 1.452-2.865 2.78-.192.448-.292.925-.363 1.408-.056.392-.088.785-.1 1.18 0 .032-.007.062-.01.093v12.223c.01.14.017.283.027.424.05.815.154 1.624.497 2.373.65 1.42 1.738 2.353 3.234 2.801.42.127.856.187 1.293.228.555.053 1.11.06 1.667.06h11.03a12.5 12.5 0 001.57-.1c.822-.106 1.596-.35 2.295-.81a5.046 5.046 0 001.88-2.207c.186-.42.293-.87.37-1.324.113-.675.138-1.358.137-2.04-.002-3.8 0-7.595-.003-11.393zm-6.423 3.99v5.712c0 .417-.058.827-.244 1.206-.29.59-.76.962-1.388 1.14-.35.1-.706.157-1.07.173-.95.045-1.773-.6-1.943-1.536a1.88 1.88 0 011.038-2.022c.323-.16.67-.25 1.018-.324.378-.082.758-.153 1.134-.24.274-.063.457-.23.51-.516a.904.904 0 00.02-.193c0-1.815 0-3.63-.002-5.443a.725.725 0 00-.026-.185c-.04-.15-.15-.243-.304-.234-.16.01-.318.035-.475.066-.76.15-1.52.303-2.28.456l-2.325.47-1.374.278c-.016.003-.032.01-.048.013-.277.077-.377.203-.39.49-.002.042 0 .086 0 .13-.002 2.602 0 5.204-.003 7.805 0 .42-.047.836-.215 1.227-.278.64-.77 1.04-1.434 1.233-.35.1-.71.16-1.075.172-.96.036-1.755-.6-1.92-1.544-.14-.812.23-1.685 1.154-2.075.357-.15.73-.232 1.108-.31.287-.06.575-.116.86-.177.383-.083.583-.323.6-.714v-.15c0-2.96 0-5.922.002-8.882 0-.123.013-.25.042-.37.07-.285.273-.448.546-.518.255-.066.515-.112.774-.165.733-.15 1.466-.296 2.2-.444l2.27-.46c.67-.134 1.34-.27 2.01-.403.22-.043.442-.088.663-.106.31-.025.523.17.554.482.008.073.012.148.012.223.002 1.91.002 3.822 0 5.732z",
169
+ youtube: "M12 0C5.376 0 0 5.376 0 12s5.376 12 12 12 12-5.376 12-12S18.624 0 12 0zm0 19.104c-3.924 0-7.104-3.18-7.104-7.104S8.076 4.896 12 4.896s7.104 3.18 7.104 7.104-3.18 7.104-7.104 7.104zm0-13.332c-3.432 0-6.228 2.796-6.228 6.228S8.568 18.228 12 18.228s6.228-2.796 6.228-6.228S15.432 5.772 12 5.772zM9.684 15.54V8.46L15.816 12l-6.132 3.54z"
170
+ };
171
+
162
172
  // src/picked.ts
163
173
  var str = (v, max) => typeof v === "string" && v.trim() ? v.trim().slice(0, max) : void 0;
164
174
  var https = (v) => typeof v === "string" && v.startsWith("https://") && v.length < 1e3 ? v : void 0;
@@ -202,6 +212,7 @@ async function matchYoutube(song, { base = MUSIC_PLUG_URL } = {}) {
202
212
  }
203
213
  export {
204
214
  LINKABLE_SERVICES,
215
+ LOGO_PATHS,
205
216
  MUSIC_PLUG_URL,
206
217
  SERVICES,
207
218
  cleanSongLinks,