-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontent.js
More file actions
2000 lines (1667 loc) · 70.6 KB
/
content.js
File metadata and controls
2000 lines (1667 loc) · 70.6 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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Arena.ai Plus - Adds pricing and other useful data to Arena.ai's leaderboard tables.
* Copyright (C) 2025 Arena.ai Plus
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*/
(function () {
'use strict';
// ============================================
// Configuration
// ============================================
const CONFIG = {
OPENROUTER_URL: 'https://openrouter.ai/api/v1/models',
COLUMN_MARKER: 'data-lmarena-price-injected',
ROW_MARKER: 'data-lmarena-row-processed',
TOOLTIP_SHOW_DELAY: 50,
TOOLTIP_HIDE_DELAY: 100,
TOKEN_UNIT_KEY: 'lmarena-token-unit',
COLUMN_VISIBILITY_KEY: 'lmarena-column-visibility',
BATTLE_NOTIFICATION_KEY: 'lmarena-battle-notification',
DEFAULT_TOKEN_UNIT: 1000000,
DEFAULT_COLUMN_VISIBILITY: {
'bang-for-buck': true,
'model-age': true,
'modalities': true
}
};
// Global settings
let currentTokenUnit = CONFIG.DEFAULT_TOKEN_UNIT;
let currentColumnVisibility = { ...CONFIG.DEFAULT_COLUMN_VISIBILITY };
let battleNotificationEnabled = false;
// Labs view detection
function isLabsView() {
return new URLSearchParams(window.location.search).get('rankBy') === 'labs';
}
// Plain /leaderboard detection — the mixed "all" overview leaderboard.
// Specific leaderboards live at sub-paths like /leaderboard/text, /leaderboard/text-to-image, etc.
// On the root overview there is very little horizontal space, so we only inject Pricing.
function isPlainLeaderboard() {
const path = window.location.pathname;
return path === '/leaderboard' || path === '/leaderboard/';
}
// ============================================
// Token Unit Helpers
// ============================================
function getTokenUnitLabel(unit) {
switch (unit) {
case 1000000: return '1M';
case 100000: return '100K';
default: return '1M';
}
}
function convertCostToUnit(costPer1M, targetUnit) {
return costPer1M * (targetUnit / 1000000);
}
function formatCost(cost) {
return cost.toFixed(2);
}
// ============================================
// Elo per Dollar Helpers (Logarithmic Formula with Rank Penalty)
// ============================================
const ELO_BASELINE = 1000;
// Rank decay base: Each rank gets this % of the previous rank's score
// 1.0 = no penalty (all ranks equal)
// 0.97 = gentle exponential decay (recommended)
// 0.95 = moderate decay
// 0.90 = aggressive decay
const RANK_DECAY_BASE = 0.88;
/**
* Calculate Value Score using logarithmic price compression with exponential rank penalty
* Formula: (Elo - baseline) / log(1 + Price) × RANK_DECAY_BASE^(rank - 1)
*
* This formula compresses the "price penalty" - for a business, the difference
* between $5 and $30 is not "6x the pain", it's just a higher tier of operating cost.
*
* The exponential rank penalty ensures:
* - Top ranks (1-10) are penalized gently
* - Lower ranks (50+) are penalized more aggressively
*
* @param {number} arenaScore - The model's Arena Score (Elo)
* @param {number} inputCostPer1M - Input cost per 1M tokens
* @param {number} outputCostPer1M - Output cost per 1M tokens
* @param {number} rank - The model's rank (1 = best, higher = worse)
* @returns {number|null} - Value score or null if not calculable
*/
function calculateBangForBuck(arenaScore, inputCostPer1M, outputCostPer1M, rank = 1) {
if (!arenaScore || arenaScore <= ELO_BASELINE) return null; // Need Elo > baseline for positive score
const blendedPrice = (inputCostPer1M + outputCostPer1M) / 2;
if (blendedPrice <= 0) return null; // Free models get N/A (can't calculate value ratio)
// Base formula: (Elo - baseline) / log(1 + Price)
const baseScore = (arenaScore - ELO_BASELINE) / Math.log(1 + blendedPrice);
// Apply exponential rank penalty: multiply by RANK_DECAY_BASE^(rank-1)
// Rank 1 gets full score (1.0), each subsequent rank loses a fixed %
const safeRank = Math.max(rank, 1);
const rankMultiplier = Math.pow(RANK_DECAY_BASE, safeRank - 1);
return baseScore * rankMultiplier;
}
async function loadPreferences() {
try {
const result = await chrome.storage.sync.get([
CONFIG.TOKEN_UNIT_KEY,
CONFIG.COLUMN_VISIBILITY_KEY,
CONFIG.BATTLE_NOTIFICATION_KEY
]);
currentTokenUnit = result[CONFIG.TOKEN_UNIT_KEY] || CONFIG.DEFAULT_TOKEN_UNIT;
currentColumnVisibility = result[CONFIG.COLUMN_VISIBILITY_KEY] || { ...CONFIG.DEFAULT_COLUMN_VISIBILITY };
battleNotificationEnabled = result[CONFIG.BATTLE_NOTIFICATION_KEY] ?? true;
} catch (error) {
console.warn('[LMArena Plus] Failed to load preferences:', error);
currentTokenUnit = CONFIG.DEFAULT_TOKEN_UNIT;
currentColumnVisibility = { ...CONFIG.DEFAULT_COLUMN_VISIBILITY };
battleNotificationEnabled = false;
}
}
// ============================================
// Column Visibility Helpers
// ============================================
function applyColumnVisibility() {
const columnVisibilityMap = {
'bang-for-buck': { header: '.lmarena-bfb-header', cell: '.lmarena-bfb-cell' },
'model-age': { header: '.lmarena-age-header', cell: '.lmarena-age-cell' },
'modalities': { header: '.lmarena-mod-header', cell: '.lmarena-mod-cell' }
};
for (const [key, selectors] of Object.entries(columnVisibilityMap)) {
const display = currentColumnVisibility[key] ? '' : 'none';
document.querySelectorAll(selectors.header).forEach(el => el.style.display = display);
document.querySelectorAll(selectors.cell).forEach(el => el.style.display = display);
}
}
// ============================================
// Loading State Manager
// ============================================
class LoadingManager {
setLoading(cells, loading, cellType = 'price') {
const classMap = {
'price': 'lmarena-price-cell--loading',
'bfb': 'lmarena-bfb-cell--loading',
'age': 'lmarena-age-cell--loading',
'ctx': 'lmarena-ctx-cell--loading',
'mod': 'lmarena-mod-cell--loading'
};
const loadingClass = classMap[cellType] || classMap['price'];
cells.forEach(cell => {
if (loading) {
cell.textContent = 'Loading';
cell.classList.add(loadingClass);
cell.classList.remove('lmarena-price-cell--na', 'lmarena-bfb-cell--na', 'lmarena-age-cell--na', 'lmarena-ctx-cell--na', 'lmarena-mod-cell--na');
} else {
cell.classList.remove(loadingClass);
}
});
}
}
// ============================================
// Notification Manager (Simplified)
// ============================================
class NotificationManager {
constructor() {
this.observer = null;
this.lastButtonState = false; // Track if buttons were visible last check
}
start() {
if (this.observer) return;
this._startObserving();
}
stop() {
if (this.observer) {
this.observer.disconnect();
this.observer = null;
}
}
setEnabled(enabled) {
if (enabled) {
this.start();
} else {
this.stop();
}
}
_startObserving() {
this.observer = new MutationObserver(() => {
this._checkForCompletion();
});
this.observer.observe(document.body, {
childList: true,
subtree: true
});
this._checkForCompletion();
}
_checkForCompletion() {
if (!battleNotificationEnabled) return;
// Simple check: look for any voting/rating buttons
const buttons = document.querySelectorAll('button');
let votingButtonsVisible = false;
for (const btn of buttons) {
const text = btn.textContent.toLowerCase();
const ariaLabel = (btn.getAttribute('aria-label') || '').toLowerCase();
// Any of these indicate generation is complete
if (text.includes('is better') ||
text.includes('both are good') ||
text.includes('both are bad') ||
ariaLabel.includes('like this response') ||
ariaLabel.includes('dislike this response')) {
votingButtonsVisible = true;
break;
}
}
// Only notify when buttons first appear (transition from false to true)
if (votingButtonsVisible && !this.lastButtonState) {
this._sendNotification();
}
this.lastButtonState = votingButtonsVisible;
}
async _sendNotification() {
if (!('Notification' in window)) return;
if (Notification.permission === 'default') {
const permission = await Notification.requestPermission();
if (permission !== 'granted') return;
}
if (Notification.permission !== 'granted') return;
// Don't notify if tab is visible, just flash title
if (document.visibilityState === 'visible') {
this._flashTitle();
return;
}
const notification = new Notification('Arena.ai Ready! 🏆', {
body: 'Generation complete - ready to vote!',
icon: chrome.runtime.getURL('icons/icon128.png'),
tag: 'lmarena-ready',
renotify: true,
requireInteraction: false
});
notification.onclick = () => {
window.focus();
notification.close();
};
this._flashTitle();
}
_flashTitle() {
const originalTitle = document.title;
let isFlashing = true;
let flashCount = 0;
const flashInterval = setInterval(() => {
if (flashCount >= 6 || document.visibilityState === 'visible') {
document.title = originalTitle;
clearInterval(flashInterval);
return;
}
document.title = isFlashing ? '🏆 Ready to Vote!' : originalTitle;
isFlashing = !isFlashing;
flashCount++;
}, 1000);
}
}
// ============================================
// Model Matcher Utility (Shared by all services)
// ============================================
const ModelMatcher = {
/**
* Normalize a model name for matching.
* Handles URL encoding, version separators, and whitespace.
*/
normalizeModelName(name) {
if (!name) return '';
return name
.toLowerCase()
.replace(/%3a/gi, ':')
// Normalize versions: 4-5 -> 4.5, 3_5 -> 3.5 (only between single digits)
.replace(/(^|[^0-9])(\d)[-_](\d)(?![0-9])/g, '$1$2.$3')
.replace(/\s+/g, '-')
.trim();
},
/**
* Check if a character position represents a version number continuation.
* This prevents gpt-4 from matching gpt-4.5
*/
_isVersionContinuation(str, pos, key) {
const charAfter = str[pos];
const charAfterPlus1 = str[pos + 1];
return (charAfter === '.' || charAfter === '-') &&
charAfterPlus1 >= '0' && charAfterPlus1 <= '9' &&
key[key.length - 1] >= '0' && key[key.length - 1] <= '9';
},
/**
* Strip common suffixes like -preview, -beta, -latest
*/
_stripSuffixes(normalized) {
return normalized
.replace(/[.-](preview|beta|latest|v\d+)(\b|$)/gi, '')
.replace(/[.-]\d{8}(\b|$)/g, '');
},
/**
* Strip date patterns like -20250929
*/
_stripDates(normalized) {
return normalized
.replace(/[.-]20\d{6}(?=[.-]|$)/g, '')
.replace(/--+/g, '-')
.replace(/[.-]$/, '')
.trim();
},
/**
* Strip thinking variants like (thinking-minimal), -thinking-32k
*/
_stripThinking(normalized) {
return normalized
.replace(/\(thinking[^)]*\)/g, '')
.replace(/[.-]thinking(-[a-z0-9]+)*$/i, '')
.replace(/[.-]thinking$/i, '')
.replace(/--+/g, '-')
.replace(/[.-]$/, '')
.trim();
},
/**
* Core matching logic: find best match in a map using prefix/suffix matching.
* @param {Map} map - The map to search in
* @param {string} searchTerm - The normalized search term
* @param {boolean} checkOperators - Whether to check operator-based matching
* @returns {any} The matched entry or null
*/
_findMatchInMap(map, searchTerm, checkOperators = false) {
// 1. Exact match
if (map.has(searchTerm)) {
return map.get(searchTerm);
}
// 2. Operator-based matching
if (checkOperators) {
let operatorMatch = null;
let operatorMatchLength = 0;
for (const [key, entry] of map) {
if (entry.operator === 'includes' && searchTerm.includes(key)) {
if (key.length > operatorMatchLength) {
operatorMatch = entry;
operatorMatchLength = key.length;
}
}
if (entry.operator === 'startsWith' && searchTerm.startsWith(key)) {
if (key.length > operatorMatchLength) {
operatorMatch = entry;
operatorMatchLength = key.length;
}
}
}
if (operatorMatch) return operatorMatch;
}
// 3. Prefix matching - search term starts with key
let bestMatch = null;
let bestMatchLength = 0;
for (const [key, entry] of map) {
if (searchTerm.startsWith(key)) {
const charAfterKey = searchTerm[key.length];
if (charAfterKey === undefined ||
((charAfterKey === '-' || charAfterKey === '.' || charAfterKey === '/' || charAfterKey === ':') &&
!this._isVersionContinuation(searchTerm, key.length, key))) {
if (key.length > bestMatchLength) {
bestMatch = entry;
bestMatchLength = key.length;
}
}
}
}
if (bestMatch) return bestMatch;
// 4. Suffix matching - key starts with search term
let shortestMatch = null;
let shortestMatchLength = Infinity;
for (const [key, entry] of map) {
if (key.startsWith(searchTerm)) {
const charAfterNormalized = key[searchTerm.length];
if (charAfterNormalized === '-' || charAfterNormalized === '.' || charAfterNormalized === '/' || charAfterNormalized === ':') {
if (key.length < shortestMatchLength) {
shortestMatch = entry;
shortestMatchLength = key.length;
}
}
}
}
return shortestMatch;
},
/**
* Find the best match for a model name in a map.
* Tries multiple normalization strategies in order.
* @param {Map} map - The map to search in
* @param {string} modelName - The original model name
* @param {Object} options - Options: { checkOperators: boolean }
* @returns {any} The matched entry or null
*/
findMatch(map, modelName, options = {}) {
const checkOperators = options.checkOperators || false;
const normalized = this.normalizeModelName(modelName);
// 1. Direct match with normalized name
let result = this._findMatchInMap(map, normalized, checkOperators);
if (result) return result;
// 2. Try without common suffixes
const withoutSuffix = this._stripSuffixes(normalized);
if (withoutSuffix !== normalized) {
result = this._findMatchInMap(map, withoutSuffix, checkOperators);
if (result) return result;
}
// 3. Try without date patterns
const withoutDates = this._stripDates(normalized);
if (withoutDates !== normalized && withoutDates.length > 0) {
result = this._findMatchInMap(map, withoutDates, checkOperators);
if (result) return result;
}
// 4. Try without thinking variants
const withoutThinking = this._stripThinking(normalized);
if (withoutThinking !== normalized && withoutThinking.length > 0) {
result = this._findMatchInMap(map, withoutThinking, checkOperators);
if (result) return result;
}
// 5. Try stripping BOTH dates AND thinking
const withoutDatesAndThinking = this._stripThinking(withoutDates);
if (withoutDatesAndThinking !== normalized &&
withoutDatesAndThinking !== withoutDates &&
withoutDatesAndThinking !== withoutThinking &&
withoutDatesAndThinking.length > 0) {
result = this._findMatchInMap(map, withoutDatesAndThinking, checkOperators);
if (result) return result;
}
return null;
}
};
// ============================================
// Context Service (Always from OpenRouter)
// ============================================
class ContextService {
constructor() {
this.contextMap = new Map();
this.isLoading = false;
}
async initialize() {
this.isLoading = true;
await this._fetchContextData();
this.isLoading = false;
}
async _fetchContextData() {
try {
const response = await fetch(CONFIG.OPENROUTER_URL, { cache: 'no-store' });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
this._buildContextMap(data);
} catch (error) {
console.error('[LMArena Plus] Failed to fetch context data from OpenRouter:', error);
}
}
_buildContextMap(data) {
const models = data.data || [];
for (const model of models) {
if (!model.id) continue;
const key = ModelMatcher.normalizeModelName(model.id);
const hasExplicitModalities = !!(model.architecture?.input_modalities || model.architecture?.output_modalities);
const contextData = {
context_length: model.context_length || null,
created: model.created || null,
input_modalities: model.architecture?.input_modalities || ['text'],
output_modalities: model.architecture?.output_modalities || ['text'],
hasExplicitModalities: hasExplicitModalities,
sourceModelName: model.id
};
if (!this.contextMap.has(key)) {
this.contextMap.set(key, contextData);
}
const shortKey = key.split('/').pop();
if (shortKey && shortKey !== key && !this.contextMap.has(shortKey)) {
this.contextMap.set(shortKey, contextData);
}
}
}
getContext(modelName) {
return ModelMatcher.findMatch(this.contextMap, modelName);
}
}
// ============================================
// Pricing Service (No Caching - Always Fresh)
// ============================================
class PricingService {
constructor() {
this.pricingMap = new Map();
this.isLoading = false;
}
async initialize() {
this.isLoading = true;
await this._fetchPricing();
this.isLoading = false;
}
async _fetchPricing() {
try {
const response = await fetch(CONFIG.OPENROUTER_URL, { cache: 'no-store' });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
this._buildPricingMap(data);
} catch (error) {
console.error('[LMArena Plus] Failed to fetch pricing from OpenRouter:', error);
}
}
_buildPricingMap(data) {
this.pricingMap.clear();
const models = data.data || [];
for (const model of models) {
if (!model.id || !model.pricing) continue;
const key = ModelMatcher.normalizeModelName(model.id);
const promptPrice = parseFloat(model.pricing.prompt) || 0;
const completionPrice = parseFloat(model.pricing.completion) || 0;
const pricing = {
input_cost_per_1m: promptPrice * 1000000,
output_cost_per_1m: completionPrice * 1000000,
sourceModelName: model.id
};
if (!this.pricingMap.has(key)) {
this.pricingMap.set(key, pricing);
}
const shortKey = key.split('/').pop();
if (shortKey && shortKey !== key && !this.pricingMap.has(shortKey)) {
this.pricingMap.set(shortKey, pricing);
}
}
}
getPricing(modelName) {
return ModelMatcher.findMatch(this.pricingMap, modelName);
}
}
// ============================================
// Tooltip Manager
// ============================================
class TooltipManager {
constructor() {
this.tooltip = null;
this.showTimeout = null;
this.hideTimeout = null;
this.currentElement = null;
this.iconUrl = chrome.runtime.getURL('icons/arenaaiplus-icon.svg');
this._createTooltip();
}
_createTooltip() {
this.tooltip = document.createElement('div');
this.tooltip.className = 'lmarena-price-tooltip';
document.body.appendChild(this.tooltip);
}
_prepareShow(element) {
clearTimeout(this.hideTimeout);
const isNewElement = this.currentElement !== element;
if (isNewElement) clearTimeout(this.showTimeout);
this.currentElement = element;
return isNewElement ? CONFIG.TOOLTIP_SHOW_DELAY : 0;
}
_showTooltipContent(element, html, delay) {
this.showTimeout = setTimeout(() => {
this.tooltip.innerHTML = html;
this.tooltip.classList.add('lmarena-price-tooltip--visible');
requestAnimationFrame(() => this._positionTooltip(element));
}, delay);
}
show(element, pricing) {
const delay = this._prepareShow(element);
const inputCost = convertCostToUnit(pricing.input_cost_per_1m || 0, currentTokenUnit);
const outputCost = convertCostToUnit(pricing.output_cost_per_1m || 0, currentTokenUnit);
const sourceModelName = pricing.sourceModelName || 'Unknown model';
this._showTooltipContent(element, `
<div class="lmarena-price-tooltip__header">
<span class="lmarena-price-tooltip__header-title">${sourceModelName}</span>
<span class="lmarena-price-tooltip__header-brand">
<span class="lmarena-price-tooltip__header-brand-text"><em>Arena</em>.ai Plus</span>
<img src="${this.iconUrl}" class="lmarena-price-tooltip__header-icon" alt="">
</span>
</div>
<div class="lmarena-price-tooltip__breakdown">
<div class="lmarena-price-tooltip__row">
<span class="lmarena-price-tooltip__label">Input tokens:</span>
<span class="lmarena-price-tooltip__value">$${formatCost(inputCost)}</span>
</div>
<div class="lmarena-price-tooltip__row">
<span class="lmarena-price-tooltip__label">Output tokens:</span>
<span class="lmarena-price-tooltip__value">$${formatCost(outputCost)}</span>
</div>
</div>
<div class="lmarena-price-tooltip__source">Source: OpenRouter</div>
`, delay);
}
hide() {
clearTimeout(this.showTimeout);
this.hideTimeout = setTimeout(() => {
this.tooltip.classList.remove('lmarena-price-tooltip--visible');
this.currentElement = null;
}, CONFIG.TOOLTIP_HIDE_DELAY);
}
showModalities(element, modData) {
const delay = this._prepareShow(element);
const inputMods = modData.input_modalities || ['text'];
const outputMods = modData.output_modalities || ['text'];
const MODALITY_NAMES = { text: 'Text', image: 'Image', audio: 'Audio', video: 'Video', file: 'File' };
const formatRow = (mods) => mods.map(k => MODALITY_NAMES[k] || k).join(', ') || 'None';
this._showTooltipContent(element, `
<div class="lmarena-price-tooltip__header">
<span class="lmarena-price-tooltip__header-title">Modalities</span>
<span class="lmarena-price-tooltip__header-brand">
<span class="lmarena-price-tooltip__header-brand-text"><em>Arena</em>.ai Plus</span>
<img src="${this.iconUrl}" class="lmarena-price-tooltip__header-icon" alt="">
</span>
</div>
<div class="lmarena-price-tooltip__explanation">
Shows which data types this model can process and generate
</div>
<div class="lmarena-price-tooltip__breakdown">
<div class="lmarena-price-tooltip__row">
<span class="lmarena-price-tooltip__label">Input:</span>
<span class="lmarena-price-tooltip__value">${formatRow(inputMods)}</span>
</div>
<div class="lmarena-price-tooltip__row">
<span class="lmarena-price-tooltip__label">Output:</span>
<span class="lmarena-price-tooltip__value">${formatRow(outputMods)}</span>
</div>
</div>
<div class="lmarena-price-tooltip__source">Source: OpenRouter</div>
`, delay);
}
_positionTooltip(element) {
if (!element || !element.isConnected) return;
const rect = element.getBoundingClientRect();
const tooltipRect = this.tooltip.getBoundingClientRect();
let left = rect.left + (rect.width / 2) - (tooltipRect.width / 2);
let top = rect.top - tooltipRect.height - 8;
const padding = 10;
if (left < padding) left = padding;
if (left + tooltipRect.width > window.innerWidth - padding) {
left = window.innerWidth - tooltipRect.width - padding;
}
if (top < padding) top = rect.bottom + 8;
this.tooltip.style.left = `${left}px`;
this.tooltip.style.top = `${top}px`;
}
showHeaderInfo(element, columnType) {
const delay = this._prepareShow(element);
const info = COLUMN_TOOLTIPS[columnType];
if (!info) return;
this._showTooltipContent(element, `
<div class="lmarena-price-tooltip__header">
<span class="lmarena-price-tooltip__header-title">${info.title}</span>
<span class="lmarena-price-tooltip__header-brand">
<span class="lmarena-price-tooltip__header-brand-text"><em>Arena</em>.ai Plus</span>
<img src="${this.iconUrl}" class="lmarena-price-tooltip__header-icon" alt="">
</span>
</div>
<div class="lmarena-price-tooltip__explanation">${info.description}</div>
<div class="lmarena-price-tooltip__source">Click to sort (where available)</div>
`, delay);
}
}
// ============================================
// Sort Manager
// ============================================
const SORT_ICONS = {
default: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lmarena-sort-icon"><path d="m21 16-4 4-4-4"></path><path d="M17 20V4"></path><path d="m3 8 4-4 4 4"></path><path d="M7 4v16"></path></svg>`,
asc: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lmarena-sort-icon lmarena-sort-icon--active"><path d="m5 12 7-7 7 7"></path><path d="M12 19V5"></path></svg>`,
desc: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lmarena-sort-icon lmarena-sort-icon--active"><path d="M12 5v14"></path><path d="m19 12-7 7-7-7"></path></svg>`
};
class SortManager {
constructor() {
this.currentColumn = null; // 'pricing', 'bfb', 'ctx', 'mod', or null
this.currentDirection = null; // 'asc', 'desc', or null
this.headerButtons = new Map(); // columnType -> button element
this._setupNativeSortListener();
}
_setupNativeSortListener() {
// Listen for clicks on native headers to clear our sort
document.addEventListener('click', (e) => {
const button = e.target.closest('button');
if (!button) return;
const th = button.closest('th');
if (!th) return;
// Check if this is a native header (not our injected ones)
if (th.classList.contains('lmarena-price-header') ||
th.classList.contains('lmarena-bfb-header') ||
th.classList.contains('lmarena-age-header') ||
th.classList.contains('lmarena-ctx-header') ||
th.classList.contains('lmarena-mod-header')) {
return;
}
// A native header was clicked, clear our sort state
this.clearSort();
}, true);
}
registerHeader(columnType, button) {
const oldButton = this.headerButtons.get(columnType);
// If new button is different from old, reset sort state for this column
if (oldButton && oldButton !== button) {
// Clear sort state when buttons change (table was replaced)
if (this.currentColumn === columnType) {
this.currentColumn = null;
this.currentDirection = null;
}
}
this.headerButtons.set(columnType, button);
this._updateButtonIcon(button, 'default');
}
toggleSort(columnType) {
let newDirection;
if (this.currentColumn === columnType) {
// Cycle: desc -> asc -> null
if (this.currentDirection === 'desc') {
newDirection = 'asc';
} else if (this.currentDirection === 'asc') {
newDirection = null;
} else {
newDirection = 'desc';
}
} else {
// New column, start with descending (highest first)
newDirection = 'desc';
}
// Reset all buttons to default
for (const [type, btn] of this.headerButtons) {
this._updateButtonIcon(btn, 'default');
}
if (newDirection) {
this.currentColumn = columnType;
this.currentDirection = newDirection;
const button = this.headerButtons.get(columnType);
if (button) {
this._updateButtonIcon(button, newDirection);
}
this._sortTable(columnType, newDirection);
} else {
this.currentColumn = null;
this.currentDirection = null;
this._restoreOriginalOrder();
}
}
clearSort() {
if (this.currentColumn) {
this.currentColumn = null;
this.currentDirection = null;
for (const [type, btn] of this.headerButtons) {
// Only update buttons that are still connected to DOM
if (btn && btn.isConnected) {
this._updateButtonIcon(btn, 'default');
}
}
// Don't restore order - native sort will handle it
}
}
// Reset all state (call when table content is fully replaced)
reset() {
this.currentColumn = null;
this.currentDirection = null;
this.headerButtons.clear();
}
_updateButtonIcon(button, state) {
// Check if button is still in DOM
if (!button || !button.isConnected) return;
const iconContainer = button.querySelector('.lmarena-sort-icon-container');
if (iconContainer) {
iconContainer.innerHTML = SORT_ICONS[state] || SORT_ICONS.default;
}
}
_sortTable(columnType, direction) {
const tables = document.querySelectorAll('table');
tables.forEach((table, tableIdx) => {
const tbody = table.querySelector('tbody');
if (!tbody) {
return;
}
const rows = Array.from(tbody.querySelectorAll('tr'));
if (rows.length === 0) {
return;
}
// Store original order if not already stored
rows.forEach((row, idx) => {
if (row._lmarenaOriginalIndex === undefined) {
row._lmarenaOriginalIndex = idx;
}
});
// Get the sort value property name based on column type
const valueKey = this._getValueKey(columnType);
// Sort rows
rows.sort((a, b) => {
const aVal = a[valueKey];
const bVal = b[valueKey];
// Handle null/undefined - push to end
if (aVal == null && bVal == null) return 0;
if (aVal == null) return 1;
if (bVal == null) return -1;
const diff = aVal - bVal;
return direction === 'asc' ? diff : -diff;
});
// Re-append rows in sorted order
rows.forEach(row => tbody.appendChild(row));
});
}
_restoreOriginalOrder() {
const tables = document.querySelectorAll('table');
tables.forEach(table => {
const tbody = table.querySelector('tbody');
if (!tbody) return;
const rows = Array.from(tbody.querySelectorAll('tr'));
if (rows.length === 0) return;
// Sort by original index
rows.sort((a, b) => {
const aIdx = a._lmarenaOriginalIndex ?? 0;
const bIdx = b._lmarenaOriginalIndex ?? 0;
return aIdx - bIdx;
});
// Re-append rows in original order
rows.forEach(row => tbody.appendChild(row));
});
}
_getValueKey(columnType) {
switch (columnType) {
case 'pricing': return '_lmarenaPlusPricing';
case 'bfb': return '_lmarenaPlusBfb';
case 'age': return '_lmarenaPlusAge';
case 'ctx': return '_lmarenaPlusCtx';
case 'mod': return '_lmarenaPlusMod';
default: return '_lmarenaPlusPricing';
}
}
}
// ============================================
// Column Injector
// ============================================
class ColumnInjector {
constructor(pricingService, contextService, tooltipManager, loadingManager, sortManager) {
this.pricingService = pricingService;
this.contextService = contextService;
this.tooltipManager = tooltipManager;
this.loadingManager = loadingManager;
this.sortManager = sortManager;
this.processedTables = new WeakSet();
this.injectedBfbCells = [];
this.injectedAgeCells = [];
this.injectedModalitiesCells = [];
}
injectIntoTable(table, showLoading = false) {
const headerRow = this._findHeaderRow(table);
if (!headerRow) return 0;
const modelColumnIndex = this._findModelColumnIndex(headerRow);
if (modelColumnIndex === -1) return 0;
const arenaScoreColumnIndex = this._findArenaScoreColumnIndex(headerRow);
// Check if our headers are actually present in the header row
// LMArena may keep the table element but replace header content, so check DOM directly
const hasOurHeaders = headerRow.querySelector('.lmarena-bfb-header, .lmarena-age-header, .lmarena-mod-header');
if (!hasOurHeaders) {
// Mark table if not already marked
if (!table.hasAttribute(CONFIG.COLUMN_MARKER)) {
table.setAttribute(CONFIG.COLUMN_MARKER, 'true');
this.processedTables.add(table);
}
// Only inject Plus-exclusive columns when there is enough space
if (!isPlainLeaderboard()) {
this._injectBfbHeader(headerRow, showLoading);
this._injectModelAgeHeader(headerRow, showLoading);
this._injectModalitiesHeader(headerRow, showLoading);
}
// Copy sticky/background styles from native headers so ours scroll correctly