Skip to content

Commit

Permalink
tweak, type and use window.lichess
Browse files Browse the repository at this point in the history
  • Loading branch information
ornicar committed Oct 31, 2024
1 parent 4343565 commit 0a8e0af
Show file tree
Hide file tree
Showing 16 changed files with 53 additions and 59 deletions.
5 changes: 5 additions & 0 deletions ui/@types/lichess/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,8 +161,13 @@ interface Fipr {
x64hash128(input: string, seed: number): string;
}

interface Api {

This comment has been minimized.

Copy link
@schlawg

schlawg Dec 17, 2024

Collaborator

My understanding is Api was intended (at least initially) for extensions, but it's a bit curious that we are also calling api.initializeDOM from various places as if it were part of site (which is being slowly demolished).

About index.d.ts, as these declarations are only visible in our monorepo, i guess typing Api here avoids some thorny circular dependency?

initializeDom: (root?: HTMLElement) => void;
}

interface Window {
site: Site;
lichess: Api;
fipr: Fipr;
i18n: I18n;
$as<T>(cash: Cash): T;
Expand Down
3 changes: 1 addition & 2 deletions ui/bits/src/bits.challengePage.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import * as xhr from 'common/xhr';
import StrongSocket from 'common/socket';
import { userComplete } from 'common/userComplete';
import { pubsub } from 'common/pubsub';

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

export function initModule(selector: string = '.infinite-scroll'): void {
$(selector).each(function (this: HTMLElement) {
Expand Down Expand Up @@ -37,7 +36,7 @@ function register(el: HTMLElement, selector: string, backoff = 500) {
nav.remove();
$(el).append(($(html).is(selector) ? $(html) : $(html).find(selector)).html());
dedupEntries(el);
pubsub.emit('content-loaded', el);
window.lichess.initializeDom(el);
setTimeout(() => register(el, selector, backoff * 1.05), backoff); // recursion with backoff
},
e => {
Expand Down
2 changes: 1 addition & 1 deletion ui/bits/src/bits.tvGames.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const requestReplacementGame = () => {
.then((data: ReplacementResponse) => {
main.find(`.mini-game[href^="/${oldId}"]`).replaceWith(data.html);
if (data.html.includes('mini-game__result')) onFinish(data.id);
pubsub.emit('content-loaded');
window.lichess.initializeDom();
})
.then(done, done);
});
Expand Down
3 changes: 1 addition & 2 deletions ui/bits/src/bits.user.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import * as xhr from 'common/xhr';
import { makeLinkPopups } from 'common/linkPopup';
import { pubsub } from 'common/pubsub';
import { alert } from 'common/dialog';

export function initModule(): void {
Expand Down Expand Up @@ -48,7 +47,7 @@ export function initModule(): void {
browseTo = (path: string) =>
xhr.text(path).then(html => {
$content.html(html);
pubsub.emit('content-loaded', $content[0]);
window.lichess.initializeDom($content[0]);
history.replaceState({}, '', path);
site.asset.loadEsm('bits.infiniteScroll');
});
Expand Down
2 changes: 1 addition & 1 deletion ui/chat/src/moderation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ export function moderationView(ctrl?: ModerationCtrl): VNode[] | undefined {
{
hook: {
insert() {
pubsub.emit('content-loaded');
window.lichess.initializeDom();
},
},
},
Expand Down
2 changes: 1 addition & 1 deletion ui/common/src/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ export default class StrongSocket implements SocketI {
const mix = this.pongCount > 4 ? 0.1 : 1 / this.pongCount;
this.averageLag += mix * (currentLag - this.averageLag);

pubsub.emit('socket.in.pong', this.averageLag);
pubsub.emit('socket.lag', this.averageLag);
this.updateStats(currentLag);
};

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

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

function userMod($inZone: Cash) {
pubsub.emit('content-loaded', $inZone[0]);
window.lichess.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: 1 addition & 2 deletions ui/notify/src/view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { h, VNode } from 'snabbdom';
import * as licon from 'common/licon';
import { spinnerVdom as spinner } from 'common/spinner';
import makeRenderers from './renderers';
import { pubsub } from 'common/pubsub';

const renderers = makeRenderers();

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

const contentLoaded = (vnode: VNode) => pubsub.emit('content-loaded', vnode.elm);
const contentLoaded = (vnode: VNode) => window.lichess.initializeDom(vnode.elm as HTMLElement);

function recentNotifications(d: NotifyData, scrolling: boolean): VNode {
return h(
Expand Down
2 changes: 1 addition & 1 deletion ui/round/src/round.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ async function boot(
$meta.length && $('.game__meta').replaceWith($meta);
$('.crosstable').replaceWith($html.find('.crosstable'));
startTournamentClock();
pubsub.emit('content-loaded');
window.lichess.initializeDom();
});
},
tourStanding(s: TourPlayer[]) {
Expand Down
2 changes: 1 addition & 1 deletion ui/simul/src/simul.home.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@ site.load.then(() => {
const rsp = await fetch('/simul/reload');
const html = await rsp.text();
$('.simul-list__content').html(html);
pubsub.emit('content-loaded');
window.lichess.initializeDom();
});
});
3 changes: 1 addition & 2 deletions ui/site/src/announce.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { escapeHtml } from 'common';
import { pubsub } from 'common/pubsub';

let timeout: Timeout | undefined;

Expand All @@ -25,7 +24,7 @@ const announce = (d: LichessAnnouncement) => {
const millis = d.date ? new Date(d.date).getTime() - Date.now() : 5000;
if (millis > 0) timeout = setTimeout(kill, millis);
else kill();
if (d.date) pubsub.emit('content-loaded');
if (d.date) window.lichess.initializeDom();
}
};

Expand Down
70 changes: 33 additions & 37 deletions ui/site/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,51 +2,47 @@ import { Pubsub, PubsubCallback, PubsubEvent } from 'common/pubsub';

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

export const api = (ps: Pubsub) => ({
initializeDom: (root?: HTMLElement) => ps.emit('content-loaded', root),
export const api = (pubsub: Pubsub) => ({
initializeDom: (root?: HTMLElement) => pubsub.emit('content-loaded', root),
events: {
on(name: PubsubEvent, cb: PubsubCallback): void {
if (!publicEvents.includes(name)) throw 'This event is not part of the public API';
ps.on(name, cb);
pubsub.on(name, cb);
},
off(name: PubsubEvent, cb: PubsubCallback): void {
ps.off(name, cb);
pubsub.off(name, cb);
},
},
socket: (() => {
const inKeys = ['mlat', 'fen', 'notifications', 'endData'];
const keys = ['lag', 'close'];
return {
subscribeToMoveLatency: () => ps.emit('socket.send', 'moveLat', true),
events: {
on(key: string, cb: PubsubCallback): void {
if (inKeys.includes(key)) ps.on(`socket.in.${key}` as PubsubEvent, cb);
else if (keys.includes(key)) ps.on(`socket.${key}` as PubsubEvent, cb);
else throw 'This event is not part of the public API';
},
off(key: string, cb: PubsubCallback): void {
const ev = inKeys.includes(key)
? (`socket.in.${key}` as PubsubEvent)
: (`socket.${key}` as PubsubEvent);
ps.off(ev, cb);
},
socket: {
subscribeToMoveLatency: () => pubsub.emit('socket.send', 'moveLat', true),
events: {
on(key: string, cb: PubsubCallback): void {
if (socketInEvents.includes(key)) pubsub.on(`socket.in.${key}` as PubsubEvent, cb);
else if (socketEvents.includes(key)) pubsub.on(`socket.${key}` as PubsubEvent, cb);
else throw 'This event is not part of the public API';
},
};
})(),
onlineFriends: (() => {
const keys = ['playing', 'stopped_playing', 'onlines', 'enters', 'leaves'];
return {
request: () => ps.emit('socket.send', 'following_onlines'),
events: {
on(key: string, cb: PubsubCallback): void {
if (!keys.includes(key)) throw 'This event is not part of the public API';
ps.on(`socket.in.following_${key}` as PubsubEvent, cb);
},
off(key: string, cb: PubsubCallback): void {
ps.off(`socket.in.following_${key}` as PubsubEvent, cb);
},
off(key: string, cb: PubsubCallback): void {
const ev = socketInEvents.includes(key)
? (`socket.in.${key}` as PubsubEvent)
: (`socket.${key}` as PubsubEvent);
pubsub.off(ev, cb);
},
};
})(),
},
},
onlineFriends: {
request: () => pubsub.emit('socket.send', 'following_onlines'),
events: {
on(key: string, cb: PubsubCallback): void {
if (!friendsEvents.includes(key)) throw 'This event is not part of the public API';
pubsub.on(`socket.in.following_${key}` as PubsubEvent, cb);
},
off(key: string, cb: PubsubCallback): void {
pubsub.off(`socket.in.following_${key}` as PubsubEvent, cb);
},
},
},
});
3 changes: 1 addition & 2 deletions ui/site/src/powertip.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import * as licon from 'common/licon';
import * as xhr from 'common/xhr';
import { requestIdleCallback, $as } from 'common';
import { spinnerHtml } from 'common/spinner';
import { pubsub } from 'common/pubsub';

// Thanks Steven Benner! - adapted from https://github.com/stevenbenner/jquery-powertip

Expand All @@ -14,7 +13,7 @@ const onPowertipPreRender = (id: string, preload?: (url: string) => void) => (el
xhr.text(url + '/mini').then(html => {
const el = document.getElementById(id) as HTMLElement;
el.innerHTML = html;
pubsub.emit('content-loaded', el);
window.lichess.initializeDom(el);
});
};

Expand Down
2 changes: 1 addition & 1 deletion ui/site/src/site.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,4 @@ site.sound = sound;
site.load.then(boot);

// public API
(window as any).lichess = api(pubsub);
window.lichess = api(pubsub);

0 comments on commit 0a8e0af

Please sign in to comment.