Advertisement
Cool_Dalek

Gui dependencies

Dec 7th, 2022 (edited)
1,949
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.98 KB | None | 0 0
  1. import cats.*
  2. import cats.effect.*
  3. import cats.effect.kernel.*
  4. import cats.effect.std.Dispatcher
  5. import cats.effect.unsafe.Scheduler
  6. import cats.syntax.all.*
  7.  
  8. import scala.concurrent.duration.*
  9. import scala.language.adhocExtensions
  10.  
  11. import scala.swing.*
  12. import scala.swing.event.*
  13.  
  14. type DependencyF[F[_], G[_[_]]] = DeferredSource[F, G[F]]
  15. transparent trait Dependent[F[_]]:
  16.   type Dependency[G[_[_]]] = DependencyF[F, G]
  17.  
  18.   protected def dispatcher: Dispatcher[F]
  19.  
  20.   inline final protected def withDependency[G[_[_]]]: Applicator[G] = new Applicator[G]
  21.  
  22.   protected final class Applicator[G[_[_]]]:
  23.  
  24.     inline def apply[R](f: G[F] => F[R])
  25.                        (ui: R => Unit)
  26.                        (using dependency: Dependency[G], ev: Monad[F]): Unit =
  27.       dispatcher.unsafeRunAndForget {
  28.         for {
  29.           value <- dependency.get
  30.           result <- f(value)
  31.         } yield Swing.onEDT(ui(result))
  32.       }
  33.     end apply
  34.  
  35.   end Applicator
  36.  
  37. end Dependent
  38.  
  39. class Editor[F[_]: Monad](
  40.                            scheduler: Scheduler,
  41.                            val dispatcher: Dispatcher[F]
  42.                          )(using DependencyF[F, DishDao]) extends BoxPanel(Orientation.Vertical), Dependent[F]:
  43.  
  44.   private val mainDish = new TextField() {
  45.     columns = 5
  46.   }
  47.   private val auxDishes = new TextArea() {
  48.     columns = 15
  49.   }
  50.   private val done = Label("")
  51.   private val buttonAdd = Button("Add") {
  52.     val mainName = mainDish.text
  53.     val auxNames = auxDishes.text.split(", ") to Set
  54.     val dish = Dish.Main(mainName, auxNames.map(Dish.Aux.apply))
  55.     withDependency[DishDao](_.addDish(dish)) { _ =>
  56.       done.text = "Done!"
  57.       scheduler.sleep(
  58.         800 millis span,
  59.         () => Swing.onEDT {
  60.           done.text = ""
  61.         }
  62.       )
  63.     }
  64.   }
  65.   contents.addOne(
  66.     FlowPanel(FlowPanel.Alignment.Right)(
  67.       Label("Main dish"), mainDish,
  68.       Label("Aux dishes"), auxDishes,
  69.       done, buttonAdd,
  70.     ),
  71.   )
  72.  
  73. end Editor
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement