-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
339 lines (280 loc) · 15.2 KB
/
Copy pathscript.js
File metadata and controls
339 lines (280 loc) · 15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
// Скрипт для копирования названия трека в формате "Исполнитель - Название"
(function() {
'use strict';
const ADDON_NAME = 'CopyTrackName';
// Глобальные настройки
let currentSettings = null;
// ─── Новое API настроек ───────────────────────────────────────────────────
/**
* Читает значение настройки из объекта настроек.
* Поддерживает как плоские значения, так и объекты вида { value, default }.
*/
function unwrapSetting(entry, fallback) {
if (entry && typeof entry === 'object' && !Array.isArray(entry)) {
if (typeof entry.value !== 'undefined') return entry.value;
if (typeof entry.default !== 'undefined') return entry.default;
}
return typeof entry !== 'undefined' ? entry : fallback;
}
/**
* Возвращает store настроек через window.pulsesyncApi.
* Если API недоступно — возвращает заглушку.
*/
function getAddonSettings(addonName) {
return (
window.pulsesyncApi?.getSettings(addonName) ?? {
getCurrent: () => ({}),
onChange: () => () => {},
}
);
}
/**
* Преобразует «плоский» объект настроек из нового API в формат,
* совместимый с остальным кодом: { key: { value, default } }.
*
* Новое API уже возвращает объект вида:
* { enableCopyIcon: { value: true, default: true }, ... }
* поэтому достаточно просто нормализовать вложенные text-поля.
*/
function normalizeSettings(raw) {
if (!raw || typeof raw !== 'object') return {};
const result = {};
for (const [key, entry] of Object.entries(raw)) {
if (entry && typeof entry === 'object' && !Array.isArray(entry)) {
// Проверяем, является ли это вложенным text-контейнером
// (все значения — тоже объекты с value/default, но без самого value/default на верхнем уровне)
const hasValueOrDefault =
typeof entry.value !== 'undefined' || typeof entry.default !== 'undefined';
if (hasValueOrDefault) {
result[key] = entry;
} else {
// Вложенный контейнер (text с buttons)
result[key] = {};
for (const [subKey, subEntry] of Object.entries(entry)) {
result[key][subKey] = subEntry;
}
}
} else {
result[key] = { value: entry, default: entry };
}
}
return result;
}
// ─── Вспомогательные геттеры ──────────────────────────────────────────────
function getBoolSetting(settings, key, fallback) {
return Boolean(unwrapSetting(settings?.[key], fallback));
}
function getNumSetting(settings, key, fallback) {
return Number(unwrapSetting(settings?.[key], fallback));
}
function getStrSetting(settings, key, fallback) {
return String(unwrapSetting(settings?.[key], fallback));
}
// ─── Цвет иконки ─────────────────────────────────────────────────────────
function getTextColor() {
return 'var(--ym-controls-color-primary-text-enabled_variant, #ffffff)';
}
// ─── Создание иконки ──────────────────────────────────────────────────────
function createCopyIcon(settings) {
const iconSize = getNumSetting(settings, 'iconSize', 16);
const iconOpacity = getNumSetting(settings, 'iconOpacity', 70) / 100;
const useStatic = getBoolSetting(settings, 'iconColor', false);
const iconColor = useStatic
? getStrSetting(settings, 'customColor', '#ffffff')
: getTextColor();
const icon = document.createElement('button');
icon.innerHTML = `
<svg width="${iconSize}" height="${iconSize}" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M16 1H4C2.9 1 2 1.9 2 3V17H4V3H16V1ZM19 5H8C6.9 5 6 5.9 6 7V21C6 22.1 6.9 23 8 23H19C20.1 23 21 22.1 21 21V7C21 5.9 20.1 5 19 5ZM19 21H8V7H19V21Z" fill="currentColor"/>
</svg>
`;
icon.style.cssText = `
background: transparent;
border: none;
cursor: pointer;
padding: 4px;
display: inline-flex;
align-items: center;
justify-content: center;
opacity: ${iconOpacity};
transition: opacity 0.2s, color 0.2s;
margin-left: 8px;
vertical-align: middle;
color: ${iconColor};
`;
icon.title = 'Копировать название трека';
icon.dataset.baseOpacity = iconOpacity;
icon.addEventListener('mouseenter', () => { icon.style.opacity = '1'; });
icon.addEventListener('mouseleave', () => { icon.style.opacity = iconOpacity.toString(); });
return icon;
}
// ─── Буфер обмена ─────────────────────────────────────────────────────────
async function copyToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
return true;
} catch (err) {
console.error('Ошибка копирования:', err);
return false;
}
}
// ─── Уведомление ─────────────────────────────────────────────────────────
function showNotification(message, success = true, settings) {
if (settings && !getBoolSetting(settings, 'showNotification', true)) return;
const notification = document.createElement('div');
notification.textContent = message;
notification.style.cssText = `
position: fixed;
bottom: 20px;
right: 20px;
background: ${success ? '#4CAF50' : '#f44336'};
color: white;
padding: 12px 24px;
border-radius: 4px;
z-index: 10000;
font-size: 14px;
box-shadow: 0 2px 8px rgba(0,0,0,0.3);
animation: slideIn 0.3s ease-out;
`;
document.body.appendChild(notification);
setTimeout(() => {
notification.style.animation = 'slideOut 0.3s ease-out';
setTimeout(() => notification.remove(), 300);
}, 2000);
}
// Анимации уведомления
const style = document.createElement('style');
style.textContent = `
@keyframes slideIn {
from { transform: translateX(400px); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
@keyframes slideOut {
from { transform: translateX(0); opacity: 1; }
to { transform: translateX(400px); opacity: 0; }
}
`;
document.head.appendChild(style);
// ─── Информация о треке ───────────────────────────────────────────────────
function extractTrackInfo(metaContainer, settings) {
const titleElement = metaContainer.querySelector('[data-test-id="TRACK_TITLE"] .Meta_title__GGBnH');
const artistElement = metaContainer.querySelector('[data-test-id="SEPARATED_ARTIST_TITLE"] .Meta_artistCaption__JESZi');
if (!titleElement || !artistElement) return null;
const title = titleElement.textContent.trim();
const artist = artistElement.textContent.trim();
// Пользовательский формат
if (getBoolSetting(settings, 'enableCustomFormat', false)) {
const customFormat = unwrapSetting(settings?.customFormat?.customFormatText, '{artist} - {title}');
return String(customFormat).replace('{artist}', artist).replace('{title}', title);
}
// Стандартные форматы
switch (getNumSetting(settings, 'copyFormat', 1)) {
case 1: return `${artist} - ${title}`;
case 2: return `${title} - ${artist}`;
case 3: return artist;
case 4: return title;
default: return `${artist} - ${title}`;
}
}
// ─── Иконка в DOM ─────────────────────────────────────────────────────────
function addCopyIconToMeta(metaContainer, settings, forceUpdate = false) {
const titleContainer = metaContainer.querySelector('.Meta_titleContainer__gDuXr');
if (!titleContainer) return;
const existingIcon = metaContainer.querySelector('.copy-track-icon');
if (!getBoolSetting(settings, 'enableCopyIcon', true)) {
existingIcon?.remove();
return;
}
if (existingIcon && forceUpdate) {
existingIcon.remove();
} else if (existingIcon && !forceUpdate) {
return;
}
const copyIcon = createCopyIcon(settings);
copyIcon.classList.add('copy-track-icon');
copyIcon.addEventListener('click', async (e) => {
e.preventDefault();
e.stopPropagation();
const trackInfo = extractTrackInfo(metaContainer, currentSettings);
if (trackInfo) {
const success = await copyToClipboard(trackInfo);
showNotification(
success ? 'Скопировано: ' + trackInfo : 'Ошибка копирования',
success,
currentSettings
);
} else {
showNotification('Не удалось получить информацию о треке', false, currentSettings);
}
});
titleContainer.appendChild(copyIcon);
}
function processMetaContainers(settings, forceUpdate = false) {
document.querySelectorAll('.Meta_root__R8n1h').forEach(container => {
addCopyIconToMeta(container, settings, forceUpdate);
});
}
// ─── Обновление существующих иконок ──────────────────────────────────────
function updateIconColors(settings) {
const useStatic = getBoolSetting(settings, 'iconColor', false);
const color = useStatic
? getStrSetting(settings, 'customColor', '#ffffff')
: getTextColor();
document.querySelectorAll('.copy-track-icon').forEach(icon => {
icon.style.color = color;
});
}
function updateIconSizes(settings) {
const iconSize = getNumSetting(settings, 'iconSize', 16);
document.querySelectorAll('.copy-track-icon svg').forEach(svg => {
svg.setAttribute('width', iconSize);
svg.setAttribute('height', iconSize);
});
}
function updateIconOpacity(settings) {
const iconOpacity = getNumSetting(settings, 'iconOpacity', 70) / 100;
document.querySelectorAll('.copy-track-icon').forEach(icon => {
icon.style.opacity = iconOpacity.toString();
icon.dataset.baseOpacity = iconOpacity;
});
}
// ─── Применение изменившихся настроек ────────────────────────────────────
function applySettings(nextSettings, prevSettings) {
const colorChanged =
getBoolSetting(nextSettings, 'iconColor', false) !== getBoolSetting(prevSettings, 'iconColor', false) ||
getStrSetting(nextSettings, 'customColor', '#ffffff') !== getStrSetting(prevSettings, 'customColor', '#ffffff');
const sizeChanged = getNumSetting(nextSettings, 'iconSize', 16) !== getNumSetting(prevSettings, 'iconSize', 16);
const opacityChanged = getNumSetting(nextSettings, 'iconOpacity', 70) !== getNumSetting(prevSettings, 'iconOpacity', 70);
const enableChanged = getBoolSetting(nextSettings, 'enableCopyIcon', true) !== getBoolSetting(prevSettings, 'enableCopyIcon', true);
if (colorChanged) updateIconColors(nextSettings);
if (sizeChanged) updateIconSizes(nextSettings);
if (opacityChanged) updateIconOpacity(nextSettings);
if (enableChanged) processMetaContainers(nextSettings, true);
}
// ─── Наблюдатель за DOM ───────────────────────────────────────────────────
const observer = new MutationObserver(() => {
processMetaContainers(currentSettings);
});
observer.observe(document.body, { childList: true, subtree: true });
// Периодическое обновление динамического цвета
setInterval(() => {
if (currentSettings && !getBoolSetting(currentSettings, 'iconColor', false)) {
updateIconColors(currentSettings);
}
}, 1000);
// ─── Инициализация через новое API ───────────────────────────────────────
const settingsStore = getAddonSettings(ADDON_NAME);
// Первичная загрузка
currentSettings = normalizeSettings(settingsStore.getCurrent());
processMetaContainers(currentSettings, false);
// Реактивное обновление при изменении настроек пользователем
settingsStore.onChange(rawNext => {
const nextSettings = normalizeSettings(rawNext);
if (currentSettings) {
applySettings(nextSettings, currentSettings);
}
currentSettings = nextSettings;
processMetaContainers(currentSettings, false);
});
console.log('CopyTrackName скрипт загружен (новое API)');
})();