Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

import api rather than window.lichess #16632

Merged
merged 1 commit into from
Dec 20, 2024
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
15 changes: 15 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 0 additions & 21 deletions ui/@types/lichess/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,29 +155,8 @@ interface Events {
off(key: string, cb: (...args: any[]) => void): void;
}

interface Api {
initializeDom: (root?: HTMLElement) => void;
events: Events;
socket: {
subscribeToMoveLatency: () => void;
events: Events;
};
onlineFriends: {
request: () => void;
events: Events;
};
chat: {
post: (text: string) => void;
};
overrides: {
[key: string]: (...args: any[]) => unknown;
};
analysis?: any;
}

interface Window {
site: Site;
lichess: Api;
fipr: Fipr;
i18n: I18n;
$as<T>(cash: Cash): T;
Expand Down
2 changes: 1 addition & 1 deletion ui/analyse/src/ctrl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ export default class AnalyseCtrl {
});
pubsub.on('board.change', redraw);
this.persistence?.merge();
window.lichess.analysis = api(this);
(window as any).lichess.analysis = api(this);
}

initialize(data: AnalyseData, merge: boolean): void {
Expand Down
23 changes: 23 additions & 0 deletions ui/api/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "api",
"version": "2.0.0",
"private": true,
"description": "lichess.org browser extension API",
"author": "Thibault Duplessis",
"license": "AGPL-3.0-or-later",
"typings": "api",
"typesVersions": {
"*": {
"*": [
"dist/*"
]
}
},
"exports": {
".": "./src/api.ts",
"./*": "./src/*.ts"
},
"dependencies": {
"common": "workspace:*"
}
}
27 changes: 24 additions & 3 deletions ui/site/src/api.ts → ui/api/src/api.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,34 @@
import type { Pubsub, PubsubCallback, PubsubEvent } from 'common/pubsub';
import { type PubsubCallback, type PubsubEvent, pubsub, initializeDom } from 'common/pubsub';

// #TODO document these somewhere
const publicEvents = ['ply', 'analysis.change', 'chat.resize', 'analysis.closeAll'];
const socketEvents = ['lag', 'close'];
const socketInEvents = ['mlat', 'fen', 'notifications', 'endData'];
const friendsEvents = ['playing', 'stopped_playing', 'onlines', 'enters', 'leaves'];

