Skip to content

Commit

Permalink
tutor wait screen WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
ornicar committed Jan 14, 2023
1 parent f891524 commit fb85fa3
Show file tree
Hide file tree
Showing 16 changed files with 93 additions and 51 deletions.
4 changes: 3 additions & 1 deletion app/controllers/Tutor.scala
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,9 @@ final class Tutor(env: Env) extends LilaController(env):
case TutorFullReport.InsufficientGames =>
BadRequest(views.html.tutor.empty.insufficientGames).toFuccess
case TutorFullReport.Empty(in: TutorQueue.InQueue) =>
Accepted(views.html.tutor.empty.queued(in, user)).toFuccess
env.tutor.queue.waitingGames(user) map { pgns =>
Accepted(views.html.tutor.empty.queued(in, user, pgns))
}
case TutorFullReport.Empty(_) => Accepted(views.html.tutor.empty.start(user)).toFuccess
case available: TutorFullReport.Available => f(ctx)(user)(available)
}
Expand Down
2 changes: 1 addition & 1 deletion app/views/opening/show.scala
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ object show:
)
}

private def exampleGames(page: OpeningPage)(implicit ctx: Context) =
private def exampleGames(page: OpeningPage)(using Context) =
div(cls := "opening__games")(page.explored.??(_.games).map { game =>
div(
cls := "opening__games__game lpv lpv--todo lpv--moves-bottom",
Expand Down
4 changes: 1 addition & 3 deletions app/views/tutor/bits.scala
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,7 @@ object bits:
menu: Frag,
title: String = "Lichess Tutor",
pageSmall: Boolean = false
)(
content: Modifier*
)(implicit ctx: Context) =
)(content: Modifier*)(using Context) =
views.html.base.layout(
moreCss = cssTag("tutor"),
moreJs = jsModule("tutor"),
Expand Down
15 changes: 11 additions & 4 deletions app/views/tutor/empty.scala
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import lila.user.User

object empty:

def start(user: User)(implicit ctx: Context) =
def start(user: User)(using Context) =
bits.layout(TutorFullReport.Empty(TutorQueue.NotInQueue), menu = emptyFrag, pageSmall = true)(
cls := "tutor__empty box",
boxTop(h1("Lichess Tutor")),
Expand All @@ -21,7 +21,7 @@ object empty:
)
)

def queued(in: TutorQueue.InQueue, user: User)(implicit ctx: Context) =
def queued(in: TutorQueue.InQueue, user: User, pgns: List[PgnStr])(using Context) =
bits.layout(
TutorFullReport.Empty(in),
menu = emptyFrag,
Expand Down Expand Up @@ -50,9 +50,16 @@ object empty:
"."
)
),
spinner
div(cls := "tutor__waiting-games")(pgns.map(waitGame))
)

private def waitGame(pgn: PgnStr)(using Context) =
div(
cls := "tutor__waiting-game lpv lpv--todo lpv--moves-false lpv--controls-false",
st.data("pgn") := pgn.value
)(lpvPreload)
private val lpvPreload = div(cls := "lpv__board")(div(cls := "cg-wrap")(cgWrapContent))

private def examinationMethod = frag(
p(
"Using the best chess engine: ",
Expand All @@ -62,7 +69,7 @@ object empty:
)
)

