Skip to content

Commit

Permalink
use async versions of alert, confirm, and prompt
Browse files Browse the repository at this point in the history
  • Loading branch information
schlawg committed Oct 27, 2024
1 parent fdef02d commit 6db4544
Show file tree
Hide file tree
Showing 43 changed files with 227 additions and 118 deletions.
7 changes: 4 additions & 3 deletions ui/analyse/src/ctrl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ import ForecastCtrl from './forecast/forecastCtrl';
import { ArrowKey, KeyboardMove, ctrl as makeKeyboardMove } from 'keyboardMove';
import * as control from './control';
import { PgnError } from 'chessops/pgn';
import { confirm } from 'common/dialog';

export default class AnalyseCtrl {
data: AnalyseData;
Expand Down Expand Up @@ -611,18 +612,18 @@ export default class AnalyseCtrl {
this.withCg(cg => cg.playPremove());
}

deleteNode(path: Tree.Path): void {
async deleteNode(path: Tree.Path): Promise<void> {
const node = this.tree.nodeAtPath(path);
if (!node) return;
const count = treeOps.countChildrenAndComments(node);
if (
(count.nodes >= 10 || count.comments > 0) &&
!confirm(
!(await confirm(
'Delete ' +
plural('move', count.nodes) +
(count.comments ? ' and ' + plural('comment', count.comments) : '') +
'?',
)
))
)
return;
this.tree.deleteNodeAt(path);
Expand Down
15 changes: 8 additions & 7 deletions ui/analyse/src/serverSideUnderboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { url as xhrUrl, textRaw as xhrTextRaw } from 'common/xhr';
import { AnalyseData } from './interfaces';
import { ChartGame, AcplChart } from 'chart';
import { stockfishName, spinnerHtml } from 'common/spinner';
import { domDialog } from 'common/dialog';
import { alert, confirm, domDialog } from 'common/dialog';
import { FEN } from 'chessground/types';
import { escapeHtml } from 'common';
import { storage } from 'common/storage';
Expand Down Expand Up @@ -118,21 +118,22 @@ export default function (element: HTMLElement, ctrl: AnalyseCtrl) {
($menuCt.length ? $menuCt : $menu.children(':first-child')).trigger('mousedown');
}
if (!data.analysis) {
$panels.find('form.future-game-analysis').on('submit', function (this: HTMLFormElement) {
$panels.find('form.future-game-analysis').on('submit', async function (this: HTMLFormElement, e: Event) {
if ($(this).hasClass('must-login')) {
if (confirm(i18n.site.youNeedAnAccountToDoThat))
location.href = '/login?referrer=' + window.location.pathname;
e.preventDefault();
confirm(i18n.site.youNeedAnAccountToDoThat, i18n.site.signIn, i18n.site.cancel).then(yes => {
if (yes) location.href = '/login?referrer=' + window.location.pathname;
});
return false;
}
xhrTextRaw(this.action, { method: this.method }).then(res => {
if (res.ok) startAdvantageChart();
else
res.text().then(t => {
if (t && !t.startsWith('<!DOCTYPE html>')) alert(t);
site.reload();
if (t && !t.startsWith('<!DOCTYPE html>')) alert(t).then(site.reload);
});
});
return false;
return true;
});
}

Expand Down
14 changes: 7 additions & 7 deletions ui/analyse/src/study/chapterEditForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { spinnerVdom as spinner } from 'common/spinner';
import { option, emptyRedButton } from '../view/util';
import { ChapterMode, EditChapterData, Orientation, StudyChapterConfig, ChapterPreview } from './interfaces';
import { defined, prop } from 'common';
import { snabDialog } from 'common/dialog';
import { confirm, snabDialog } from 'common/dialog';
import { h, VNode } from 'snabbdom';
import { Redraw } from '../interfaces';
import { StudySocketSend } from '../socket';
Expand Down Expand Up @@ -142,8 +142,8 @@ function viewLoaded(ctrl: StudyChapterEditForm, data: StudyChapterConfig): VNode
{
hook: bind(
'click',
() => {
if (confirm(i18n.study.clearAllCommentsInThisChapter)) ctrl.clearAnnotations(data.id);
async () => {
if (await confirm(i18n.study.clearAllCommentsInThisChapter)) ctrl.clearAnnotations(data.id);
},
ctrl.redraw,
),
Expand All @@ -156,8 +156,8 @@ function viewLoaded(ctrl: StudyChapterEditForm, data: StudyChapterConfig): VNode
{
hook: bind(
'click',
() => {
if (confirm(i18n.study.clearVariations)) ctrl.clearVariations(data.id);
async () => {
if (await confirm(i18n.study.clearVariations)) ctrl.clearVariations(data.id);
},
ctrl.redraw,
),
Expand All @@ -172,8 +172,8 @@ function viewLoaded(ctrl: StudyChapterEditForm, data: StudyChapterConfig): VNode
{
hook: bind(
'click',
() => {
if (confirm(i18n.study.deleteThisChapter)) ctrl.delete(data.id);
async () => {
if (await confirm(i18n.study.deleteThisChapter)) ctrl.delete(data.id);
},
ctrl.redraw,
),
Expand Down
5 changes: 3 additions & 2 deletions ui/analyse/src/study/description.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as licon from 'common/licon';
import { bind, onInsert, looseH as h } from 'common/snabbdom';
import { richHTML } from 'common/richText';
import StudyCtrl from './studyCtrl';
import { confirm } from 'common/dialog';

export type Save = (t: string) => void;

Expand Down Expand Up @@ -46,8 +47,8 @@ export function view(study: StudyCtrl, chapter: boolean): VNode | undefined {
}),
h('a', {
attrs: { 'data-icon': licon.Trash, title: 'Delete' },
hook: bind('click', () => {
if (confirm('Delete permanent description?')) desc.save('');
hook: bind('click', async () => {
if (await confirm('Delete permanent description?')) desc.save('');
}),
}),
]),
Expand Down
1 change: 1 addition & 0 deletions ui/analyse/src/study/studyChapters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { fenColor } from 'common/miniBoard';
import { initialFen } from 'chess';
import type Sortable from 'sortablejs';
import { pubsub } from 'common/pubsub';
import { alert } from 'common/dialog';

/* read-only interface for external use */
export class StudyChapters {
Expand Down
15 changes: 7 additions & 8 deletions ui/analyse/src/study/studyComments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { richHTML } from 'common/richText';
import AnalyseCtrl from '../ctrl';
import { nodeFullName } from '../view/util';
import StudyCtrl from './studyCtrl';
import { confirm } from 'common/dialog';

export type AuthorObj = {
id: string;
Expand Down Expand Up @@ -40,14 +41,12 @@ export function currentComments(ctrl: AnalyseCtrl, includingMine: boolean): VNod
study.members.canContribute() && study.vm.mode.write
? h('a.edit', {
attrs: { 'data-icon': licon.Trash, title: 'Delete' },
hook: bind(
'click',
() => {
if (confirm('Delete ' + authorText(by) + "'s comment?"))
study.commentForm.delete(chapter.id, ctrl.path, comment.id);
},
ctrl.redraw,
),
hook: bind('click', async () => {
if (await confirm('Delete ' + authorText(by) + "'s comment?")) {
study.commentForm.delete(chapter.id, ctrl.path, comment.id);
ctrl.redraw();
}
}),
})
: null,
authorDom(by),
Expand Down
1 change: 1 addition & 0 deletions ui/analyse/src/study/studyCtrl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import { GamebookOverride } from './gamebook/interfaces';
import { EvalHitMulti, EvalHitMultiArray } from '../interfaces';
import { MultiCloudEval } from './multiCloudEval';
import { pubsub } from 'common/pubsub';
import { alert } from 'common/dialog';

interface Handlers {
path(d: WithWhoAndPos): void;
Expand Down
22 changes: 15 additions & 7 deletions ui/analyse/src/study/studyForm.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { VNode } from 'snabbdom';
import * as licon from 'common/licon';
import { prop } from 'common';
import { snabDialog } from 'common/dialog';
import { confirm, prompt, snabDialog } from 'common/dialog';
import flairPickerLoader from 'bits/flairPicker';
import { bindSubmit, bindNonPassive, onInsert, looseH as h } from 'common/snabbdom';
import { emptyRedButton } from '../view/util';
Expand Down Expand Up @@ -254,11 +254,14 @@ export function view(ctrl: StudyForm): VNode {
'form',
{
attrs: { action: '/study/' + data.id + '/delete', method: 'post' },
hook: bindNonPassive(
'submit',
_ =>
isNew || prompt(i18n.study.confirmDeleteStudy(data.name))?.trim() === data.name.trim(),
),
hook: bindNonPassive('submit', e => {
if (isNew) return;

e.preventDefault();
prompt(i18n.study.confirmDeleteStudy(data.name)).then(userInput => {
if (userInput?.trim() === data.name.trim()) (e.target as HTMLFormElement).submit();
});
}),
},
[h(emptyRedButton, isNew ? i18n.site.cancel : i18n.study.deleteStudy)],
),
Expand All @@ -267,7 +270,12 @@ export function view(ctrl: StudyForm): VNode {
'form',
{
attrs: { action: '/study/' + data.id + '/clear-chat', method: 'post' },
hook: bindNonPassive('submit', _ => confirm(i18n.study.deleteTheStudyChatHistory)),
hook: bindNonPassive('submit', e => {
e.preventDefault();
confirm(i18n.study.deleteTheStudyChatHistory).then(yes => {
if (yes) (e.target as HTMLFormElement).submit();
});
}),
},
[h(emptyRedButton, i18n.study.clearChat)],
),
Expand Down
15 changes: 12 additions & 3 deletions ui/bits/src/bits.account.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import * as xhr from 'common/xhr';
import { storage } from 'common/storage';
import { addPasswordVisibilityToggleListener } from 'common/password';
import flairPickerLoader from './exports/flairPicker';
import { confirm } from 'common/dialog';
import { $as } from 'common';

site.load.then(() => {
$('.emoji-details').each(function (this: HTMLElement) {
Expand Down Expand Up @@ -60,8 +62,12 @@ site.load.then(() => {
};
checkDanger();
form.find('input').on('change', checkDanger);
submit.on('click', function (this: HTMLElement) {
return !isDanger || confirm(this.title);
submit.on('click', function (this: HTMLElement, e: Event) {
if (!isDanger) return true;
e.preventDefault();
confirm(this.title).then(yes => {
if (yes) $as<HTMLFormElement>(form).submit();
});
});
});

Expand All @@ -78,7 +84,10 @@ site.load.then(() => {
clean = serialize();
});
window.addEventListener('beforeunload', e => {
if (clean != serialize() && !confirm('You have unsaved changes. Are you sure you want to leave?'))
if (
clean != serialize() &&
!window.confirm('You have unsaved changes. Are you sure you want to leave?')
)
e.preventDefault();
});
});
Expand Down
6 changes: 2 additions & 4 deletions ui/bits/src/bits.checkout.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as xhr from 'common/xhr';
import { spinnerHtml } from 'common/spinner';
import { contactEmail } from './bits';
import { alert } from 'common/dialog';

export interface Pricing {
currency: string;
Expand All @@ -13,10 +14,7 @@ export interface Pricing {
const $checkout = $('div.plan_checkout');
const getFreq = () => $checkout.find('group.freq input:checked').val();
const getDest = () => $checkout.find('group.dest input:checked').val();
const showErrorThenReload = (error: string) => {
alert(error);
location.assign('/patron');
};
const showErrorThenReload = (error: string) => alert(error).then(() => location.assign('/patron'));

export function initModule({ stripePublicKey, pricing }: { stripePublicKey: string; pricing: any }): void {
contactEmail();
Expand Down
6 changes: 4 additions & 2 deletions ui/bits/src/bits.login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { debounce } from 'common/timing';
import { addPasswordVisibilityToggleListener } from 'common/password';
import { storedJsonProp } from 'common/storage';
import { spinnerHtml } from 'common/spinner';
import { alert } from 'common/dialog';

export function initModule(mode: 'login' | 'signup' | 'reset'): void {
mode === 'login' ? loginStart() : mode === 'signup' ? signupStart() : resetStart();
Expand Down Expand Up @@ -73,8 +74,9 @@ function loginStart() {
addPasswordVisibilityToggleListener();
load();
} else {
alert(text || res.statusText + '. Please wait some time before trying again.');
toggleSubmit($f.find('.submit'), true);
alert(text || res.statusText + '. Please wait some time before trying again.').then(() =>
toggleSubmit($f.find('.submit'), true),
);
}
} catch (e) {
console.warn(e);
Expand Down
1 change: 1 addition & 0 deletions ui/bits/src/bits.plan.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as xhr from 'common/xhr';
import { alert } from 'common/dialog';

const showError = (error: string) => alert(error);

Expand Down
5 changes: 3 additions & 2 deletions ui/bits/src/bits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { text, formToXhr } from 'common/xhr';
import flairPickerLoader from './exports/flairPicker';
import { spinnerHtml } from 'common/spinner';
import { wireCropDialog } from './exports/crop';
import { confirm } from 'common/dialog';

// avoid node_modules and pay attention to imports here. we don't want to force people
// to download the entire toastui editor library just to do some light form processing.
Expand Down Expand Up @@ -191,8 +192,8 @@ function pmAll() {
function practiceNag() {
const el = document.querySelector('.do-reset');
if (!(el instanceof HTMLAnchorElement)) return;
el.addEventListener('click', () => {
if (confirm('You will lose your practice progress!')) (el.parentNode as HTMLFormElement).submit();
el.addEventListener('click', async () => {
if (await confirm('You will lose your practice progress!')) (el.parentNode as HTMLFormElement).submit();
});
}

Expand Down
1 change: 1 addition & 0 deletions 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 { pubsub } from 'common/pubsub';
import { alert } from 'common/dialog';

export function initModule(): void {
makeLinkPopups($('.social_links'));
Expand Down
5 changes: 3 additions & 2 deletions ui/ceval/src/view/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { onInsert, bind, dataIcon, looseH as h } from 'common/snabbdom';
import * as Licon from 'common/licon';
import { onClickAway } from 'common';
import { clamp } from 'common/algo';
import { confirm } from 'common/dialog';

const allSearchTicks: [number, string][] = [
[4000, '4s'],
Expand Down Expand Up @@ -216,9 +217,9 @@ function engineSelection(ctrl: ParentCtrl) {
external &&
h('button.delete', {
attrs: { ...dataIcon(Licon.X), title: 'Delete external engine' },
hook: bind('click', e => {
hook: bind('click', async e => {
(e.currentTarget as HTMLElement).blur();
if (confirm('Remove external engine?'))
if (await confirm('Remove external engine?'))
ceval.engines.deleteExternal(external.id).then(ok => ok && ctrl.redraw?.());
}),
}),
Expand Down
1 change: 1 addition & 0 deletions ui/chat/src/ctrl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { moderationCtrl } from './moderation';
import { prop } from 'common';
import { storage, type LichessStorage } from 'common/storage';
import { pubsub, PubsubEvent, PubsubCallback } from 'common/pubsub';
import { alert } from 'common/dialog';

export default class ChatCtrl {
data: ChatData;
Expand Down
1 change: 1 addition & 0 deletions ui/chat/src/discussion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { presetView } from './preset';
import ChatCtrl from './ctrl';
import { tempStorage } from 'common/storage';
import { pubsub } from 'common/pubsub';
import { alert } from 'common/dialog';

const whisperRegex = /^\/[wW](?:hisper)?\s/;

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

export function moderationCtrl(opts: ModerationOpts): ModerationCtrl {
let data: ModerationData | undefined;
Expand Down Expand Up @@ -60,8 +61,8 @@ export function report(ctrl: ChatCtrl, line: HTMLElement): void {
const text = (line.querySelector('t') as HTMLElement).innerText;
if (userA) reportUserText(ctrl.data.resourceId, userA.href.split('/')[4], text);
}
function reportUserText(resourceId: string, username: string, text: string) {
if (confirm(`Report "${text}" to moderators?`)) flag(resourceId, username, text);
async function reportUserText(resourceId: string, username: string, text: string) {
if (await confirm(`Report "${text}" to moderators?`)) flag(resourceId, username, text);
}

export const lineAction = (): VNode => h('action.mod', { attrs: { 'data-icon': licon.Agent } });
Expand Down Expand Up @@ -137,8 +138,8 @@ export function moderationView(ctrl?: ModerationCtrl): VNode[] | undefined {
'a.text',
{
attrs: { 'data-icon': licon.Clock },
hook: bind('click', () => {
reportUserText(ctrl.opts.resourceId, data.name, data.text);
hook: bind('click', async () => {
await reportUserText(ctrl.opts.resourceId, data.name, data.text);
ctrl.timeout(ctrl.opts.reasons[0], data.text);
}),
},
Expand Down
2 changes: 1 addition & 1 deletion ui/cli/src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { load as loadDasher } from 'dasher';
import { domDialog } from 'common/dialog';
import { alert, domDialog } from 'common/dialog';
import { escapeHtml } from 'common';
import { userComplete } from 'common/userComplete';

Expand Down
Loading

0 comments on commit 6db4544

Please sign in to comment.