From cdaf2c4157f85b2e5ccecb2a30a5f2564e292e5c Mon Sep 17 00:00:00 2001 From: tombdf Date: Tue, 25 Feb 2025 22:02:55 +0100 Subject: [PATCH] feat!: convert portfolio to Haskell web application * Migrate from static HTML/JS to Haskell/Scotty web application * Add server-side routing and API endpoints * Implement language switching and command processing * Set up project structure with stack * Move static assets to dedicated directory * Add type definitions and template rendering --- .gitignore | 10 +++ app/Main.hs | 26 ++++++ app/Routes.hs | 113 ++++++++++++++++++++++++ app/Templates.hs | 40 +++++++++ app/Types.hs | 27 ++++++ index.html | 137 ------------------------------ package.yaml | 37 ++++++++ stack.yaml | 6 ++ stack.yaml.lock | 12 +++ style.css => static/css/style.css | 0 static/js/terminal.js | 80 +++++++++++++++++ 11 files changed, 351 insertions(+), 137 deletions(-) create mode 100644 .gitignore create mode 100644 app/Main.hs create mode 100644 app/Routes.hs create mode 100644 app/Templates.hs create mode 100644 app/Types.hs delete mode 100644 index.html create mode 100644 package.yaml create mode 100644 stack.yaml create mode 100644 stack.yaml.lock rename style.css => static/css/style.css (100%) create mode 100644 static/js/terminal.js diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0dc7f35 --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +.stack-work/ +*~ +*.hi +*.o +*.cabal +dist +dist-* +cabal-dev +.ghc.environment.* +tags diff --git a/app/Main.hs b/app/Main.hs new file mode 100644 index 0000000..cd85a32 --- /dev/null +++ b/app/Main.hs @@ -0,0 +1,26 @@ +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE ScopedTypeVariables #-} + +module Main where + +import Web.Scotty +import Network.Wai.Middleware.Static +import Network.Wai.Middleware.RequestLogger +import Control.Monad.IO.Class +import Data.Text.Lazy (pack) +import System.Environment (getEnv) +import Control.Exception (catch) +import qualified Routes + +main :: IO () +main = do + port <- read <$> getEnv "PORT" `catch` \(_ :: IOError) -> return "3000" + putStrLn $ "Starting server on port " ++ show port + scotty port $ do + middleware logStdoutDev + middleware $ staticPolicy (addBase "static") + + -- Routes + get "/" $ Routes.indexHandler + get "/api/command/:cmd" $ Routes.commandHandler + get "/api/language/:lang" $ Routes.languageHandler diff --git a/app/Routes.hs b/app/Routes.hs new file mode 100644 index 0000000..4a8c746 --- /dev/null +++ b/app/Routes.hs @@ -0,0 +1,113 @@ +{-# LANGUAGE OverloadedStrings #-} + +module Routes where + +import Web.Scotty +import Data.Text.Lazy (Text) +import qualified Data.Text.Lazy as TL +import Data.Map.Strict (Map) +import qualified Data.Map.Strict as Map +import Control.Monad.IO.Class +import Network.HTTP.Types.Status +import Data.Aeson (ToJSON, object, (.=)) +import Templates +import Types + +indexHandler :: ActionM () +indexHandler = do + html $ renderIndex French + +commandHandler :: ActionM () +commandHandler = do + cmd <- param "cmd" :: ActionM Text + langParam <- (param "lang" :: ActionM Text) `rescue` (\_ -> return "fr") + let lang = if langParam == "en" then English else French + let response = processCommand cmd lang + json response + +languageHandler :: ActionM () +languageHandler = do + langParam <- param "lang" :: ActionM Text + let lang = if langParam == "en" then English else French + let response = CommandResponse (getTranslation "languageChanged" lang) False + json response + +processCommand :: Text -> Language -> CommandResponse +processCommand "help" lang = + let helpText = getTranslation "availableCommands" lang <> "\n\n" <> + "help: " <> getTranslation "help" lang <> "\n" <> + "about: " <> getTranslation "about" lang <> "\n" <> + "skills: " <> getTranslation "skills" lang <> "\n" <> + "projects: " <> getTranslation "projects" lang <> "\n" <> + "contact: " <> getTranslation "contact" lang <> "\n" <> + "clear: " <> getTranslation "clear" lang <> "\n" <> + "language: " <> getTranslation "language" lang + in CommandResponse helpText False + +processCommand "about" lang = CommandResponse (getCommandResponse "about" lang) False +processCommand "skills" lang = CommandResponse (getCommandResponse "skills" lang) False +processCommand "projects" lang = CommandResponse (getCommandResponse "projects" lang) True +processCommand "contact" lang = CommandResponse (getCommandResponse "contact" lang) True + +processCommand cmd lang = + let errorMsg = getTranslation "commandNotRecognized" lang + errorMsgWithCmd = TL.replace "{0}" cmd errorMsg + in CommandResponse errorMsgWithCmd False + +getTranslation :: TranslationKey -> Language -> Text +getTranslation key lang = + case lang of + French -> Map.findWithDefault "Translation missing" key frenchTranslations + English -> Map.findWithDefault "Translation missing" key englishTranslations + +getCommandResponse :: Text -> Language -> Text +getCommandResponse cmd lang = + case lang of + French -> Map.findWithDefault "Response missing" cmd frenchResponses + English -> Map.findWithDefault "Response missing" cmd englishResponses + +frenchTranslations :: Translation +frenchTranslations = Map.fromList + [ ("welcome", "Bienvenue dans le Portfolio de Thomas Brasdefer.\nTapez 'help' pour voir la liste des commandes disponibles. Type 'language' to switch to English.") + , ("help", "Affiche la liste des commandes disponibles") + , ("about", "À propos de moi") + , ("skills", "Mes compétences") + , ("projects", "Mes projets") + , ("contact", "Mes coordonnées") + , ("clear", "Efface l'écran") + , ("language", "Change la langue (fr/en)") + , ("languageChanged", "Langue changée en français") + , ("commandNotRecognized", "Commande non reconnue: {0}. Tapez 'help' pour voir la liste des commandes.") + , ("availableCommands", "Commandes disponibles:") + ] + +englishTranslations :: Translation +englishTranslations = Map.fromList + [ ("welcome", "Welcome to Thomas Brasdefer's Portfolio.\nType 'help' to see the list of available commands. Tapez 'language' pour passer en français.") + , ("help", "Display the list of available commands") + , ("about", "About me") + , ("skills", "My skills") + , ("projects", "My projects") + , ("contact", "My contact information") + , ("clear", "Clear the screen") + , ("language", "Change language (fr/en)") + , ("languageChanged", "Language changed to English") + , ("commandNotRecognized", "Command not recognized: {0}. Type 'help' to see the list of commands.") + , ("availableCommands", "Available commands:") + ] + +frenchResponses :: Map Text Text +frenchResponses = Map.fromList + [ ("about", "Actuellement élève ingénieur en informatique, je suis particulièrement intéressé par le développement bas niveau, la programmation logique, la cybersécurité, la cryptographie et ,dans une certaine mesure, l'intelligence artificielle. Je suis plutôt sensible aux questions de l'open source et du logiciel libre.\n\nJe cultive également un certain intérêt pour la philosophie « classique », plus particulièrement la philosophie aristotélicienne et scolastique.\nJe suis aussi assez friand de l'histoire de France lors du XIIe siècle (la « Renaissance du Moyen Âge ») et plus largement lors du reigne de la dynastie des Capétiens direct.\nMais je dois admettre que, les années n'aidant pas, j'ai de moins en moins de temps à consacrer à ces sujets.") + , ("skills", "Langages:\n- C\n- Java\n- Python\n- Prolog\n- HTML/CSS/Javascript/PHP\n\nFrameworks:\n- Flask\n- Spring Boot\n\nOutils:\n- Git\n- Docker\n\n Systèmes:\n- Linux (Debian/Ubuntu/Arch)\n- Windows") + , ("projects", "1. Ce portfolio (HTML, CSS, JavaScript)\n2. Générateur de documentation Prolog (Prolog)\n3. Générateur de commentaire de documentation (Python)") + , ("contact", "Email: thomas@hexasec.io\nLinkedIn: Thomas Brasdefer\nGitea: tombdf") + ] + +englishResponses :: Map Text Text +englishResponses = Map.fromList + [ ("about", "Currently a student in computer engineering, I'm particularly interested in low-level programming, logic programming, cybersecurity, cryptography and, to a certain extent, artificial intelligence. I'm very interested in open source and free software.\n\nI also cultivate a certain interest in \"classical\" philosophy, particularly Aristotelian and Scholastic philosophy.\nI'm also quite fond of French history during the 12th century (the \"Renaissance of the Middle Ages\") and more broadly during the reign of the direct Capetian dynasty.\nBut I have to admit that, as the years go by, I have less and less time to devote to these subjects.") + , ("skills", "Languages:\n- C\n- Java\n- Python\n- Prolog\n- HTML/CSS/Javascript/PHP\n\nFrameworks:\n- Flask\n- Spring Boot\n\nTools:\n- Git\n- Docker\n\n OS:\n- Linux (Debian/Ubuntu/Arch)\n- Windows") + , ("projects", "1. This portfolio (HTML, CSS, JavaScript)\n2. Prolog documentation generator (Prolog)\n3. Comments generator (Python)") + , ("contact", "Email: thomas@hexasec.io\nLinkedIn: Thomas Brasdefer\nGitea: tombdf") + ] diff --git a/app/Templates.hs b/app/Templates.hs new file mode 100644 index 0000000..30e3576 --- /dev/null +++ b/app/Templates.hs @@ -0,0 +1,40 @@ +{-# LANGUAGE OverloadedStrings #-} + +module Templates where + +import Data.Text.Lazy (Text) +import qualified Data.Text.Lazy as TL +import Types + +renderIndex :: Language -> Text +renderIndex lang = TL.concat + [ "\n" + , "\n" + , " \n" + , " \n" + , " \n" + , " \n" + , " Portfolio\n" + , " \n" + , " \n" + , " \n" + , "
\n" + , "
\n" + , "
\n" + , " $\n" + , " \n" + , "
\n" + , "
\n" + , " \n" + , " \n" + , " \n" + , "" + ] + +languageCode :: Language -> Text +languageCode French = "fr" +languageCode English = "en" diff --git a/app/Types.hs b/app/Types.hs new file mode 100644 index 0000000..b69c7ce --- /dev/null +++ b/app/Types.hs @@ -0,0 +1,27 @@ +{-# LANGUAGE OverloadedStrings #-} + +module Types where + +import Data.Text.Lazy (Text) +import Data.Map.Strict (Map) +import qualified Data.Map.Strict as Map +import Data.Aeson (ToJSON(..), object, (.=)) + +data Language = French | English + deriving (Show, Eq) + +type TranslationKey = Text +type TranslationValue = Text +type Translation = Map TranslationKey TranslationValue + +data CommandResponse = CommandResponse + { responseText :: Text + , responseHtml :: Bool + } deriving (Show) + +-- Instance ToJSON pour permettre la sérialisation JSON +instance ToJSON CommandResponse where + toJSON (CommandResponse text html) = + object [ "responseText" .= text + , "responseHtml" .= html + ] diff --git a/index.html b/index.html deleted file mode 100644 index a24638d..0000000 --- a/index.html +++ /dev/null @@ -1,137 +0,0 @@ - - - - - - - Portfolio - - - - -
-
- -
- - - - diff --git a/package.yaml b/package.yaml new file mode 100644 index 0000000..9347cd4 --- /dev/null +++ b/package.yaml @@ -0,0 +1,37 @@ +name: portfolio +version: 0.1.0.0 +github: "yourusername/portfolio" +license: BSD3 +author: "Thomas Brasdefer" +maintainer: "thomas@hexasec.io" +copyright: "2025 Thomas Brasdefer" + +description: Portfolio website using Haskell and Scotty + +dependencies: + - base >= 4.7 && < 5 + - scotty + - wai + - wai-extra + - text + - bytestring + - containers + - transformers + - aeson + - warp + - http-types + - wai-middleware-static + +library: + source-dirs: app + +executables: + portfolio-exe: + main: Main.hs + source-dirs: app + ghc-options: + - -threaded + - -rtsopts + - -with-rtsopts=-N + dependencies: + - portfolio diff --git a/stack.yaml b/stack.yaml new file mode 100644 index 0000000..0cc1b56 --- /dev/null +++ b/stack.yaml @@ -0,0 +1,6 @@ +resolver: lts-21.22 +packages: + - . +extra-deps: [] +flags: {} +extra-package-dbs: [] diff --git a/stack.yaml.lock b/stack.yaml.lock new file mode 100644 index 0000000..7df3396 --- /dev/null +++ b/stack.yaml.lock @@ -0,0 +1,12 @@ +# This file was autogenerated by Stack. +# You should not edit this file by hand. +# For more information, please see the documentation at: +# https://docs.haskellstack.org/en/stable/topics/lock_files + +packages: [] +snapshots: +- completed: + sha256: afd5ba64ab602cabc2d3942d3d7e7dd6311bc626dcb415b901eaf576cb62f0ea + size: 640060 + url: https://raw.githubusercontent.com/commercialhaskell/stackage-snapshots/master/lts/21/22.yaml + original: lts-21.22 diff --git a/style.css b/static/css/style.css similarity index 100% rename from style.css rename to static/css/style.css diff --git a/static/js/terminal.js b/static/js/terminal.js new file mode 100644 index 0000000..f5b5ad2 --- /dev/null +++ b/static/js/terminal.js @@ -0,0 +1,80 @@ +let currentLanguage = 'fr'; +const terminal = document.getElementById('terminal'); +const userInput = document.getElementById('user-input'); +const welcomeText = document.getElementById('welcome-text'); +const inputLine = document.getElementById('input-line'); + +async function initTerminal(lang) { + currentLanguage = lang; + const response = await fetch(`/api/command/help?lang=${currentLanguage}`); + const data = await response.json(); + const welcomeMsg = currentLanguage === 'fr' + ? "Bienvenue dans le Portfolio de Thomas Brasdefer.\nTapez 'help' pour voir la liste des commandes disponibles. Type 'language' to switch to English." + : "Welcome to Thomas Brasdefer's Portfolio.\nType 'help' to see the list of available commands. Tapez 'language' pour passer en français."; + + typeText(welcomeMsg, welcomeText); +} + +function typeText(text, element, speed = 50) { + let i = 0; + element.innerHTML = ''; + function type() { + if (i < text.length) { + element.innerHTML += text.charAt(i); + i++; + setTimeout(type, speed); + } else { + inputLine.style.display = 'flex'; + userInput.focus(); + } + } + type(); +} + +userInput.addEventListener('keydown', async function(event) { + if (event.key === 'Enter') { + const command = userInput.value.trim().toLowerCase(); + addToTerminal(`$ ${command}`); + + if (command === 'clear') { + clearTerminal(); + } else if (command === 'language') { + currentLanguage = currentLanguage === 'fr' ? 'en' : 'fr'; + const response = await fetch(`/api/language/${currentLanguage}`); + const data = await response.json(); + addToTerminal(data.responseText); + } else { + const response = await fetch(`/api/command/${command}?lang=${currentLanguage}`); + const data = await response.json(); + if (data.responseHtml) { + addToTerminalHtml(data.responseText); + } else { + addToTerminal(data.responseText); + } + } + + userInput.value = ''; + } +}); + +function addToTerminal(text) { + const output = document.createElement('div'); + output.classList.add('output'); + output.textContent = text; + terminal.insertBefore(output, inputLine); + terminal.scrollTop = terminal.scrollHeight; +} + +function addToTerminalHtml(html) { + const output = document.createElement('div'); + output.classList.add('output'); + output.innerHTML = html; + terminal.insertBefore(output, inputLine); + terminal.scrollTop = terminal.scrollHeight; +} + +function clearTerminal() { + const outputs = document.querySelectorAll('.output'); + outputs.forEach(output => output.remove()); + welcomeText.innerHTML = ''; +}