def insufficientGames(implicit ctx: Context) =
def insufficientGames(using Context) =
bits.layout(TutorFullReport.InsufficientGames, menu = emptyFrag, pageSmall = true)(
cls := "tutor__insufficient box",
boxTop(h1("Lichess Tutor")),
Expand Down
3 changes: 3 additions & 0 deletions modules/common/src/main/base/LilaModel.scala
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,6 @@ trait LilaModel:

opaque type UserAgent = String
object UserAgent extends OpaqueString[UserAgent]

opaque type PgnStr = String
object PgnStr extends OpaqueString[PgnStr]
8 changes: 3 additions & 5 deletions modules/tutor/src/main/Env.scala
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ final class Env(
mat: akka.stream.Materializer
):

private val reportColl = db(config.CollName("tutor_report"))
private val colls = TutorColls(db(config.CollName("tutor_report")), db(config.CollName("tutor_queue")))

lazy val nbAnalysisSetting = settingStore[Int](
"tutorNbAnalysis",
Expand All @@ -37,11 +37,9 @@ final class Env(

private lazy val fishnet = wire[TutorFishnet]
private lazy val builder = wire[TutorBuilder]
private lazy val queue =
TutorQueue(reportColl = reportColl, queueColl = db(config.CollName("tutor_queue")), cacheApi = cacheApi)
lazy val queue = wire[TutorQueue]

lazy val api = wire[TutorApi]

trait ReportColl
trait QueueColl
final private class TutorColls(val report: Coll, val queue: Coll)
trait NbAnalysis
5 changes: 3 additions & 2 deletions modules/tutor/src/main/TutorApi.scala
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package lila.tutor

import com.softwaremill.tagging.*
import org.joda.time.DateTime
import play.api.Mode
import scala.concurrent.duration.*
Expand All @@ -10,9 +11,9 @@ import lila.memo.CacheApi
import lila.user.User

final class TutorApi(
colls: TutorColls,
queue: TutorQueue,
builder: TutorBuilder,
reportColl: Coll,
cacheApi: CacheApi
)(using
ec: scala.concurrent.ExecutionContext,
Expand Down Expand Up @@ -75,7 +76,7 @@ final class TutorApi(
.buildAsyncFuture(findLatest)
}

private def findLatest(userId: UserId) = reportColl
private def findLatest(userId: UserId) = colls.report
.find($doc(TutorFullReport.F.user -> userId))
.sort($sort desc TutorFullReport.F.at)
.one[TutorFullReport]
10 changes: 5 additions & 5 deletions modules/tutor/src/main/TutorBuilder.scala
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,11 @@ import lila.common.config
import cats.data.NonEmptyList

final private class TutorBuilder(
colls: TutorColls,
insightApi: InsightApi,
perfStatsApi: InsightPerfStatsApi,
userRepo: UserRepo,
fishnet: TutorFishnet,
reportColl: Coll
fishnet: TutorFishnet
)(using ec: ExecutionContext):

import TutorBsonHandlers.given
Expand All @@ -55,7 +55,7 @@ final private class TutorBuilder(
"_id" -> s"${report.user}:${dateFormatter print report.at}",
"millis" -> lap.millis
)
_ <- reportColl.insert.one(doc).void
_ <- colls.report.insert.one(doc).void
} yield report.some
}
} yield none
Expand All @@ -74,10 +74,10 @@ final private class TutorBuilder(

private[tutor] def eligiblePerfTypesOf(user: User) =
PerfType.standardWithUltra.filter { pt =>
user.perfs(pt).latest.exists(_ isAfter DateTime.now.minusMonths(6))
user.perfs(pt).latest.exists(_ isAfter DateTime.now.minusMonths(12))
}

private def hasFreshReport(user: User): Fu[Boolean] = reportColl.exists(
private def hasFreshReport(user: User): Fu[Boolean] = colls.report.exists(
$doc(
TutorFullReport.F.user -> user.id,
TutorFullReport.F.at $gt DateTime.now.minusMinutes(TutorFullReport.freshness.toMinutes.toInt)
Expand Down
39 changes: 23 additions & 16 deletions modules/tutor/src/main/TutorQueue.scala
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ import lila.user.User
import lila.common.config.Max

final private class TutorQueue(
reportColl: Coll,
queueColl: Coll,
colls: TutorColls,
gameRepo: lila.game.GameRepo,
cacheApi: CacheApi
)(using ec: ExecutionContext, scheduler: akka.actor.Scheduler):
)(using ExecutionContext, akka.actor.Scheduler):

import TutorQueue.*

Expand All @@ -25,7 +25,7 @@ final private class TutorQueue(
private val durationCache = cacheApi.unit[FiniteDuration] {
_.refreshAfterWrite(1 minutes)
.buildAsyncFuture { _ =>
reportColl
colls.report
.aggregateOne(ReadPreference.secondaryPreferred) { framework =>
import framework.*
Sort(Descending(TutorFullReport.F.at)) -> List(
Expand All @@ -43,26 +43,33 @@ final private class TutorQueue(
def status(user: User): Fu[Status] = workQueue { fetchStatus(user) }

def enqueue(user: User): Fu[Status] = workQueue {
queueColl.insert
colls.queue.insert
.one($doc(F.id -> user.id, F.requestedAt -> DateTime.now))
.recover(lila.db.ignoreDuplicateKey)
.void >> fetchStatus(user)
}

private given BSONDocumentReader[Next] = Macros.reader
def next: Fu[Option[Next]] = queueColl.find($empty).sort($sort asc F.requestedAt).one[Next]
def start(userId: UserId): Funit = queueColl.updateField($id(userId), F.startedAt, DateTime.now).void
def remove(userId: UserId): Funit = queueColl.delete.one($id(userId)).void
def next: Fu[Option[Next]] = colls.queue.find($empty).sort($sort asc F.requestedAt).one[Next]
def start(userId: UserId): Funit = colls.queue.updateField($id(userId), F.startedAt, DateTime.now).void
def remove(userId: UserId): Funit = colls.queue.delete.one($id(userId)).void

private def fetchStatus(user: User): Fu[Status] =
queueColl.primitiveOne[DateTime]($id(user.id), F.requestedAt) flatMap {
case None => fuccess(NotInQueue)
case Some(at) =>
for {
position <- queueColl.countSel($doc(F.requestedAt $lte at))
avgDuration <- durationCache.get({})
} yield InQueue(position, avgDuration)
def waitingGames(user: User): Fu[List[PgnStr]] = gameRepo.recentPovsByUserFromSecondary(user, 10) map {
_.map { pov =>
PgnStr(pov.game.chess.sans.mkString(" "))
}
}

private def fetchStatus(user: User): Fu[Status] =
fuccess(InQueue(1, 5.minutes))
// queueColl.primitiveOne[DateTime]($id(user.id), F.requestedAt) flatMap {
// case None => fuccess(NotInQueue)
// case Some(at) =>
// for {
// position <- queueColl.countSel($doc(F.requestedAt $lte at))
// avgDuration <- durationCache.get({})
// } yield InQueue(position, avgDuration)
// }

object TutorQueue:

Expand Down
20 changes: 10 additions & 10 deletions pnpm-lock.yaml

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

2 changes: 1 addition & 1 deletion ui/common/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"@types/lichess": "workspace:*",
"@types/dom-screen-wake-lock": "1.0.0",
"chessground": "^8.3.6",
"lichess-pgn-viewer": "^1.4.4",
"lichess-pgn-viewer": "^1.5",
"snabbdom": "^3.5.1",
"tablesort": "^5.3.0"
},
Expand Down
2 changes: 1 addition & 1 deletion ui/opening/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"common": "workspace:*",
"date-fns": "^2.29.3",
"debounce-promise": "^3.1.2",
"lichess-pgn-viewer": "^1.4.4"
"lichess-pgn-viewer": "^1.5"
},
"scripts": {
"compile": "tsc",
Expand Down
2 changes: 1 addition & 1 deletion ui/site/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"flatpickr": "^4.6.13",
"highcharts": "=4.2.5",
"hopscotch": "^0.3.1",
"lichess-pgn-viewer": "^1.4.4",
"lichess-pgn-viewer": "^1.5",
"prop-types": "^15.8.1",
"stockfish-mv.wasm": "^0.6.1",
"stockfish-nnue.wasm": "1.0.0-1946a675.smolnet",
Expand Down
11 changes: 11 additions & 0 deletions ui/tutor/css/_home.scss
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,15 @@
margin: 10vh auto;
}
}
&__waiting-games {
@extend %flex-center-nowrap;
// height: 240px;
width: 100%;
overflow: hidden;
gap: 1em;
margin: 3em 0;
}
&__waiting-game {
flex: 0 0 200px;
}
}
2 changes: 1 addition & 1 deletion ui/tutor/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"@types/lichess": "workspace:*",
"chessground": "^8.3.6",
"common": "workspace:*",
"lichess-pgn-viewer": "^1.4.4"
"lichess-pgn-viewer": "^1.5"
},
"scripts": {
"compile": "tsc",
Expand Down
15 changes: 15 additions & 0 deletions ui/tutor/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,19 @@ lichess.load.then(() => {
},
});
});

$('.tutor__waiting-game').each(function (this: HTMLElement) {
const lpv = Lpv(this, {
pgn: this.dataset['pgn']!,
showMoves: false,
showClocks: true,
showPlayers: true,
showControls: false,
chessground: { coordinates: false },
drawArrows: false,
});
const nbMoves = Array.from(lpv.game.moves.mainline()).length;
const interval = 60 / nbMoves;
setInterval(() => lpv.goTo('next', false), interval * 1000);
});
});

0 comments on commit fb85fa3

Please sign in to comment.