export const api = (pubsub: Pubsub): Api => ({
initializeDom: (root?: HTMLElement) => pubsub.emit('content-loaded', root),
export interface Api {
initializeDom: (root?: HTMLElement) => void;
events: Events;
socket: {
subscribeToMoveLatency: () => void;
events: Events;
};
onlineFriends: {
request: () => void;
events: Events;
};
chat: {
post: (text: string) => void;
};
overrides: {
[key: string]: (...args: any[]) => unknown;
};
analysis?: any;
}

// this object is available to extensions as window.lichess
export const api: Api = ((window as any).lichess = {
initializeDom,
events: {
on(name: PubsubEvent, cb: PubsubCallback): void {
if (!publicEvents.includes(name)) throw 'This event is not part of the public API';
Expand Down
3 changes: 3 additions & 0 deletions ui/api/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "../tsconfig.base.json"
}
1 change: 1 addition & 0 deletions ui/bits/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"@types/yaireo__tagify": "4.27.0",
"@types/zxcvbn": "^4.4.5",
"@yaireo/tagify": "4.17.9",
"api": "workspace:*",
"canvas-confetti": "^1.9.3",
"chat": "workspace:*",
"chess": "workspace:*",
Expand Down
3 changes: 2 additions & 1 deletion ui/bits/src/bits.challengePage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as xhr from 'common/xhr';
import { wsConnect, wsSend } from 'common/socket';
import { userComplete } from 'common/userComplete';
import { isTouchDevice, isIos } from 'common/device';
import { initializeDom } from 'common/pubsub';

interface ChallengeOpts {
xhrUrl: string;
Expand All @@ -19,7 +20,7 @@ export function initModule(opts: ChallengeOpts): void {
xhr.text(opts.xhrUrl).then(html => {
$(selector).replaceWith($(html).find(selector));
init();
window.lichess.initializeDom($(selector)[0]);
initializeDom($(selector)[0]);
});
},
},
Expand Down
3 changes: 2 additions & 1 deletion ui/bits/src/bits.infiniteScroll.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as xhr from 'common/xhr';
import { spinnerHtml } from 'common/spinner';
import { initializeDom } from 'common/pubsub';

export function initModule(selector: string = '.infinite-scroll'): void {
$(selector).each(function (this: HTMLElement) {
Expand Down Expand Up @@ -36,7 +37,7 @@ function register(el: HTMLElement, selector: string, backoff = 500) {
nav.remove();
$(el).append(($(html).is(selector) ? $(html) : $(html).find(selector)).html());
dedupEntries(el);
window.lichess.initializeDom(el);
initializeDom(el);
setTimeout(() => register(el, selector, backoff * 1.05), backoff); // recursion with backoff
},
e => {
Expand Down
13 changes: 7 additions & 6 deletions ui/bits/src/bits.tvGames.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as xhr from 'common/xhr';
import { pubsub } from 'common/pubsub';
import { pubsub, initializeDom } from 'common/pubsub';
import { api } from 'api';

interface ReplacementResponse {
id: string;
Expand Down Expand Up @@ -28,8 +29,8 @@ const requestReplacementGame = () => {
.json(url.toString())
.then((data: ReplacementResponse) => {
main.find(`.mini-game[href^="/${oldId}"]`).replaceWith(data.html);
if (data.html.includes('mini-game__result')) window.lichess.overrides.tvGamesOnFinish(data.id);
window.lichess.initializeDom();
if (data.html.includes('mini-game__result')) api.overrides.tvGamesOnFinish(data.id);
initializeDom();
})
.then(done, done);
});
Expand All @@ -40,17 +41,17 @@ const done = () => {
requestReplacementGame();
};

window.lichess.overrides.tvGamesOnFinish = (id: string) =>
api.overrides.tvGamesOnFinish = (id: string) =>
setTimeout(() => {
finishedIdQueue.push(id);
requestReplacementGame();
}, 7000); // 7000 matches the rematch wait duration in /modules/tv/main/Tv.scala

site.load.then(() => {
pubsub.on('socket.in.finish', ({ id }) => window.lichess.overrides.tvGamesOnFinish(id));
pubsub.on('socket.in.finish', ({ id }) => api.overrides.tvGamesOnFinish(id));
$('main.tv-games')
.find('.mini-game')
.each((_i, el) => {
if ($(el).find('.mini-game__result').length > 0) window.lichess.overrides.tvGamesOnFinish(getId(el)!);
if ($(el).find('.mini-game__result').length > 0) api.overrides.tvGamesOnFinish(getId(el)!);
});
});
3 changes: 2 additions & 1 deletion ui/bits/src/bits.user.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as xhr from 'common/xhr';
import { makeLinkPopups } from 'common/linkPopup';
import { alert } from 'common/dialog';
import { initializeDom } from 'common/pubsub';

export function initModule(): void {
makeLinkPopups($('.social_links'));
Expand Down Expand Up @@ -47,7 +48,7 @@ export function initModule(): void {
browseTo = (path: string) =>
xhr.text(path).then(html => {
$content.html(html);
window.lichess.initializeDom($content[0]);
initializeDom($content[0]);
history.replaceState({}, '', path);
site.asset.loadEsm('bits.infiniteScroll');
});
Expand Down
1 change: 1 addition & 0 deletions ui/chat/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
".": "./src/chat.ts"
},
"dependencies": {
"api": "workspace:*",
"common": "workspace:*",
"palantir": "workspace:*"
}
Expand Down
3 changes: 2 additions & 1 deletion ui/chat/src/ctrl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { prop } from 'common';
import { storage, type LichessStorage } from 'common/storage';
import { pubsub, type PubsubEvent, type PubsubCallback } from 'common/pubsub';
import { alert } from 'common/dialog';
import { api } from 'api';

export default class ChatCtrl {
data: ChatData;
Expand Down Expand Up @@ -102,7 +103,7 @@ export default class ChatCtrl {
alert('Max length: 140 chars. ' + text.length + ' chars used.');
return false;
}
window.lichess.chat.post(text);
api.chat.post(text);
return true;
};

Expand Down
4 changes: 2 additions & 2 deletions ui/chat/src/moderation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type { ModerationCtrl, ModerationOpts, ModerationData, ModerationReason }
import { numberFormat } from 'common/number';
import { userModInfo, flag, timeout } from './xhr';
import type ChatCtrl from './ctrl';
import { pubsub } from 'common/pubsub';
import { pubsub, initializeDom } from 'common/pubsub';
import { confirm } from 'common/dialog';

export function moderationCtrl(opts: ModerationOpts): ModerationCtrl {
Expand Down Expand Up @@ -158,7 +158,7 @@ export function moderationView(ctrl?: ModerationCtrl): VNode[] | undefined {
{
hook: {
insert() {
window.lichess.initializeDom();
initializeDom();
},
},
},
Expand Down
4 changes: 4 additions & 0 deletions ui/common/src/pubsub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,10 @@ export class Pubsub {

export const pubsub: Pubsub = new Pubsub();

export function initializeDom(root?: HTMLElement): void {
pubsub.emit('content-loaded', root);
}

interface OneTimeHandler {
promise: Promise<void>;
resolve?: () => void;
Expand Down
6 changes: 3 additions & 3 deletions ui/lobby/src/lobby.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as xhr from 'common/xhr';
import main from './main';
import type { LobbyOpts } from './interfaces';
import { wsConnect, wsPingInterval } from 'common/socket';
import { pubsub } from 'common/pubsub';
import { pubsub, initializeDom } from 'common/pubsub';

export function initModule(opts: LobbyOpts) {
opts.appElement = document.querySelector('.lobby__app') as HTMLElement;
Expand Down Expand Up @@ -35,12 +35,12 @@ export function initModule(opts: LobbyOpts) {
reload_timeline() {
xhr.text('/timeline').then(html => {
$('.timeline').html(html);
window.lichess.initializeDom();
initializeDom();
});
},
featured(o: { html: string }) {
$('.lobby__tv').html(o.html);
window.lichess.initializeDom();
initializeDom();
},
redirect(e: RedirectTo) {
lobbyCtrl.setRedirecting();
Expand Down
3 changes: 2 additions & 1 deletion ui/mod/src/mod.user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import tablesort from 'tablesort';
import { expandCheckboxZone, shiftClickCheckboxRange, selector } from './checkBoxes';
import { spinnerHtml } from 'common/spinner';
import { confirm } from 'common/dialog';
import { initializeDom } from 'common/pubsub';

site.load.then(() => {
const $toggle = $('.mod-zone-toggle'),
Expand Down Expand Up @@ -63,7 +64,7 @@ site.load.then(() => {
const getLocationHash = (a: HTMLAnchorElement) => a.href.replace(/.+(#\w+)$/, '$1');

function userMod($inZone: Cash) {
window.lichess.initializeDom($inZone[0]);
initializeDom($inZone[0]);

const makeReady = (selector: string, f: (el: HTMLElement, i: number) => void, cls = 'ready') => {
$inZone.find(selector + `:not(.${cls})`).each(function (this: HTMLElement, i: number) {
Expand Down
3 changes: 2 additions & 1 deletion ui/notify/src/view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { h, type VNode } from 'snabbdom';
import * as licon from 'common/licon';
import { spinnerVdom as spinner } from 'common/spinner';
import makeRenderers from './renderers';
import { initializeDom } from 'common/pubsub';

const renderers = makeRenderers();

Expand Down Expand Up @@ -73,7 +74,7 @@ function clickHook(f: () => void) {
};
}

const contentLoaded = (vnode: VNode) => window.lichess.initializeDom(vnode.elm as HTMLElement);
const contentLoaded = (vnode: VNode) => initializeDom(vnode.elm as HTMLElement);

function recentNotifications(d: NotifyData, scrolling: boolean): VNode {
return h(
Expand Down
4 changes: 2 additions & 2 deletions ui/round/src/round.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { wsConnect, wsDestroy } from 'common/socket';
import { storage } from 'common/storage';
import { setClockWidget } from 'common/clock';
import { makeChat } from 'chat';
import { pubsub } from 'common/pubsub';
import { pubsub, initializeDom } from 'common/pubsub';
import { myUserId } from 'common';
import { alert } from 'common/dialog';

Expand Down Expand Up @@ -76,7 +76,7 @@ async function boot(
$meta.length && $('.game__meta').replaceWith($meta);
$('.crosstable').replaceWith($html.find('.crosstable'));
startTournamentClock();
window.lichess.initializeDom();
initializeDom();
});
},
tourStanding(s: TourPlayer[]) {
Expand Down
4 changes: 2 additions & 2 deletions ui/simul/src/simul.home.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { wsConnect } from 'common/socket';
import { pubsub } from 'common/pubsub';
import { pubsub, initializeDom } from 'common/pubsub';

site.load.then(() => {
wsConnect(`/socket/v5`, false, { params: { flag: 'simul' } });
pubsub.on('socket.in.reload', async () => {
const rsp = await fetch('/simul/reload');
const html = await rsp.text();
$('.simul-list__content').html(html);
window.lichess.initializeDom();
initializeDom();
});
});
1 change: 1 addition & 0 deletions ui/site/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"author": "Thibault Duplessis",
"license": "AGPL-3.0-or-later",
"dependencies": {
"api": "workspace:*",
"chat": "workspace:*",
"chess": "workspace:*",
"common": "workspace:*",
Expand Down
Loading
Loading