Compare commits

...
Sign in to create a new pull request.
Author SHA1 Message Date
a2b11fc82b we're not in lisp 2025-03-04 19:11:56 +00:00
72fdc2fffe Update dynamicUI.hs 2025-03-04 18:47:29 +00:00
309edca4f4 updateUI function works. 2025-03-04 17:45:59 +00:00
cd8a22182d adding non-working version of the dynamicUI example 2025-03-04 16:57:08 +00:00

93
dynamicUI.hs Normal file
View file

@ -0,0 +1,93 @@
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE OverloadedLabels #-}
-- Copyright © 2025 Hashirama Senju
{-
we dynamically update the UI when new data comes to the entry
-}
module Main where
import qualified GI.Gtk as Gtk
import qualified GI.Gio as Gio
import qualified Data.Text as T
import Control.Monad (void)
createWordLabel :: T.Text -> IO Gtk.Widget
createWordLabel word = do
label <- Gtk.labelNew (Just word)
-- Gesture for hover detection
motionController <- Gtk.eventControllerMotionNew
Gtk.widgetAddController label motionController
-- Print only when hovering an actual word
void $ Gtk.on motionController #enter $ \_ _ -> putStrLn (T.unpack word)
Gtk.toWidget label
updateUI :: Gtk.Box -> [String] -> IO ()
updateUI outerBox sentence = do
-- Remove all existing children from outerBox
let removeChildren widget = do
mChild <- Gtk.widgetGetFirstChild widget
case mChild of
Just child -> do
Gtk.boxRemove outerBox child
removeChildren widget
Nothing -> return ()
removeChildren outerBox
-- Create a new sentence box
sentenceBox <- Gtk.boxNew Gtk.OrientationHorizontal 0
Gtk.widgetSetHalign sentenceBox Gtk.AlignCenter
let tokens = map T.pack sentence
widgets <- mapM createWordLabel tokens
mapM_ (Gtk.boxAppend sentenceBox) widgets
Gtk.boxAppend outerBox sentenceBox
main :: IO ()
main = do
app <- Gtk.applicationNew (Just "com.example.YomichanHover") []
void $ Gio.onApplicationActivate app $ do
window <- Gtk.applicationWindowNew app
Gtk.windowSetTitle window (Just "Yomichan Hover")
Gtk.windowSetDefaultSize window 400 150
finalBox <- Gtk.boxNew Gtk.OrientationVertical 10
Gtk.widgetSetHalign finalBox Gtk.AlignCenter
Gtk.widgetSetValign finalBox Gtk.AlignCenter
Gtk.windowSetChild window (Just finalBox)
-- Input field
entry <- Gtk.entryNew
Gtk.boxAppend finalBox entry
Gtk.editableSetEditable entry True
-- Outer box (centers content)
outerBox <- Gtk.boxNew Gtk.OrientationVertical 0
Gtk.widgetSetHalign outerBox Gtk.AlignCenter
Gtk.widgetSetValign outerBox Gtk.AlignCenter
Gtk.boxAppend finalBox outerBox
-- Connect signal to update UI when pressing Enter
void $ Gtk.on entry #activate $ do
text <- Gtk.editableGetText entry
let sentence = words (T.unpack text)
updateUI outerBox sentence
void $ Gtk.on window #closeRequest $ do
Gio.applicationQuit app
return False
Gtk.widgetSetVisible window True
_ <- Gio.applicationRun app Nothing
return ()