Compare commits

..

1 Commits

Author SHA1 Message Date
efim
69fe8ee641 docs(11): readme with lessons learned 2023-07-04 06:29:59 +00:00
186 changed files with 299 additions and 8119 deletions

View File

View File

@@ -1,2 +0,0 @@
version = "3.7.3"
runner.dialect = scala3

View File

@@ -33,7 +33,7 @@ Users should be able to:
:PROPERTIES:
:CUSTOM_ID: links
:END:
- [[https://www.frontendmentor.io/solutions/tailwind-scala-ssr-scalatags-and-cask-deployed-with-docker-image-UPzyFXyf_L][Solution URL]]
- Solution URL
- [[https://efim-frontentmentor-price-grid-component.onrender.com/][Live Site URL]]
** My process

View File

@@ -128,8 +128,8 @@ object Page {
target := "_blank",
"Frontend Mentor. "
),
"Source code at",
a(href := "https://github.com/efim/Learning-HTMX", "Your Name Here")
"Coded by ",
a(href := "#", "Your Name Here")
)
)
}

View File

@@ -23,16 +23,15 @@ Users should be able to:
:PROPERTIES:
:CUSTOM_ID: screenshot
:END:
[[screenshot-desktop.png]]
[[screenshot-mobile.png]]
[[./screenshot.png]]
*** Links
:PROPERTIES:
:CUSTOM_ID: links
:END:
- [[https://www.frontendmentor.io/solutions/responsive-by-tailwindcss-ssr-on-scala-with-cask-thymeleaf-template-bMMgFdajHT][Solution URL]]
- [[https://efim-frontentmentor-order-summary.onrender.com/][Live Site URL]]
Free instance on render.com is turned off after 15 minutes of inactivity, please give the server a moment to start up if you're visiting it at the moment of being turned off
- Solution URL: [[https://your-solution-url.com][Add solution URL here]]
- Live Site URL: [[https://your-live-site-url.com][Add live site URL
here]]
** My process
:PROPERTIES:
@@ -43,11 +42,16 @@ Users should be able to:
:CUSTOM_ID: built-with
:END:
- Semantic HTML5 markup
- Tailwincss
- CSS custom properties
- Flexbox
- CSS Grid
- Mobile-first workflow
- SSR in Scala & Cask webserver
- Thymeleaf templates
- [[https://reactjs.org/][React]] - JS library
- [[https://nextjs.org/][Next.js]] - React framework
- [[https://styled-components.com/][Styled Components]] - For styles
*Note: These are just examples. Delete this note and replace the list
above with your own choices*
**** running during development
installing "sbt-revolver":
#+begin_src scala
@@ -78,10 +82,9 @@ will look for file in "src/main/resources/templates/index.html" to treat as a te
**** with these html templates I can start learning and using Emmet mode in Emacs
https://github.com/smihica/emmet-mode
**** Importing Thymeleaf template
There are other methods to include templates like th:replace and th:include, which have slightly different behaviours. th:insert keeps the host tag (the div in your case), th:replace replaces the whole host tag with the fragment, and th:include replaces the inner content of the host tag with the fragment.
**** importing Thymeleaf template
So i can actually have the "Order Summary" as reusable part.
There are other methods to include templates like th:replace and th:include, which have slightly different behaviours. th:insert keeps the host tag (the div in your case), th:replace replaces the whole host tag with the fragment, and th:include replaces the inner content of the host tag with the fragment.
**** getting responsive background image with Tailwincss
#+begin_src html
<div
@@ -93,10 +96,28 @@ So i can actually have the "Order Summary" as reusable part.
:PROPERTIES:
:CUSTOM_ID: continued-development
:END:
This was first exercise I've done with Thymeleaf templates.
Use this section to outline areas that you want to continue focusing on
in future projects. These could be concepts you're still not completely
comfortable with or techniques you found useful that you want to refine
and perfect.
Next is using fragments with some dynamic content and styling.
Then attempting to include htmx fueled reactivity.
*Note: Delete this note and the content within this section and replace
with your own plans for continued development.*
*** Useful resources
:PROPERTIES:
:CUSTOM_ID: useful-resources
:END:
- [[https://www.example.com][Example resource 1]] - This helped me for
XYZ reason. I really liked this pattern and will use it going forward.
- [[https://www.example.com][Example resource 2]] - This is an amazing
article which helped me finally understand XYZ. I'd recommend it to
anyone still learning this concept.
*Note: Delete this note and replace the list above with resources that
helped you during the challenge. These could come in handy for anyone
viewing your solution or for yourself when you look back on this project
in the future.*
** Acknowledgments
:PROPERTIES:

View File

@@ -1,10 +1,10 @@
{ pkgs, lib, sbt-derivation }:
let
pname = "order-summary-component-app";
package = sbt-derivation.lib.mkSbtDerivation {
inherit pkgs pname;
inherit pkgs;
# ...and the rest of the arguments
pname = "order-summary-component-app";
version = "0.0.1";
src = pkgs.nix-gitignore.gitignoreSource [ ] ./.;
nativeBuildInputs = [ pkgs.nodePackages.tailwindcss ];
@@ -17,7 +17,7 @@ let
# anyway copied to correct place
installPhase = ''
mkdir -p $out/bin
cp target/scala-*/order-summary-component-assembly-*.jar $out/bin/${pname}.jar
cp target/scala-*/order-summary-component-assembly-*.jar $out/bin/order-summary-component.jar
mkdir -p $out/bin/dist
cp ./output.css $out/bin/dist/output.css
cp -r public $out/bin/public
@@ -26,8 +26,6 @@ let
depsSha256 = "sha256-ADQB4qTl69ERlLAURrtR3fWa7PUdYjFLk5QdU5QgxRQ=";
};
in {
inherit package;
module = { config, pkgs, ... }:
let cfg = config.services.orderSummaryComponent;
in {
@@ -69,7 +67,7 @@ in {
startLimitBurst = 10;
serviceConfig = {
ExecStart =
"${pkgs.jdk}/bin/java -jar ${package}/bin/${pname}.jar -p ${
"${pkgs.jdk}/bin/java -jar ${package}/bin/order-summary-component.jar -p ${
toString cfg.port
} --host ${serverHost}";
WorkingDirectory = "${package}/bin";
@@ -86,16 +84,7 @@ in {
};
};
};
image = pkgs.dockerTools.buildLayeredImage {
name = pname;
tag = "latest";
created = "now";
config = {
Cmd = [ "${pkgs.jdk}/bin/java" "-jar" "${package}/bin/${pname}.jar" "--host" "0.0.0.0" ];
ExposedPorts = {
"8080/tcp" = {};
};
WorkingDir = "${package}/bin";
};
};
in {
package = package;
module = module;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

View File

@@ -43,7 +43,7 @@
Challenge by
<a href="https://www.frontendmentor.io?ref=challenge" target="_blank"
>Frontend Mentor</a
>. Source code at <a href="https://github.com/efim/Learning-HTMX">Your Name Here</a>.
>. Coded by <a href="#">Your Name Here</a>.
</div>
</body>
</html>

View File

@@ -1,6 +1,6 @@
# Frontend Mentor - Expenses chart component solution
# Frontend Mentor - Testimonials grid section solution
This is a solution to the [Expenses chart component challenge on Frontend Mentor](https://www.frontendmentor.io/challenges/expenses-chart-component-e7yJBUdjwt). Frontend Mentor challenges help you improve your coding skills by building realistic projects.
This is a solution to the [Testimonials grid section challenge on Frontend Mentor](https://www.frontendmentor.io/challenges/testimonials-grid-section-Nnw6J7Un7). Frontend Mentor challenges help you improve your coding skills by building realistic projects.
## Table of contents
@@ -24,11 +24,7 @@ This is a solution to the [Expenses chart component challenge on Frontend Mentor
Users should be able to:
- View the bar chart and hover over the individual bars to see the correct amounts for each day
- See the current days bar highlighted in a different colour to the other bars
- View the optimal layout for the content depending on their devices screen size
- See hover states for all interactive elements on the page
- **Bonus**: Use the JSON data file provided to dynamically size the bars on the chart
- View the optimal layout for the site depending on their device's screen size
### Screenshot

View File

@@ -1,6 +1,6 @@
# Frontend Mentor - Expenses chart component
# Frontend Mentor - Testimonials grid section
![Design preview for the Expenses chart component coding challenge](./design/desktop-preview.jpg)
![Design preview for the Testimonials grid section coding challenge](./design/desktop-preview.jpg)
## Welcome! 👋
@@ -8,25 +8,19 @@ Thanks for checking out this front-end coding challenge.
[Frontend Mentor](https://www.frontendmentor.io) challenges help you improve your coding skills by building realistic projects.
**To do this challenge, you need a decent understanding of HTML, CSS and JavaScript.**
**To do this challenge, you need a basic understanding of HTML and CSS.**
## The challenge
Your challenge is to build out this bar chart component and get it looking as close to the design as possible.
Your challenge is to build out this testimonials grid section and get it looking as close to the design as possible.
You can use any tools you like to help you complete the challenge. So if you've got something you'd like to practice, feel free to give it a go.
We provide the data for the chart in a local `data.json` file. So you can use that to dynamically add the bars if you choose.
Your users should be able to:
- View the bar chart and hover over the individual bars to see the correct amounts for each day
- See the current day's bar highlighted in a different colour to the other bars
- View the optimal layout for the content depending on their device's screen size
- See hover states for all interactive elements on the page
- **Bonus**: See dynamically generated bars based on the data provided in the local JSON file
- View the optimal layout for the site depending on their device's screen size
Want some support on the challenge? [Join our community](https://www.frontendmentor.io/community) and ask questions in the **#help** channel.
Want some support on the challenge? [Join our Slack community](https://www.frontendmentor.io/slack) and ask questions in the **#help** channel.
## Where to find everything
@@ -53,7 +47,7 @@ Feel free to use any workflow that you feel comfortable with. Below is a suggest
## Deploying your project
As mentioned above, there are many ways to host your project for free. Our recommended hosts are:
As mentioned above, there are many ways to host your project for free. Our recommend hosts are:
- [GitHub Pages](https://pages.github.com/)
- [Vercel](https://vercel.com/)
@@ -79,7 +73,7 @@ Remember, if you're looking for feedback on your solution, be sure to ask questi
There are multiple places you can share your solution:
1. Share your solution page in the **#finished-projects** channel of the [community](https://www.frontendmentor.io/community).
1. Share your solution page in the **#finished-projects** channel of the [Slack community](https://www.frontendmentor.io/slack).
2. Tweet [@frontendmentor](https://twitter.com/frontendmentor) and mention **@frontendmentor**, including the repo and live URLs in the tweet. We'd love to take a look at what you've built and help share it around.
3. Share your solution on other social channels like LinkedIn.
4. Blog about your experience building your project. Writing about your workflow, technical choices, and talking through your code is a brilliant way to reinforce what you've learned. Great platforms to write on are [dev.to](https://dev.to/), [Hashnode](https://hashnode.com/), and [CodeNewbie](https://community.codenewbie.org/).

View File

@@ -1,101 +0,0 @@
* Frontend Mentor - Testimonials grid section solution
:PROPERTIES:
:CUSTOM_ID: frontend-mentor---testimonials-grid-section-solution
:END:
This is a solution to the
[[https://www.frontendmentor.io/challenges/testimonials-grid-section-Nnw6J7Un7][Testimonials
grid section challenge on Frontend Mentor]]. Frontend Mentor challenges
help you improve your coding skills by building realistic projects.
** Overview
:PROPERTIES:
:CUSTOM_ID: overview
:END:
*** The challenge
:PROPERTIES:
:CUSTOM_ID: the-challenge
:END:
Users should be able to:
- View the optimal layout for the site depending on their device's
screen size
*** Screenshot
:PROPERTIES:
:CUSTOM_ID: screenshot
:END:
[[screenshot-desktop.png]]
[[screenshot-mobile.png]]
*** Links
:PROPERTIES:
:CUSTOM_ID: links
:END:
- [[https://efim-frontentmentor-testimoinals-grid.onrender.com/][Solution URL]]
- Live Site URL
** My process
:PROPERTIES:
:CUSTOM_ID: my-process
:END:
*** Built with
:PROPERTIES:
:CUSTOM_ID: built-with
:END:
- Semantic HTML5 markup
- TailwindCSS
- CSS Grid
- SSR on Scala with Cask
- Thymeleaf templates
*** What I learned
:PROPERTIES:
:CUSTOM_ID: what-i-learned
:END:
**** defining template fragments in Thymeleaf that take parameters
Bigger thing i didn't understand is that element marked by "th:fragment" are also rendered.
I had a problem with 'th:each' being defined on the same element as 'th:fragment'
even though due to th:each single 'testimonial' object is available for inserting. if i try to use that singular 'testimonial' as fragment argument, the also existing 'th:each' over "testimonials" runs and sinse there's no passed list of objects - nothing gets rendered.
So 'th:each' should be around the single fragment in the future.
Currently i've hacked this by passing List(testimonial) for re-rendering a single item.
**** A way to style fragments from the code
I've initially implemented the static page, with manually settin different testimonial colors and sizes, but then implemented a template fragment, which uses "th:classappend" to add tailwind color and size classes from the context objects.
This way unfortunately the tag marked with "th:fragement" (and it is getting rendered when template file is opened as a static file) doesn't have stylings.
And I'd really like a way that allows for having a fully displayed static template, which doesn't interfere with rendering.
Also - had to remember to not have space in
content: ["./src/**/*.{html,scala}"],
so that TailwindCSS would also monitor classes in the code
**** first attempt to use partial gragments as replies to htmx requests
I've added logic for transposing the 2x1 card into 1x2 and vice-versa (as an exercise in using htmx).
Backing in "next orientation" into argument for the hx-get request, which is executed on click, and receives new html markup to get inserted, with the testimonial orientation classes changed.
*** Continued development
:PROPERTIES:
:CUSTOM_ID: continued-development
:END:
a better way to style the components, so that static file would also have the styling on the 'fragment' element
already found a way to render fragments without needing to put them into a separate file.
*** Useful resources
:PROPERTIES:
:CUSTOM_ID: useful-resources
:END:
- The htmx [[https://htmx.org/docs/][documentation]] and [[https://htmx.org/examples/][examples]]
- [[https://htmx.org/essays/][The articles on htmx approach to web dev]]
** Acknowledgments
:PROPERTIES:
:CUSTOM_ID: acknowledgments
:END:
Here I'll like to express gratitute to htmx, for writing examples and articles which helped me to go from totally not understanding their position, to actively wanting to learn this.

View File

@@ -26,8 +26,6 @@ let
depsSha256 = "sha256-Y5RktcE3fxUJci4o7LTuNlBEybTdVRqsG551AkVeRPw=";
};
in {
inherit package;
module = { config, pkgs, ... }:
let cfg = config.services.${pname};
in {
@@ -86,20 +84,7 @@ in {
};
};
};
image = pkgs.dockerTools.buildLayeredImage {
name = pname;
tag = "latest";
created = "now";
config = {
Cmd = [
"${pkgs.jdk}/bin/java"
"-jar"
"${package}/bin/${pname}.jar"
"--host"
"0.0.0.0"
];
ExposedPorts = { "8080/tcp" = { }; };
WorkingDir = "${package}/bin";
};
};
in {
package = package;
module = module;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 280 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 95 KiB

View File

@@ -189,7 +189,7 @@
Challenge by
<a href="https://www.frontendmentor.io?ref=challenge" target="_blank"
>Frontend Mentor</a
>. Source code at <a href="https://github.com/efim/Learning-HTMX">Your Name Here</a>.
>. Coded by <a href="#">Your Name Here</a>.
</div>
</body>
</html>

View File

@@ -0,0 +1,113 @@
# Frontend Mentor - Rock, Paper, Scissors solution
This is a solution to the [Rock, Paper, Scissors challenge on Frontend Mentor](https://www.frontendmentor.io/challenges/rock-paper-scissors-game-pTgwgvgH). Frontend Mentor challenges help you improve your coding skills by building realistic projects.
## Table of contents
- [Overview](#overview)
- [The challenge](#the-challenge)
- [Screenshot](#screenshot)
- [Links](#links)
- [My process](#my-process)
- [Built with](#built-with)
- [What I learned](#what-i-learned)
- [Continued development](#continued-development)
- [Useful resources](#useful-resources)
- [Author](#author)
- [Acknowledgments](#acknowledgments)
**Note: Delete this note and update the table of contents based on what sections you keep.**
## Overview
### The challenge
Users should be able to:
- View the optimal layout for the game depending on their device's screen size
- Play Rock, Paper, Scissors against the computer
- Maintain the state of the score after refreshing the browser _(optional)_
- **Bonus**: Play Rock, Paper, Scissors, Lizard, Spock against the computer _(optional)_
### Screenshot
![](./screenshot.jpg)
Add a screenshot of your solution. The easiest way to do this is to use Firefox to view your project, right-click the page and select "Take a Screenshot". You can choose either a full-height screenshot or a cropped one based on how long the page is. If it's very long, it might be best to crop it.
Alternatively, you can use a tool like [FireShot](https://getfireshot.com/) to take the screenshot. FireShot has a free option, so you don't need to purchase it.
Then crop/optimize/edit your image however you like, add it to your project, and update the file path in the image above.
**Note: Delete this note and the paragraphs above when you add your screenshot. If you prefer not to add a screenshot, feel free to remove this entire section.**
### Links
- Solution URL: [Add solution URL here](https://your-solution-url.com)
- Live Site URL: [Add live site URL here](https://your-live-site-url.com)
## My process
### Built with
- Semantic HTML5 markup
- CSS custom properties
- Flexbox
- CSS Grid
- Mobile-first workflow
- [React](https://reactjs.org/) - JS library
- [Next.js](https://nextjs.org/) - React framework
- [Styled Components](https://styled-components.com/) - For styles
**Note: These are just examples. Delete this note and replace the list above with your own choices**
### What I learned
Use this section to recap over some of your major learnings while working through this project. Writing these out and providing code samples of areas you want to highlight is a great way to reinforce your own knowledge.
To see how you can add code snippets, see below:
```html
<h1>Some HTML code I'm proud of</h1>
```
```css
.proud-of-this-css {
color: papayawhip;
}
```
```js
const proudOfThisFunc = () => {
console.log('🎉')
}
```
If you want more help with writing markdown, we'd recommend checking out [The Markdown Guide](https://www.markdownguide.org/) to learn more.
**Note: Delete this note and the content within this section and replace with your own learnings.**
### Continued development
Use this section to outline areas that you want to continue focusing on in future projects. These could be concepts you're still not completely comfortable with or techniques you found useful that you want to refine and perfect.
**Note: Delete this note and the content within this section and replace with your own plans for continued development.**
### Useful resources
- [Example resource 1](https://www.example.com) - This helped me for XYZ reason. I really liked this pattern and will use it going forward.
- [Example resource 2](https://www.example.com) - This is an amazing article which helped me finally understand XYZ. I'd recommend it to anyone still learning this concept.
**Note: Delete this note and replace the list above with resources that helped you during the challenge. These could come in handy for anyone viewing your solution or for yourself when you look back on this project in the future.**
## Author
- Website - [Add your name here](https://www.your-site.com)
- Frontend Mentor - [@yourusername](https://www.frontendmentor.io/profile/yourusername)
- Twitter - [@yourusername](https://www.twitter.com/yourusername)
**Note: Delete this note and add/remove/edit lines above based on what links you'd like to share.**
## Acknowledgments
This is where you can give a hat tip to anyone who helped you out on this project. Perhaps you worked in a team or got some inspiration from someone else's solution. This is the perfect place to give them some credit.
**Note: Delete this note and edit this section's content as necessary. If you completed this challenge by yourself, feel free to delete this section entirely.**

View File

@@ -0,0 +1,119 @@
# Frontend Mentor - Rock, Paper, Scissors
![Design preview for the Rock, Paper, Scissors coding challenge](./design/desktop-preview.jpg)
## Welcome! 👋
Thanks for checking out this front-end coding challenge.
[Frontend Mentor](https://www.frontendmentor.io) challenges help you improve your coding skills by building realistic projects.
**To do this challenge, you need a basic understanding of HTML, CSS and JavaScript.**
## The challenge
Your challenge is to build out this Rock, Paper, Scissors game and get it looking as close to the design as possible.
You can use any tools you like to help you complete the challenge. So if you've got something you'd like to practice, feel free to give it a go.
Your users should be able to:
- View the optimal layout for the game depending on their device's screen size
- Play Rock, Paper, Scissors against the computer
- Maintain the state of the score after refreshing the browser _(optional)_
- **Bonus**: Play Rock, Paper, Scissors, Lizard, Spock against the computer _(optional)_
### Rules
If the player wins, they gain 1 point. If the computer wins, the player loses one point.
#### Original
- Paper beats Rock
- Rock beats Scissors
- Scissors beats Paper
#### Bonus
- Scissors beats Paper
- Paper beats Rock
- Rock beats Lizard
- Lizard beats Spock
- Spock beats Scissors
- Scissors beats Lizard
- Paper beats Spock
- Rock beats Scissors
- Lizard beats Paper
- Spock beats Rock
Not sure what Rock, Paper, Scissors, Lizard, Spock is? [Check out this clip from The Big Bang Theory](https://www.youtube.com/watch?v=iSHPVCBsnLw).
Want some support on the challenge? [Join our Slack community](https://www.frontendmentor.io/slack) and ask questions in the **#help** channel.
## Where to find everything
Your task is to build out the project to the designs inside the `/design` folder. You can either choose the `original` designs for the simpler version or the `bonus` designs for the harder version. You will find both mobile and desktop versions of the design to work to. Each file is also named depending on which step in the game the design is for.
The designs are in JPG static format. Using JPGs will mean that you'll need to use your best judgment for styles such as `font-size`, `padding` and `margin`.
If you would like the design files (we provide Sketch & Figma versions) to inspect the design in more detail, you can [subscribe as a PRO member](https://www.frontendmentor.io/pro).
You will find all the required assets in the `/images` folder. The assets are already optimized.
There is also a `style-guide.md` file containing the information you'll need, such as color palette and fonts.
## Building your project
Feel free to use any workflow that you feel comfortable with. Below is a suggested process, but do not feel like you need to follow these steps:
1. Initialize your project as a public repository on [GitHub](https://github.com/). Creating a repo will make it easier to share your code with the community if you need help. If you're not sure how to do this, [have a read-through of this Try Git resource](https://try.github.io/).
2. Configure your repository to publish your code to a web address. This will also be useful if you need some help during a challenge as you can share the URL for your project with your repo URL. There are a number of ways to do this, and we provide some recommendations below.
3. Look through the designs to start planning out how you'll tackle the project. This step is crucial to help you think ahead for CSS classes to create reusable styles.
4. Before adding any styles, structure your content with HTML. Writing your HTML first can help focus your attention on creating well-structured content.
5. Write out the base styles for your project, including general content styles, such as `font-family` and `font-size`.
6. Start adding styles to the top of the page and work down. Only move on to the next section once you're happy you've completed the area you're working on.
## Deploying your project
As mentioned above, there are many ways to host your project for free. Our recommend hosts are:
- [GitHub Pages](https://pages.github.com/)
- [Vercel](https://vercel.com/)
- [Netlify](https://www.netlify.com/)
You can host your site using one of these solutions or any of our other trusted providers. [Read more about our recommended and trusted hosts](https://medium.com/frontend-mentor/frontend-mentor-trusted-hosting-providers-bf000dfebe).
## Create a custom `README.md`
We strongly recommend overwriting this `README.md` with a custom one. We've provided a template inside the [`README-template.md`](./README-template.md) file in this starter code.
The template provides a guide for what to add. A custom `README` will help you explain your project and reflect on your learnings. Please feel free to edit our template as much as you like.
Once you've added your information to the template, delete this file and rename the `README-template.md` file to `README.md`. That will make it show up as your repository's README file.
## Submitting your solution
Submit your solution on the platform for the rest of the community to see. Follow our ["Complete guide to submitting solutions"](https://medium.com/frontend-mentor/a-complete-guide-to-submitting-solutions-on-frontend-mentor-ac6384162248) for tips on how to do this.
Remember, if you're looking for feedback on your solution, be sure to ask questions when submitting it. The more specific and detailed you are with your questions, the higher the chance you'll get valuable feedback from the community.
## Sharing your solution
There are multiple places you can share your solution:
1. Share your solution page in the **#finished-projects** channel of the [Slack community](https://www.frontendmentor.io/slack).
2. Tweet [@frontendmentor](https://twitter.com/frontendmentor) and mention **@frontendmentor**, including the repo and live URLs in the tweet. We'd love to take a look at what you've built and help share it around.
3. Share your solution on other social channels like LinkedIn.
4. Blog about your experience building your project. Writing about your workflow, technical choices, and talking through your code is a brilliant way to reinforce what you've learned. Great platforms to write on are [dev.to](https://dev.to/), [Hashnode](https://hashnode.com/), and [CodeNewbie](https://community.codenewbie.org/).
We provide templates to help you share your solution once you've submitted it on the platform. Please do edit them and include specific questions when you're looking for feedback.
The more specific you are with your questions the more likely it is that another member of the community will give you feedback.
## Got feedback for us?
We love receiving feedback! We're always looking to improve our challenges and our platform. So if you have anything you'd like to mention, please email hi[at]frontendmentor[dot]io.
This challenge is completely free. Please share it with anyone who will find it useful for practice.
**Have fun building!** 🚀

View File

@@ -1,166 +0,0 @@
* Frontend Mentor - Rock, Paper, Scissors solution
:PROPERTIES:
:CUSTOM_ID: frontend-mentor---rock-paper-scissors-solution
:END:
This is a solution to the
[[https://www.frontendmentor.io/challenges/rock-paper-scissors-game-pTgwgvgH][Rock,
Paper, Scissors challenge on Frontend Mentor]]. Frontend Mentor
challenges help you improve your coding skills by building realistic
projects.
** Overview
:PROPERTIES:
:CUSTOM_ID: overview
:END:
*** The challenge
:PROPERTIES:
:CUSTOM_ID: the-challenge
:END:
Users should be able to:
- View the optimal layout for the game depending on their device's
screen size
- Play Rock, Paper, Scissors against the computer
- Maintain the state of the score after refreshing the browser
/(optional)/
- *Bonus*: Play Rock, Paper, Scissors, Lizard, Spock against the
computer /(optional)/
*** Screenshot
:PROPERTIES:
:CUSTOM_ID: screenshot
:END:
[[screenshot-desktop.png]]
[[screenshot-mobile.png]]
*** Links
:PROPERTIES:
:CUSTOM_ID: links
:END:
- Solution URL
- [[https://efim-frontendmentor-rock-paper-scissors.onrender.com/][Live Site URL]]
** My process
:PROPERTIES:
:CUSTOM_ID: my-process
:END:
*** Built with
:PROPERTIES:
:CUSTOM_ID: built-with
:END:
- Semantic HTML5 markup
- TailwindCSS, css animations
- Flexbox & CSS Grid
- Mobile-first workflow
- SSR on Scala with Cask
- Thymeleaf templates
- htmx for partial page updates and interactivity
*** What I learned
:PROPERTIES:
:CUSTOM_ID: what-i-learned
:END:
**** for template fragement styling - using CSS vars in <style> tag
Allows for "initial" fragment specification to have static styling for viewing the page directly.
This is useful for fragments that should have different stylings, like hand selection badges - should have different colors, so colors are specified in the code and passed as css var values via "th:style".
Ordinary "style" attribute allows the tag which is marked by "th:fragment" to be viewed with some default styles. This is needed because for the "static" view of the page, browser ignores "th:fragment" attribute and just renders what it knows, as well as 'paper' and 'rock' badges, which are marked by "th:remove='all'" tag, which means they are only present in the "mockup static view"
But! Syling sizes this way seems to be an error, i don't want to specify 8rem in my code for the fragments, and that also makes styling of responsive design complicated. I guess I'll want the fragment itself occupy "all parent" and control the size of parent from html where the fragment is inserted.
**** different htmx controls:
***** the hx-get on the click
substitutes the hand selection part of the page to the initial "showdown" - with selected hand and animated wait on the "house choice".
***** on load + delay:3s hx-get
on "wait for house choice" fragemnt
means the "get house choice" rest method executed automatically, and generates random choice.
I'm substituting both hands \ whole 'showdown table' so i'm passing also a players choice into '/house-choice' rest endpoint.
I could only substitue the house choice badge and the message, that would have been a simpler design.
***** i wanted for message to show up with delay
so initially i though I'll do another timed on load request to fetch message, but figured that i could use css animation to fade the message in.
***** handling state of the fragment
Creating a scala object "ShowdownState" allows for setting single variable into context, and then at least "having all attributes of state" is enforced by scala compiler.
In documentaion i found that there's a shorthand for referencing attributes of single object:
https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#expressions-on-selections-asterisk-syntax
So i could set "th:object="${showdownState}"
and then reference directly it's attributes by "*{playersChoice}"
This can mitigate untyped nature of template variables.
***** I got more experience with laying out template fragments.
Putting 'showdown table' into separate file definitely helped, styling in the opened static file is nice.
I'm not sure how much separate files are necessary. Maybe state of "player hand is present, house hand is not present" separate of "showdown and both hands are present" would be easier for styling. Because fragments could be shown at the page.
Negative side of that - all other "not for render" parts of the page would have to be styled and kept in sync with the parts of pages for styling.
Maybe I'll do put some bigger fragments into separate files, but not recrete the outer page for them, just keep them in center of blank page.
***** Triggering client events from HTMX
https://htmx.org/headers/hx-trigger/
Adding header to REST response will trigger js event in the page.
#+begin_src scala
cask.Response(
result,
headers = Seq(
"Content-Type" -> "text/html;charset=UTF-8",
"HX-Trigger-After-Settle" -> s"""{"updateScore": ${showdownState.scoreChange}}"""
)
)
#+end_src
This is a way to pass data from server into js code, executing on client.
For exmaple +1 \ +0 \ -1 for the score change.
***** Using small js scripts for browser functions
I.e updating score, saving it into local storage and loading.
Two simple scripts directly near the html markup which contains the score:
#+begin_src html
<script type="text/javascript">
document.body.addEventListener("updateScore", function (evt) {
let scoreElement = document.querySelector("#the-score-number");
let newScore =
parseInt(scoreElement.textContent) + evt.detail.value;
console.log(
`the score will update by ${evt.detail.value} to ${newScore}`
);
localStorage.setItem("score", newScore);
scoreElement.textContent = newScore;
});
</script>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", (event) => {
let scoreElement = document.querySelector("#the-score-number");
let storedScore = localStorage.getItem("score");
if (storedScore !== null) {
scoreElement.textContent = storedScore;
} else {
scoreElement.textContent = 0;
localStorage.setItem("score", 0);
}
});
</script>
#+end_src
And debugging directly in the static preview.
We can create event in the console and fire it from any element:
#+begin_src js
var myEvent2 = new CustomEvent('updateScore', {detail : {value: -1}});
document.body.dispatchEvent(myEvent2)
#+end_src
*** Continued development
:PROPERTIES:
:CUSTOM_ID: continued-development
:END:
I could remake the html, to take into account the desktop layout. Which i didn't plan out and just didn't do - right now desktop only shows mobile layout increased in size.
Overall in the future I'd want to practice more with features available in htmx, to know how to make websites with interactivity expected my modern users.
And also - practice integration with js libraries - htmx examples show integration with sortable via events, and many others can be possible.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

View File

@@ -228,7 +228,7 @@
Challenge by
<a href="https://www.frontendmentor.io?ref=challenge" target="_blank"
>Frontend Mentor</a
>. Source code at <a href="https://github.com/efim/Learning-HTMX">Your Name Here</a>.
>. Coded by <a href="#">Your Name Here</a>.
</footer>
</body>
</html>

View File

@@ -1 +0,0 @@
use flake

View File

@@ -1,16 +0,0 @@
.bsp/
.scala-build/
.metals/
.direnv
*/dist/
/11-single-price-grid-component/.bloop/
**/.bloop
**/project/project/
**/project/metals.sbt
**/project/.bloop
**/project/target/
**/target/
*/result
result

View File

@@ -1,2 +0,0 @@
version = "3.7.3"
runner.dialect = scala3

View File

@@ -1,161 +0,0 @@
* Frontend Mentor - Multi-step form solution
:PROPERTIES:
:CUSTOM_ID: frontend-mentor---multi-step-form-solution
:END:
This is a solution to the
[[https://www.frontendmentor.io/challenges/multistep-form-YVAnSdqQBJ][Multi-step
form challenge on Frontend Mentor]]. Frontend Mentor challenges help you
improve your coding skills by building realistic projects.
** Overview
:PROPERTIES:
:CUSTOM_ID: overview
:END:
*** The challenge
:PROPERTIES:
:CUSTOM_ID: the-challenge
:END:
Users should be able to:
- Complete each step of the sequence
- Go back to a previous step to update their selections
- See a summary of their selections on the final step and confirm their
order
- View the optimal layout for the interface depending on their device's
screen size
- See hover and focus states for all interactive elements on the page
- Receive form validation messages if:
- A field has been missed
- The email address is not formatted correctly
- A step is submitted, but no selection has been made
*** Screenshot
:PROPERTIES:
:CUSTOM_ID: screenshot
:END:
[[screenshot-desktop.png]]
[[screenshot-mobile.png]]
*** Links
:PROPERTIES:
:CUSTOM_ID: links
:END:
- [[https://www.frontendmentor.io/solutions/responsive-ssr-on-scala-interactivity-by-htmx-thymeleaf-templates-QIGkOSgRa4][Solution URL]]
- [[https://efim-frontentmentor-multi-step-form.onrender.com][Live Site URL]]
** My process
:PROPERTIES:
:CUSTOM_ID: my-process
:END:
*** Built with
:PROPERTIES:
:CUSTOM_ID: built-with
:END:
- Semantic HTML5 markup
well, i tried, but yeah
- TailwinCSS
- Mobile-first workflow
- Server-side rendering, in Scala and Cask
- htmx
- Thymeleaf html templates
*** What I learned
:PROPERTIES:
:CUSTOM_ID: what-i-learned
:END:
**** hx-get and hx-post
***** How i show correct form stage for each user on same URL
on 'index.html' i use "initial loading" element
#+begin_src html
<section hx-get="/get-form" hx-trigger="load" hx-swap="outerHTML">
<!-- here be immediate hx-get for the form. to subscitute the body -->
<img class="w-14 text-green-500 fill-current" src="../public/images/tail-spin.svg" alt="loading..." />
</section>
#+end_src
This element will do single GET request to server to /get-form
And user already has cookie with sessionId set from visiting the root enpoint, which returned 'index.html'
So request to /get-form already includes 'sessionId' cookie, and server can find \ initialize Answers data for this particular session,
and 'currentStep' is part of the Answers
so reloading 'index.html' would trigger /get-form, which would render correct step.
***** hx-post
This will make POST request.
If we do GET request from <input> only current input value is included, as query para.
POST request from <input> or from <form> would include all filelds of the form.
So form submittion on "Next" and "Back" done via htmx POST requests, which parse and save passed attributes, but also server selects required next form step, renders it and returns for the 'hx-swap="outerHTML"'
hx-post on <input> allows for 'inline validation' (see useful resources)
this allows for validating field value - in isolation or together with all other form field values.
**** Learned format in which browser sends POST attributes to the server
Request payload as text:
name=e&email=emails%40la.la&phone=%2B7%20(911)%2084-35644%20ext%20155
I chose this exercise also because i wanted more experience in working with forms.
Single form would still be much nicer, even with htmx, but yeah.
Current exercise felt like full-fledged application.
**** Styling of the checkbox and radiobuttons as big selectable areas
This was first time I attempted something like this.
Insight was to use <label> as overall container for the input and other data - descriptions and icons.
Because user clicking on label automatically translates into toggling of the input, no js needed.
Either hide (for radio button part on step 2) or keep (for checkboxes on step 3) the input, and put descriptions and icons as next element.
So that =peer-= styling can be used.
**** htmx inline validation of the phone number field
Almost exactly as in example.
Separate rest endpoint for the input field, which returns new rendered state.
hx-post is triggered on input field default trigger = "changed",
and i guess only on focus leaving field. So this seems quite efficient.
This way validation can be done with very heavy libraries and access to DB and such. Over single field, or over all of them at once.
Seems unusual, but cool
*** Continued development
:PROPERTIES:
:CUSTOM_ID: continued-development
:END:
I want to learn more about Thymeleaf - how to use files for efficient fragment
storage. Currently it feels that i have separate files, and it's nice, but some
files have several fragments, and maybe need more documentation or markings.
Look for other templating solutions for java \ scala, maybe there are others
with 'fragment' functionality
Would be nice to refactor the code, to have smaller and more directed files.
I am also getting better at doing flex \ grid layouts without specific
paddings\margins on the lements, but feel that i'm still abusing that, and that
future tinkering with layouts could be painful due to free space being
constructed from manual paddings\margings
For htmx - would be nice to learn transition animations, and try to use it in a bigger exercise already.
*** Useful resources
:PROPERTIES:
:CUSTOM_ID: useful-resources
:END:
- htmx inline validation
https://htmx.org/examples/inline-validation/
- htmx control of parameters sent with response
https://htmx.org/docs/#parameters
** Acknowledgments
:PROPERTIES:
:CUSTOM_ID: acknowledgments
:END:
- svg animated spinner - from SamHerbert
https://github.com/SamHerbert/SVG-Loaders/tree/master
http://samherbert.net/svg-loaders/
- tailwind elements - for their example of 'switch styled' checkbox
which I used as inspiration for my styling
https://tailwind-elements.com/docs/standard/forms/switch/
- to render.com for allowing DockerImage deployments on a free tier
they get shut down after 15 minutes of inactivity, and image has to be < 10Gb
but this is great! no credit card needed

View File

@@ -1,17 +0,0 @@
ThisBuild / scalaVersion := "3.2.2"
fork := true
ThisBuild / version := "0.0.1"
ThisBuild / organization := "industries.sunshine"
lazy val multiStepForm = (project in file("."))
.settings(
name := "multi-step-form",
libraryDependencies ++= Seq(
"com.lihaoyi" %% "cask" % "0.9.1",
"com.lihaoyi" %% "mainargs" % "0.5.0",
"org.thymeleaf" % "thymeleaf" % "3.1.1.RELEASE",
"com.googlecode.libphonenumber" % "libphonenumber" % "8.13.16"
)
)

View File

@@ -1,101 +0,0 @@
{ pkgs, lib, sbt-derivation }:
let
pname = "multi-step-form";
package = sbt-derivation.lib.mkSbtDerivation {
inherit pkgs pname;
# ...and the rest of the arguments
version = "0.0.1";
src = pkgs.nix-gitignore.gitignoreSource [ ] ./.;
nativeBuildInputs = [ pkgs.nodePackages.tailwindcss ];
buildPhase = ''
tailwindcss -i ./src/input.css -o ./src/main/resources/public/output.css
sbt assembly
'';
installPhase = ''
mkdir -p $out/bin
cp target/scala-*/${pname}-assembly-*.jar $out/bin/${pname}.jar
'';
depsSha256 = "sha256-zG4e7ERdi/WxzACymaYUQ0x8v4/peGARuqPAK8xvBmE=";
};
module = { config, pkgs, ... }:
let cfg = config.services.${pname};
in {
options.services.${pname} = {
enable = lib.mkEnableOption "My frontendmentor exercise ${pname}";
port = lib.mkOption {
type = lib.types.int;
default = 8080;
description = "Port to listen on.";
};
host = lib.mkOption {
type = lib.types.str;
default = "localhost";
description = "Host to bind to.";
};
useNginx = lib.mkOption {
type = lib.types.bool;
default = true;
description = "Whether to use Nginx to proxy requests.";
};
};
config = lib.mkIf cfg.enable {
users.groups."${pname}-group" = { };
users.users."${pname}-user" = {
isSystemUser = true;
group = "${pname}-group";
};
systemd.services.${pname} =
let serverHost = if cfg.useNginx then "localhost" else cfg.host;
in {
description = "Exercise app ${pname}";
wantedBy = [ "multi-user.target" ];
after = [ "network.target" ];
startLimitIntervalSec = 30;
startLimitBurst = 10;
serviceConfig = {
ExecStart =
"${pkgs.jdk}/bin/java -jar ${package}/bin/${pname}.jar -p ${
toString cfg.port
} --host ${serverHost}";
WorkingDirectory = "${package}/bin";
Restart = "on-failure";
User = "${pname}-user";
Group = "${pname}-group";
};
};
services.nginx = lib.mkIf cfg.useNginx {
virtualHosts.${cfg.host} = {
locations."/".proxyPass = "http://127.0.0.1:${toString cfg.port}";
};
};
};
};
image = pkgs.dockerTools.buildLayeredImage {
name = pname;
tag = "latest";
created = "now";
config = {
Cmd = [ "${pkgs.jdk}/bin/java" "-jar" "${package}/bin/${pname}.jar" "--host" "0.0.0.0" ];
ExposedPorts = {
"8080/tcp" = {};
};
};
};
# image = pkgs.dockerTools.buildLayeredImage { # so, wow, this works
# name = "hello2";
# tag = "latest";
# config.Cmd = [ "${pkgs.hello}/bin/hello" ];
# };
in {
package = package;
module = module;
image = image;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

View File

@@ -1 +0,0 @@
sbt.version=1.9.0

View File

@@ -1,3 +0,0 @@
addSbtPlugin("io.spray" % "sbt-revolver" % "0.10.0")
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "2.1.1")

Binary file not shown.

Before

Width:  |  Height:  |  Size: 112 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

View File

@@ -1,33 +0,0 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
html {
font-size: 16px;
}
/* path is relative to 'out.css' */
@font-face {
font-family: 'Ubuntu';
src: url('fonts/Ubuntu-Regular.ttf') format('truetype');
font-weight: 400; /* Regular */
font-style: normal;
}
@font-face {
font-family: 'Ubuntu';
src: url('fonts/Ubuntu-Medium.ttf') format('truetype');
font-weight: 600; /* Semibold */
font-style: normal;
}
@font-face {
font-family: 'Ubuntu';
src: url('fonts/Ubuntu-Bold.ttf') format('truetype');
font-weight: 700; /* Bold */
font-style: normal;
}
/* div, p, button, ol, li, summary, article, h1 { */
/* outline: 1px solid red; */
/* } */

File diff suppressed because one or more lines are too long

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="274" height="568" fill="none" viewBox="0 0 274 568"><rect width="274" height="568" fill="#483EFF" rx="10"/><mask id="a" width="274" height="568" x="0" y="0" maskUnits="userSpaceOnUse" style="mask-type:alpha"><rect width="274" height="568" fill="#fff" rx="10"/></mask><g mask="url(#a)"><path fill="#6259FF" fill-rule="evenodd" d="M-34.692 543.101C3.247 632.538 168.767 685.017 211.96 612.52c43.194-72.497-66.099-85.653-104.735-160.569-38.635-74.916-68.657-121.674-124.482-104.607-55.824 17.068-55.375 106.32-17.436 195.757Z" clip-rule="evenodd"/><path fill="#F9818E" fill-rule="evenodd" d="M233.095 601.153c60.679-28.278 92.839-143.526 41.875-171.528-50.965-28.003-57.397 47.579-108.059 75.987-50.662 28.408-82.14 50.207-69.044 88.241 13.096 38.034 74.549 35.578 135.228 7.3Z" clip-rule="evenodd"/><path stroke="#fff" stroke-linecap="round" stroke-linejoin="bevel" stroke-width="5" d="m165.305 469.097 10.607-10.806M209.461 474.581l-12.506-10.503M187.56 488.991l-6.908 14.798"/><path fill="#FFAF7E" d="M.305 546.891c37.003 0 67-29.997 67-67s-29.997-67-67-67-67 29.997-67 67 29.997 67 67 67Z"/></g></svg>

Before

Width:  |  Height:  |  Size: 1.1 KiB

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="375" height="172" viewBox="0 0 375 172"><defs><path id="a" d="M0 0h375v172H0z"/></defs><g fill="none" fill-rule="evenodd"><mask id="b" fill="#fff"><use xlink:href="#a"/></mask><use xlink:href="#a" fill="#483EFF"/><g mask="url(#b)"><g transform="translate(-151.029 -133.957)"><path fill="#6259FF" d="M79.546 349.634c54.547 128.646 292.524 204.132 354.626 99.852 62.102-104.28-95.035-123.204-150.583-230.963-55.547-107.759-98.711-175.015-178.973-150.466C24.354 92.607 25 220.987 79.546 349.634Z"/><ellipse cx="129.864" cy="258.711" fill="#FFAF7E" rx="96.329" ry="96.373"/><path fill="#F9818E" d="M464.88 433.146c87.31-40.69 133.585-206.525 60.253-246.82-73.333-40.293-82.587 68.465-155.485 109.343-72.898 40.877-118.192 72.245-99.348 126.973 18.845 54.728 107.27 51.194 194.58 10.504Z"/><g stroke="#FFF" stroke-linecap="round" stroke-linejoin="bevel" stroke-width="5"><path d="m367.336 243.125 15.263-15.549M430.872 251.016l-17.995-15.112M399.36 271.751l-9.94 21.293"/></g></g></g></g></svg>

Before

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 KiB

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40"><g fill="none" fill-rule="evenodd"><circle cx="20" cy="20" r="20" fill="#F9818E"/><path fill="#FFF" fill-rule="nonzero" d="M25.057 15H14.944C12.212 15 10 17.03 10 19.885c0 2.857 2.212 4.936 4.944 4.936h10.113c2.733 0 4.943-2.08 4.943-4.936S27.79 15 25.057 15ZM17.5 20.388c0 .12-.108.237-.234.237h-1.552v1.569c0 .126-.138.217-.259.217H14.5c-.118 0-.213-.086-.213-.203v-1.583h-1.569c-.126 0-.217-.139-.217-.26v-.956c0-.117.086-.213.202-.213h1.584v-1.554c0-.125.082-.231.203-.231h.989c.12 0 .236.108.236.234v1.551h1.555c.125 0 .231.083.231.204v.988Zm5.347.393a.862.862 0 0 1-.869-.855c0-.472.39-.856.869-.856.481 0 .87.384.87.856 0 .471-.389.855-.87.855Zm1.9 1.866a.86.86 0 0 1-.87-.852.86.86 0 0 1 .87-.855c.48 0 .87.38.87.855a.86.86 0 0 1-.87.852Zm0-3.736a.862.862 0 0 1-.87-.854c0-.472.39-.856.87-.856s.87.384.87.856a.862.862 0 0 1-.87.854Zm1.899 1.87a.862.862 0 0 1-.868-.855c0-.472.389-.856.868-.856s.868.384.868.856a.862.862 0 0 1-.868.855Z"/></g></svg>

Before

Width:  |  Height:  |  Size: 1.0 KiB

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40"><g fill="none" fill-rule="evenodd"><circle cx="20" cy="20" r="20" fill="#FFAF7E"/><path fill="#FFF" fill-rule="nonzero" d="M24.995 18.005h-3.998v5.998h-2v-5.998H15a1 1 0 0 0-1 1V29a1 1 0 0 0 1 1h9.995a1 1 0 0 0 1-1v-9.995a1 1 0 0 0-1-1Zm-5.997 8.996h-2v-1.999h2v2Zm2-11.175a2.999 2.999 0 1 0-2 0v2.18h2v-2.18Z"/></g></svg>

Before

Width:  |  Height:  |  Size: 405 B

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="9" viewBox="0 0 12 9"><path fill="none" stroke="#FFF" stroke-width="2" d="m1 4 3.433 3.433L10.866 1"/></svg>

Before

Width:  |  Height:  |  Size: 167 B

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 40 40"><g fill="none" fill-rule="evenodd"><circle cx="20" cy="20" r="20" fill="#483EFF"/><path fill="#FFF" fill-rule="nonzero" d="M26.666 13H13.334A3.333 3.333 0 0 0 10 16.333v7.193a3.447 3.447 0 0 0 2.14 3.24c1.238.5 2.656.182 3.56-.8L18.52 23h2.96l2.82 2.966a3.2 3.2 0 0 0 3.56.8 3.447 3.447 0 0 0 2.14-3.24v-7.193A3.333 3.333 0 0 0 26.666 13Zm-9.333 6H16v1.333a.667.667 0 0 1-1.333 0V19h-1.333a.667.667 0 0 1 0-1.334h1.333v-1.333a.667.667 0 1 1 1.333 0v1.333h1.333a.667.667 0 1 1 0 1.334Zm7.333 2a2.667 2.667 0 1 1 0-5.333 2.667 2.667 0 0 1 0 5.333ZM26 18.333a1.333 1.333 0 1 1-2.667 0 1.333 1.333 0 0 1 2.667 0Z"/></g></svg>

Before

Width:  |  Height:  |  Size: 704 B

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="80" height="80" viewBox="0 0 80 80"><g fill="none"><circle cx="40" cy="40" r="40" fill="#F9818E"/><path fill="#E96170" d="M48.464 79.167c.768-.15 1.53-.321 2.288-.515a40.04 40.04 0 0 0 3.794-1.266 40.043 40.043 0 0 0 3.657-1.63 40.046 40.046 0 0 0 12.463-9.898A40.063 40.063 0 0 0 78.3 51.89c.338-1.117.627-2.249.867-3.391L55.374 24.698a21.6 21.6 0 0 0-15.332-6.365 21.629 21.629 0 0 0-15.344 6.365c-8.486 8.489-8.486 22.205 0 30.694l23.766 23.775Z"/><path fill="#FFF" d="M40.003 18.333a21.58 21.58 0 0 1 15.31 6.351c8.471 8.471 8.471 22.158 0 30.63-8.47 8.47-22.156 8.47-30.627 0-8.47-8.472-8.47-22.159 0-30.63a21.594 21.594 0 0 1 15.317-6.35Zm9.865 15c-.316.028-.622.15-.872.344l-12.168 9.13-5.641-5.642c-1.224-1.275-3.63 1.132-2.356 2.356l6.663 6.663c.56.56 1.539.63 2.173.156l13.326-9.995c1.122-.816.43-2.993-.956-3.013a1.666 1.666 0 0 0-.17 0Z"/></g></svg>

Before

Width:  |  Height:  |  Size: 908 B

View File

@@ -1,32 +0,0 @@
<!-- By Sam Herbert (@sherb), for everyone. More @ http://goo.gl/7AJzbL -->
<svg width="38" height="38" viewBox="0 0 38 38" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient x1="8.042%" y1="0%" x2="65.682%" y2="23.865%" id="a">
<stop stop-color="hsl(228, 100%, 84%)" stop-opacity="0" offset="0%"/>
<stop stop-color="hsl(228, 100%, 84%)" stop-opacity=".631" offset="63.146%"/>
<stop stop-color="hsl(228, 100%, 84%)" offset="100%"/>
</linearGradient>
</defs>
<g fill="none" fill-rule="evenodd">
<g transform="translate(1 1)">
<path d="M36 18c0-9.94-8.06-18-18-18" id="Oval-2" stroke="url(#a)" stroke-width="2">
<animateTransform
attributeName="transform"
type="rotate"
from="0 18 18"
to="360 18 18"
dur="0.9s"
repeatCount="indefinite" />
</path>
<circle fill="#fff" cx="36" cy="18" r="1">
<animateTransform
attributeName="transform"
type="rotate"
from="0 18 18"
to="360 18 18"
dur="0.9s"
repeatCount="indefinite" />
</circle>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

File diff suppressed because it is too large Load Diff

View File

@@ -1,30 +0,0 @@
<!DOCTYPE html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<title>TEst</title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="../public/out.css" rel="stylesheet" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<!-- Place favicon.ico in the root directory -->
</head>
<body>
<!--[if lt IE 8]>
<p class="browserupgrade">
You are using an <strong>outdated</strong> browser. Please
<a href="http://browsehappy.com/">upgrade your browser</a> to improve
your experience.
</p>
<![endif]-->
<main class="bg-green-200">
<h1 class="text-3xl">Hello!</h1>
<secion>
<p>into the template</p>
</secion>
</main>
</body>
</html>

View File

@@ -1,58 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- displays site properly based on user's device -->
<link
rel="icon"
type="image/png"
sizes="32x32"
th:href="'public/images/favicon-32x32.png'"
href="../public/images/favicon-32x32.png"
/>
<link
th:href="'public/out.css'"
href="../public/out.css"
rel="stylesheet"
/>
<script th:src="'public/htmx.min.js'" src="../public/htmx.min.js"></script>
<title>Frontend Mentor | Multi-step form</title>
<!-- Feel free to remove these styles or customise in your own stylesheet 👍 -->
<style>
.attribution {
font-size: 11px;
text-align: center;
}
.attribution a {
color: hsl(228, 45%, 44%);
}
</style>
</head>
<body>
<main class="grid place-content-center w-screen h-screen bg-magnolia">
<section hx-get="/get-form" hx-trigger="load" hx-swap="outerHTML">
<!-- here be immediate hx-get for the form. to subscitute the body -->
<img
class="w-14 text-green-500 fill-current"
th:src="'public/images/tail-spin.svg'"
src="../public/images/tail-spin.svg"
alt="loading..."
/>
</section>
<section class="absolute top-0 end-0" id="new-session-control">
<button hx-get="/force-new-session">Request new session</button>
</section>
<div class="fixed inset-x-0 bottom-0 attribution">
Challenge by
<a href="https://www.frontendmentor.io?ref=challenge" target="_blank"
>Frontend Mentor</a
>. Source code at
<a href="https://github.com/efim/Learning-HTMX">Your Name Here</a>.
</div>
</main>
</body>
</html>

View File

@@ -1,233 +0,0 @@
<!DOCTYPE html>
<html class="no-js" lang="">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- displays site properly based on user's device -->
<link
rel="icon"
type="image/png"
sizes="32x32"
href="./assets/images/favicon-32x32.png"
/>
<link href="../public/out.css" rel="stylesheet" />
<title>Frontend Mentor | Multi-step form</title>
<!-- Feel free to remove these styles or customise in your own stylesheet 👍 -->
<style>
.attribution {
font-size: 11px;
text-align: center;
}
.attribution a {
color: hsl(228, 45%, 44%);
}
</style>
</head>
<body class="grid place-content-center h-screen bg-magnolia">
<!--[if lt IE 8]>
<p class="browserupgrade">
You are using an <strong>outdated</strong> browser. Please
<a href="http://browsehappy.com/">upgrade your browser</a> to improve
your experience.
</p>
<![endif]-->
<form
class="flex flex-col items-center w-screen h-screen md:grid md:items-start md:p-5 md:bg-white md:rounded-2xl md:grid-cols-[auto_1fr] md:w-desktop-form md:h-desktop-form md:drop-shadow-2xl"
id="form-step"
th:fragment="formFragment(formData)"
hx-post="/submit-step/1/2"
hx-swap="outerHTML"
action="/submit-step/1/2"
method="post"
>
<summary
class="w-full h-44 bg-no-repeat bg-cover md:row-span-2 md:tracking-widest bg-sidebar-mobile marker:text-white md:bg-sidebar-desktop md:h-[568px] md:w-[274px]"
id="sidebar"
th:fragment="stepsSummary(formData)"
>
<ol
class="grid grid-cols-[repeat(4,_auto)] gap-x-5 content-center items-center place-content-center h-24 md:flex-col md:h-full md:grid-rows-[repeat(4,_auto)] md:grid-cols-1 md:content-start md:p-10 md:gap-y-7 text-white text-sm uppercase"
>
<li
class="items-center md:grid md:gap-x-4 md:grid-cols-[auto_1fr]"
th:each="stepNum: ${formData.stepsAmount}"
>
<div
class="grid place-content-center w-8 h-8 font-bold text-white rounded-full border border-white"
th:classappend="${stepNum.index} == ${formData.userAnswers.currentStep} ? '!bg-light-blue !text-marine-blue'"
th:text="${stepNum.index}"
>
1
</div>
<p class="hidden md:flex md:flex-col">
<span class="text-light-gray"
>Step <span th:text="${stepNum.index}">1</span></span
><span class="font-bold" th:text="${stepNum.name}"
>Your info</span
>
</p>
</li>
<li
class="items-center md:grid md:gap-x-4 md:grid-cols-[auto_1fr]"
th:remove="all"
>
<div
class="grid place-content-center w-8 h-8 text-white rounded-full border border-white"
>
2
</div>
<p class="hidden md:flex md:flex-col">
<span class="text-light-gray">Step 2</span
><span class="font-bold">Select plan</span>
</p>
</li>
<li
class="items-center md:grid md:gap-x-4 md:grid-cols-[auto_1fr]"
th:remove="all"
>
<div
class="grid place-content-center w-8 h-8 text-white rounded-full border border-white"
>
3
</div>
<p class="hidden md:flex md:flex-col">
<span class="text-light-gray">Step 3</span
><span class="font-bold">Add-ons</span>
</p>
</li>
<li
class="items-center md:grid md:gap-x-4 md:grid-cols-[auto_1fr]"
th:remove="all"
>
<div
class="grid place-content-center w-8 h-8 text-white rounded-full border border-white"
>
4
</div>
<p class="hidden md:flex md:flex-col">
<span class="text-light-gray">Step 4</span
><span class="font-bold">summary</span>
</p>
</li>
</ol>
</summary>
<section
id="multipage-form-container"
class="flex flex-col py-8 px-6 -mt-20 w-11/12 bg-white rounded-xl md:px-24 md:mt-0 md:w-full drop-shadow-xl md:drop-shadow-none"
>
<!-- Step 1 start -->
<h1 class="text-2xl font-bold md:text-4xl text-marine-blue">
Personal info
</h1>
<p class="py-3 text-cool-gray">
Please provide your name, email address, and phone number.
</p>
<div class="contents">
<label
for="name"
class="pt-3 text-sm md:pt-5 md:pb-2 text-marine-blue"
>Name</label
>
<input
id="name"
th:value="${formData.userAnswers.step1.name}"
name="name"
type="text"
required
placeholder="e.g. Stephen King"
class="p-1 px-4 h-10 text-sm font-semibold rounded border md:p-6 md:px-4 md:text-base md:rounded-lg focus:outline-none placeholder:text-cool-gray invalid:border-strawberry-red focus:border-marine-blue"
/>
</div>
<div class="contents">
<label
for="email"
class="pt-3 text-sm md:pt-5 md:pb-2 text-marine-blue"
>Email Address</label
>
<input
id="email"
th:value="${formData.userAnswers.step1.email}"
name="email"
type="email"
required
placeholder="e.g. stephenking@lorem.com"
class="p-1 px-4 h-10 text-sm font-semibold rounded border md:p-6 md:px-4 md:text-base md:rounded-lg focus:outline-none placeholder:text-cool-gray invalid:border-strawberry-red focus:border-marine-blue"
/>
</div>
<!-- Following is email input field
it has outer div that sets separate 'value' variable
and innder div which denotes fragment, parametrized by this only variable
now i should be able to render only this input field as fragment -->
<div
th:with="value=${formData.userAnswers.step1.phone},error=''"
class="contents relative"
>
<div
class="contents"
hx-target="this"
hx-swap="outerHTML"
th:fragment="email-input (value,error)"
>
<label
for="phone"
class="pt-3 text-sm md:pt-5 md:pb-2 text-marine-blue"
>Phone Number</label
>
<input
id="phone"
th:value="${value}"
name="phone"
type="tel"
required
placeholder="e.g. +1 234 567 890"
class="p-1 px-4 h-10 text-sm font-semibold rounded border md:p-6 md:px-4 md:text-base md:rounded-lg focus:outline-none placeholder:text-cool-gray invalid:border-strawberry-red focus:border-marine-blue"
th:classappend="${!error.isEmpty} ? 'border-strawberry-red' : ''"
hx-post="/step1/phonenumber"
hx-indicator="#ind"
/>
<div
th:if="${error} != null"
th:text="${error}"
class="text-sm text-strawberry-red">Please enter valid phone number</div>
<img
id="ind"
src="../public/images/tail-spin.svg"
th:src="'public/images/tail-spin.svg'"
class="absolute w-14 h-14 htmx-indicator"
/>
</div>
</div>
<!-- Step 1 end -->
</section>
<div class="md:hidden grow"></div>
<section
id="footer-controls"
class="flex flex-row items-center py-4 w-full bg-white md:items-end md:h-full"
>
<div class="grow"></div>
<input
type="submit"
class="grid place-content-center mr-3 w-24 h-10 text-sm font-semibold text-white rounded md:mr-24 md:w-32 md:h-12 md:text-base md:rounded-lg bg-marine-blue"
value="Next Step"
/>
<a
th:remove="all"
href="step2.html"
class="grid place-content-center mr-3 w-24 h-10 text-sm font-semibold text-white rounded md:mr-24 md:w-32 md:h-12 md:text-base md:rounded-lg bg-marine-blue"
>Next Step</a
>
</section>
</form>
<div class="fixed inset-x-0 bottom-0 attribution">
Challenge by
<a href="https://www.frontendmentor.io?ref=challenge" target="_blank"
>Frontend Mentor</a
>. Coded by <a href="#">Your Name Here</a>.
</div>
</body>
</html>

View File

@@ -1,260 +0,0 @@
<!DOCTYPE html>
<html class="no-js" lang="">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- displays site properly based on user's device -->
<link
rel="icon"
type="image/png"
sizes="32x32"
href="./assets/images/favicon-32x32.png"
/>
<link href="../public/out.css" rel="stylesheet" />
<title>Frontend Mentor | Multi-step form</title>
<!-- Feel free to remove these styles or customise in your own stylesheet 👍 -->
<style>
.attribution {
font-size: 11px;
text-align: center;
}
.attribution a {
color: hsl(228, 45%, 44%);
}
</style>
</head>
<body>
<!--[if lt IE 8]>
<p class="browserupgrade">
You are using an <strong>outdated</strong> browser. Please
<a href="http://browsehappy.com/">upgrade your browser</a> to improve
your experience.
</p>
<![endif]-->
<main class="grid place-content-center h-screen">
<form
class="flex flex-col items-center w-screen h-screen md:grid md:items-start md:p-5 md:bg-white md:rounded-2xl md:grid-cols-[auto_1fr] md:w-desktop-form md:h-desktop-form md:drop-shadow-2xl"
id="form-step"
hx-post="/submit-step/2/3"
hx-swap="outerHTML"
action="/submit-step/2/3"
method="post"
th:fragment="formFragment(formData)"
>
<summary
class="w-full h-44 bg-no-repeat md:row-span-2 bg-sidebar-mobile marker:text-white md:bg-sidebar-desktop md:h-[568px] md:w-[274px]"
id="sidebar"
th:replace="~{step1::stepsSummary (${formData})}"
>
<ol
class="grid grid-cols-[repeat(4,_auto)] gap-x-5 content-center items-center place-content-center h-24 md:flex-col md:h-full md:grid-rows-[repeat(4,_auto)] md:grid-cols-1 md:content-start md:p-10 md:gap-y-7 text-white text-sm uppercase"
>
<li class="items-center md:grid md:gap-x-4 md:grid-cols-[auto_1fr]">
<div
class="grid place-content-center w-8 h-8 text-white rounded-full border border-white"
>
1
</div>
<p class="hidden md:flex md:flex-col">
<span class="text-light-gray">Step 1</span
><span class="font-bold">Your info</span>
</p>
</li>
<li class="items-center md:grid md:gap-x-4 md:grid-cols-[auto_1fr]">
<div
class="grid place-content-center w-8 h-8 text-white rounded-full border border-white"
>
2
</div>
<p class="hidden md:flex md:flex-col">
<span class="text-light-gray">Step 2</span
><span class="font-bold">Select plan</span>
</p>
</li>
<li class="items-center md:grid md:gap-x-4 md:grid-cols-[auto_1fr]">
<div
class="grid place-content-center w-8 h-8 text-white rounded-full border border-white"
>
3
</div>
<p class="hidden md:flex md:flex-col">
<span class="text-light-gray">Step 3</span
><span class="font-bold">Add-ons</span>
</p>
</li>
<li class="items-center md:grid md:gap-x-4 md:grid-cols-[auto_1fr]">
<div
class="grid place-content-center w-8 h-8 text-white rounded-full border border-white"
>
4
</div>
<p class="hidden md:flex md:flex-col">
<span class="text-light-gray">Step 4</span
><span class="font-bold">summary</span>
</p>
</li>
</ol>
</summary>
<section
id="multipage-form-container"
class="flex flex-col py-8 px-6 -mt-20 w-11/12 bg-white rounded-xl md:px-24 md:mt-0 md:w-full drop-shadow-xl md:drop-shadow-none"
>
<!-- Step 2 start -->
<h1 class="text-2xl font-bold md:text-4xl text-marine-blue">
Select your plan
</h1>
<p class="py-3 mb-4 text-cool-gray">
You have the option of monthly or yearly billing.
</p>
<div
class="flex flex-col gap-y-3 my-3 w-full md:flex-row md:gap-x-4"
id="plan-type-inputs"
th:fragment="planTypesInputs(formData)"
>
<label
for="ArcadePlanType"
class="relative h-20 md:h-40 md:grow"
th:each="planType: ${formData.availablePlans}"
th:for="${planType}"
>
<input
id="ArcadePlanType"
th:id="${planType}"
type="radio"
name="plan-type"
value="Arcade"
th:value="${planType}"
class="hidden peer"
th:checked="${formData.userAnswers.step2.planType.toString()} == ${planType.toString()}"
checked
/>
<div
class="grid absolute inset-y-0 inset-x-0 place-content-center h-full rounded-lg border md:grid-cols-1 md:p-4 grid-cols-[auto_1fr] border-light-gray peer-checked:border-purplish-blue peer-checked:bg-magnolia/50 md:grid-rows-[1fr_auto_auto] hover:bg-magnolia/[.1] hover:border-purplish-blue"
>
<img
class="place-self-center px-4 md:row-span-1 md:place-self-start md:px-0"
th:src="${planType.iconPath}" src="../public/images/icon-arcade.svg" alt="" />
<div class="flex flex-col items-start">
<h2 th:text="${planType}" class="font-semibold text-marine-blue">Arcade</h2>
<p
th:text="|$${formData.planCost(planType)}/${formData.periodCostLabel}|"
class="text-sm text-cool-gray"
>
$9/mo
</p>
<p th:if="${formData.userAnswers.step2.isYearly}" class="text-xs text-marine-blue">
2 months free
</p>
</div>
</div>
</label>
<label
for="AdvancedPlanType"
class="relative h-20 md:w-32"
th:remove="all"
>
<input
id="AdvancedPlanType"
type="radio"
name="plan-type"
value="Advanced"
class="hidden peer"
th:checked="${formData.userAnswers.step2.planType.toString()} == 'Advanced'"
/>
<div
class="absolute inset-y-0 inset-x-0 rounded-lg border border-cool-gray peer-checked:border-purplish-blue peer-checked:bg-magnolia"
>
<img src="../public/images/icon-advanced.svg" alt="" />
<h2>Advanced</h2>
</div>
</label>
<label
for="ProPlanType"
class="relative h-20 md:w-32"
th:remove="all"
>
<input
id="ProPlanType"
type="radio"
name="plan-type"
value="Pro"
class="hidden peer"
th:checked="${formData.userAnswers.step2.planType.toString()} == 'Pro'"
/>
<div
class="absolute inset-y-0 inset-x-0 rounded-lg border border-cool-gray peer-checked:border-purplish-blue peer-checked:bg-magnolia"
>
<img src="../public/images/icon-pro.svg" alt="" />
<h2>Pro</h2>
</div>
</label>
</div>
<div
class="grid grid-flow-col-dense place-content-center mt-3 w-full rounded-lg md:mt-5 bg-light-gray/25"
>
<div
class="inline-grid grid-cols-3 place-items-center h-12 text-sm font-bold"
>
<input
class="mr-2 w-9 h-5 ml-2 rounded-full appearance-none mt-[0.3rem] bg-marine-blue after:absolute after:h-3 after:w-3 after:rounded-full after:border-none after:bg-neutral-100 after:transition-[background-color_0.2s,transform_0.2s] checked:after:ml-[1.2rem] after:ml-[0.25rem] after:mt-[0.25rem] hover:cursor-pointer col-start-2 row-start-1 peer md:mx-4"
type="checkbox"
name="isPackageYearly"
role="switch"
id="packageDuration"
th:checked="${formData.userAnswers.step2.isYearly}"
hx-post="/step2/planTypeInputs"
hx-target="#plan-type-inputs"
hx-swap="outerHTML"
/>
<p
class="row-start-1 text-marine-blue peer-checked:text-cool-gray"
>
Monthly
</p>
<p
class="row-start-1 text-cool-gray peer-checked:text-marine-blue"
>
Yearly
</p>
</div>
</div>
<!-- Step 2 end -->
</section>
<div class="md:hidden grow"></div>
<section
id="footer-controls"
class="flex flex-row items-center py-4 w-full bg-white md:items-end md:h-full"
>
<a
hx-post="/submit-step/2/1"
hx-swap="outerHTML"
hx-target="#form-step"
href="step1.html"
class="ml-6 text-sm font-semibold md:pb-3 md:ml-24 md:text-base text-cool-gray"
>Go Back</a
>
<div class="grow"></div>
<input
type="submit"
class="grid place-content-center mr-3 w-24 h-10 text-sm font-semibold text-white rounded md:mr-24 md:w-32 md:h-12 md:text-base md:rounded-lg bg-marine-blue"
value="Next Step"
/>
<a
th:remove="all"
href="step3.html"
class="grid place-content-center mr-3 w-24 h-10 text-sm font-semibold text-white rounded md:mr-24 md:w-32 md:h-12 md:text-base md:rounded-lg bg-marine-blue"
>Next Step</a
>
</section>
</form>
</main>
</body>
</html>

View File

@@ -1,241 +0,0 @@
<!DOCTYPE html>
<html class="no-js" lang="">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- displays site properly based on user's device -->
<link
rel="icon"
type="image/png"
sizes="32x32"
href="./assets/images/favicon-32x32.png"
/>
<link href="../public/out.css" rel="stylesheet" />
<title>Frontend Mentor | Multi-step form</title>
<!-- Feel free to remove these styles or customise in your own stylesheet 👍 -->
<style>
.attribution {
font-size: 11px;
text-align: center;
}
.attribution a {
color: hsl(228, 45%, 44%);
}
</style>
</head>
<body>
<!--[if lt IE 8]>
<p class="browserupgrade">
You are using an <strong>outdated</strong> browser. Please
<a href="http://browsehappy.com/">upgrade your browser</a> to improve
your experience.
</p>
<![endif]-->
<main class="grid place-content-center h-screen">
<form
class="flex flex-col items-center w-screen h-screen md:grid md:items-start md:p-5 md:bg-white md:rounded-2xl md:grid-cols-[auto_1fr] md:w-desktop-form md:h-desktop-form md:drop-shadow-2xl"
id="form-step"
hx-post="/submit-step/3/4"
hx-swap="outerHTML"
action="/submit-step/3/4"
method="post"
th:fragment="formFragment(formData)"
>
<summary
class="w-full h-44 bg-no-repeat md:row-span-2 bg-sidebar-mobile marker:text-white md:bg-sidebar-desktop md:h-[568px] md:w-[274px]"
id="sidebar"
th:replace="~{step1::stepsSummary (${formData})}"
>
<ol
class="grid grid-cols-[repeat(4,_auto)] gap-x-5 content-center items-center place-content-center h-24 md:flex-col md:h-full md:grid-rows-[repeat(4,_auto)] md:grid-cols-1 md:content-start md:p-10 md:gap-y-7 text-white text-sm uppercase"
>
<li class="items-center md:grid md:gap-x-4 md:grid-cols-[auto_1fr]">
<div
class="grid place-content-center w-8 h-8 text-white rounded-full border border-white"
>
1
</div>
<p class="hidden md:flex md:flex-col">
<span class="text-light-gray">Step 1</span
><span class="font-bold">Your info</span>
</p>
</li>
<li class="items-center md:grid md:gap-x-4 md:grid-cols-[auto_1fr]">
<div
class="grid place-content-center w-8 h-8 text-white rounded-full border border-white"
>
2
</div>
<p class="hidden md:flex md:flex-col">
<span class="text-light-gray">Step 2</span
><span class="font-bold">Select plan</span>
</p>
</li>
<li class="items-center md:grid md:gap-x-4 md:grid-cols-[auto_1fr]">
<div
class="grid place-content-center w-8 h-8 text-white rounded-full border border-white"
>
3
</div>
<p class="hidden md:flex md:flex-col">
<span class="text-light-gray">Step 3</span
><span class="font-bold">Add-ons</span>
</p>
</li>
<li class="items-center md:grid md:gap-x-4 md:grid-cols-[auto_1fr]">
<div
class="grid place-content-center w-8 h-8 text-white rounded-full border border-white"
>
4
</div>
<p class="hidden md:flex md:flex-col">
<span class="text-light-gray">Step 4</span
><span class="font-bold">summary</span>
</p>
</li>
</ol>
</summary>
<section
id="multipage-form-container"
class="flex flex-col py-8 px-6 -mt-20 w-11/12 bg-white rounded-xl md:px-24 md:mt-0 md:w-full drop-shadow-xl md:drop-shadow-none"
>
<!-- Step 3 start -->
<h1 class="text-2xl font-bold md:text-4xl text-marine-blue">
Pick add-ons
</h1>
<p class="py-3 md:pb-10 text-cool-gray">
Add-ons help enhance your gaming experience.
</p>
<div class="flex flex-col gap-y-3 w-full text-sm md:text-base">
<label
th:each="addon: ${formData.availableAddons}"
for="multiplayer-games"
th:for="${addon}"
class="relative pl-5 h-16 md:w-full md:h-20"
>
<input
id="multiplayer-games"
th:id="${addon}"
type="checkbox"
value="OnlineService"
th:value="${addon}"
name="addon-services"
class="absolute z-40 my-5 w-6 h-6 text-white rounded-lg border md:my-7 accent-purplish-blue border-light-gray peer"
th:checked="${formData.userAnswers.step3.containsAddon(addon)}"
/>
<div
class="absolute inset-y-0 inset-x-0 z-20 rounded-lg border border-cool-gray peer-checked:border-purplish-blue peer-checked:bg-magnolia/75 hover:bg-magnolia/[.1] hover:border-purplish-blue"
>
<div
class="grid place-content-center ml-16 h-full grid-cols-[1fr_70px]"
>
<h1 th:text="${addon.name}"
class="font-bold text-marine-blue"
>Online Service</h1>
<p th:text="${addon.description}"
class="text-xs text-cool-gray"
>
Access to multiplayer games
</p>
<p
class="col-start-2 row-span-2 row-start-1 self-center text-purplish-blue"
th:text="|+$${formData.addonCost(addon)}/${formData.periodCostLabel}|"
>
+$1/mo
</p>
</div>
</div>
</label>
<label
for="larger-storage"
class="relative pl-6 h-20 md:w-full"
th:remove="all"
>
<input
id="larger-storage"
type="checkbox"
name="addon-services"
value="LargerStorage"
class="my-7 w-6 h-6 peer"
th:checked="${formData.userAnswers.step3.containsAddon('LargerStorage')}"
/>
<div
class="absolute inset-y-0 inset-x-0 rounded-lg border border-cool-gray peer-checked:border-purplish-blue peer-checked:bg-magnolia/50"
>
<div
class="grid place-content-center ml-20 h-full grid-cols-[1fr_100px]"
>
<h1>Larger storage</h1>
<p>Extra 1TB of cloud save</p>
<p class="col-start-2 row-span-2 row-start-1 self-center">
+$2/mo
</p>
</div>
</div>
</label>
<label
for="custom-profile"
class="relative pl-6 h-20 md:w-full"
th:remove="all"
>
<input
id="custom-profile"
type="checkbox"
name="addon-services"
value="CustomProfile"
class="my-7 w-6 h-6 peer"
th:checked="${formData.userAnswers.step3.containsAddon('CustomProfile')}"
/>
<div
class="absolute inset-y-0 inset-x-0 rounded-lg border border-cool-gray peer-checked:border-purplish-blue peer-checked:bg-magnolia/50"
>
<div
class="grid place-content-center ml-20 h-full grid-cols-[1fr_100px]"
>
<h1>Customizable Profile</h1>
<p>Custom theme on your profile</p>
<p class="col-start-2 row-span-2 row-start-1 self-center">
+$2/mo
</p>
</div>
</div>
</label>
</div>
<!-- Step 3 end -->
</section>
<div class="md:hidden grow"></div>
<section
id="footer-controls"
class="flex flex-row items-center py-4 w-full bg-white md:items-end md:h-full"
>
<a
hx-post="/submit-step/3/2"
hx-swap="outerHTML"
hx-target="#form-step"
href="step2.html"
class="ml-6 text-sm font-semibold md:pb-3 md:ml-24 md:text-base text-cool-gray"
>Go Back</a
>
<div class="grow"></div>
<input
type="submit"
href="step4.html"
class="grid place-content-center mr-3 w-24 h-10 text-sm font-semibold text-white rounded md:mr-24 md:w-32 md:h-12 md:text-base md:rounded-lg bg-marine-blue"
value="Next Step"
/>
<a
th:remove="all"
href="step4.html"
class="grid place-content-center mr-3 w-24 h-10 text-sm font-semibold text-white rounded md:mr-24 md:w-32 md:h-12 md:text-base md:rounded-lg bg-marine-blue"
>Next Step</a
>
</section>
</form>
</main>
</body>
</html>

View File

@@ -1,204 +0,0 @@
<!DOCTYPE html>
<html class="no-js" lang="">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- displays site properly based on user's device -->
<link
rel="icon"
type="image/png"
sizes="32x32"
href="./assets/images/favicon-32x32.png"
/>
<link href="../public/out.css" rel="stylesheet" />
<title>Frontend Mentor | Multi-step form</title>
<!-- Feel free to remove these styles or customise in your own stylesheet 👍 -->
<style>
.attribution {
font-size: 11px;
text-align: center;
}
.attribution a {
color: hsl(228, 45%, 44%);
}
</style>
</head>
<body>
<!--[if lt IE 8]>
<p class="browserupgrade">
You are using an <strong>outdated</strong> browser. Please
<a href="http://browsehappy.com/">upgrade your browser</a> to improve
your experience.
</p>
<![endif]-->
<main class="grid place-content-center h-screen">
<form
class="flex flex-col items-center w-screen h-screen md:grid md:items-start md:p-5 md:bg-white md:rounded-2xl md:grid-cols-[auto_1fr] md:w-desktop-form md:h-desktop-form md:drop-shadow-2xl"
id="form-step"
hx-post="/submit-step/4/5"
action="/submit-step/4/5"
hx-swap="outerHTML"
method="post"
th:fragment="formFragment(formData)"
>
<summary
class="w-full h-44 bg-no-repeat md:row-span-2 bg-sidebar-mobile marker:text-white md:bg-sidebar-desktop md:h-[568px] md:w-[274px]"
id="sidebar"
th:replace="~{step1::stepsSummary (${formData})}"
>
<ol
class="grid grid-cols-[repeat(4,_auto)] gap-x-5 content-center items-center place-content-center h-24 md:flex-col md:h-full md:grid-rows-[repeat(4,_auto)] md:grid-cols-1 md:content-start md:p-10 md:gap-y-7 text-white text-sm uppercase"
>
<li class="items-center md:grid md:gap-x-4 md:grid-cols-[auto_1fr]">
<div
class="grid place-content-center w-8 h-8 text-white rounded-full border border-white"
>
1
</div>
<p class="hidden md:flex md:flex-col">
<span class="text-light-gray">Step 1</span
><span class="font-bold">Your info</span>
</p>
</li>
<li class="items-center md:grid md:gap-x-4 md:grid-cols-[auto_1fr]">
<div
class="grid place-content-center w-8 h-8 text-white rounded-full border border-white"
>
2
</div>
<p class="hidden md:flex md:flex-col">
<span class="text-light-gray">Step 2</span
><span class="font-bold">Select plan</span>
</p>
</li>
<li class="items-center md:grid md:gap-x-4 md:grid-cols-[auto_1fr]">
<div
class="grid place-content-center w-8 h-8 text-white rounded-full border border-white"
>
3
</div>
<p class="hidden md:flex md:flex-col">
<span class="text-light-gray">Step 3</span
><span class="font-bold">Add-ons</span>
</p>
</li>
<li class="items-center md:grid md:gap-x-4 md:grid-cols-[auto_1fr]">
<div
class="grid place-content-center w-8 h-8 text-white rounded-full border border-white"
>
4
</div>
<p class="hidden md:flex md:flex-col">
<span class="text-light-gray">Step 4</span
><span class="font-bold">summary</span>
</p>
</li>
</ol>
</summary>
<section
id="multipage-form-container"
class="flex flex-col py-8 px-6 -mt-20 w-11/12 bg-white rounded-xl md:px-24 md:mt-0 md:w-full drop-shadow-xl md:drop-shadow-none"
>
<!-- Step 3 start -->
<h1 class="text-2xl font-bold md:text-4xl text-marine-blue">
Finishing up
</h1>
<p class="pt-3 pb-5 md:pb-8 text-cool-gray">
Double-check everything looks OK before confirming.
</p>
<div
class="flex flex-col w-full text-sm rounded-lg divide-y md:text-base bg-magnolia/75"
id="selection-overview"
>
<div id="selected-plan" class="grid p-3 md:p-6 grid-cols-[1fr_auto]">
<h2 th:text="${formData.fullPlanName}"
class="font-bold text-marine-blue"
>Arcade (Monthly)</h2>
<p
th:text="|$${formData.selectedPlanCost}/${formData.periodCostLabel}|"
class="row-span-2 self-end font-bold text-marine-blue"
>
$90/y
</p>
<a
hx-post="/submit-step/4/2"
hx-swap="outerHTML"
hx-target="#form-step"
href="step3.html"
hx-params="not form-confirmed"
class="underline text-cool-gray"
>Change</a
>
</div>
<div id="selected-addons" class="flex flex-col gap-y-4 p-3 md:p-6 mp-10"
th:if="not ${formData.userAnswers.step3.addonsAsJava.isEmpty}"
>
<div
th:each="addon: ${formData.userAnswers.step3.addonsAsJava}"
class="flex flex-row"
>
<p th:text="${addon.name}" class="grow text-cool-gray">Online service</p>
<p
th:text="|+$${formData.addonCost(addon)}/${formData.periodCostLabel}|"
>
+$10/yr
</p>
</div>
<div th:remove="all">Larger storage +$20/yr</div>
</div>
</div>
<section class="flex flex-row p-3 mt-5 md:px-6">
<p class="grow text-cool-gray">
Total (per
<span
th:text="${formData.userAnswers.step2.isYearly} ? 'year' : 'month'"
>year</span
>)
</p>
<p
th:text="|+$${formData.fullOrderPrice}/${formData.periodCostLabel}|"
class="font-bold md:text-lg text-purplish-blue"
>
$120
</p>
</section>
<!-- Step 3 end -->
</section>
<div class="md:hidden grow"></div>
<section
id="footer-controls"
class="flex flex-row items-center py-4 w-full bg-white md:items-end md:h-full"
>
<a
hx-post="/submit-step/4/3"
hx-swap="outerHTML"
hx-target="#form-step"
href="step3.html"
class="ml-6 text-sm font-semibold md:pb-3 md:ml-24 md:text-base text-cool-gray"
hx-params="not form-confirmed"
>Go Back</a
>
<div class="grow"></div>
<input type="hidden" name="form-confirmed" value="true" />
<input
type="submit"
class="grid place-content-center mr-3 w-24 h-10 text-sm font-semibold text-white rounded md:mr-24 md:w-32 md:h-12 md:text-base md:rounded-lg bg-purplish-blue"
value="Confirm"
/>
<a
th:remove="all"
href="step5.html"
class="grid place-content-center mr-3 w-24 h-10 text-sm font-semibold text-white rounded md:mr-24 md:w-32 md:h-12 md:text-base md:rounded-lg bg-purplish-blue"
>Confirm</a
>
</section>
</form>
</main>
</body>
</html>

View File

@@ -1,119 +0,0 @@
<!DOCTYPE html>
<html class="no-js" lang="">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- displays site properly based on user's device -->
<link
rel="icon"
type="image/png"
sizes="32x32"
href="./assets/images/favicon-32x32.png"
/>
<link href="../public/out.css" rel="stylesheet" />
<title>Frontend Mentor | Multi-step form</title>
<!-- Feel free to remove these styles or customise in your own stylesheet 👍 -->
<style>
.attribution {
font-size: 11px;
text-align: center;
}
.attribution a {
color: hsl(228, 45%, 44%);
}
</style>
</head>
<body>
<!--[if lt IE 8]>
<p class="browserupgrade">
You are using an <strong>outdated</strong> browser. Please
<a href="http://browsehappy.com/">upgrade your browser</a> to improve
your experience.
</p>
<![endif]-->
<main class="grid place-content-center h-screen">
<article
class="flex flex-col items-center w-screen h-screen md:grid md:items-start md:p-5 md:bg-white md:rounded-2xl md:grid-cols-[auto_1fr] md:w-desktop-form md:h-desktop-form md:drop-shadow-2xl"
id="form-step"
th:fragment="formFragment(formData)"
>
<summary
class="w-full h-44 bg-no-repeat md:row-span-2 bg-sidebar-mobile marker:text-white md:bg-sidebar-desktop md:h-[568px] md:w-[274px]"
id="sidebar"
th:replace="~{step1::stepsSummary (${formData})}"
>
<ol
class="grid grid-cols-[repeat(4,_auto)] gap-x-5 content-center items-center place-content-center h-24 md:flex-col md:h-full md:grid-rows-[repeat(4,_auto)] md:grid-cols-1 md:content-start md:p-10 md:gap-y-7 text-white text-sm uppercase"
>
<li class="items-center md:grid md:gap-x-4 md:grid-cols-[auto_1fr]">
<div
class="grid place-content-center w-8 h-8 text-white rounded-full border border-white"
>
1
</div>
<p class="hidden md:flex md:flex-col">
<span class="text-light-gray">Step 1</span
><span class="font-bold">Your info</span>
</p>
</li>
<li class="items-center md:grid md:gap-x-4 md:grid-cols-[auto_1fr]">
<div
class="grid place-content-center w-8 h-8 text-white rounded-full border border-white"
>
2
</div>
<p class="hidden md:flex md:flex-col">
<span class="text-light-gray">Step 2</span
><span class="font-bold">Select plan</span>
</p>
</li>
<li class="items-center md:grid md:gap-x-4 md:grid-cols-[auto_1fr]">
<div
class="grid place-content-center w-8 h-8 text-white rounded-full border border-white"
>
3
</div>
<p class="hidden md:flex md:flex-col">
<span class="text-light-gray">Step 3</span
><span class="font-bold">Add-ons</span>
</p>
</li>
<li class="items-center md:grid md:gap-x-4 md:grid-cols-[auto_1fr]">
<div
class="grid place-content-center w-8 h-8 text-white rounded-full border border-white"
>
4
</div>
<p class="hidden md:flex md:flex-col">
<span class="text-light-gray">Step 4</span
><span class="font-bold">summary</span>
</p>
</li>
</ol>
</summary>
<section
id="multipage-form-container"
class="flex flex-col gap-y-4 items-center py-20 px-8 -mt-20 w-11/12 bg-white rounded-xl md:row-span-2 md:justify-center md:px-24 md:mt-0 md:w-full md:h-full drop-shadow-xl md:drop-shadow-none"
>
<!-- Step 5 start -->
<img src="../public/images/icon-thank-you.svg" alt="" class="mb-2 w-14 h-14 md:w-20 md:h-20" />
<h2 class="text-2xl font-bold md:mt-2 md:text-4xl text-marine-blue">Thank you!</h2>
<p class="text-center text-cool-gray">
Thanks for confirming your subscription! We hope you have fun
using our platform. If you ever need support, please feel free
to email us at support@loremgaming.com.
</p>
<!-- Step 5 end -->
</section>
<div class="md:hidden grow"></div>
</article>
</main>
</body>
</html>

View File

@@ -1,22 +0,0 @@
package multistepform
import mainargs.{main, arg, ParserForMethods}
object Main {
@main def run(
@arg(name="port", short='p', doc="Port on which server will start service")
portArg: Int = 8080,
@arg(name="host", doc="Host on which server will start serving")
hostArg: String = "localhost"
): Unit = {
println(s"Will start server on ${hostArg}:${portArg}")
val server = new cask.Main {
override def allRoutes: Seq[cask.main.Routes] = Seq(Routes())
override def port: Int = portArg
override def host: String = hostArg
}
server.main(Array.empty)
}
def main(args: Array[String]): Unit = ParserForMethods(this).runOrExit(args)
}

View File

@@ -1,219 +0,0 @@
package multistepform
import java.util.UUID
import scala.jdk.CollectionConverters._
object Models {
/** Labels and form info which dynamically depend on user answers e.g plan
* name 'Arcade (Yearly)' vs 'Pro (Monthly)'
*/
final case class FormData(
userAnswers: Answers
) {
val stepsAmount = Steps.values.toList.asJava
// yeah, in real world it will not be this simple
def yearlyCost(monthlyCost: Int): Int = 10 * monthlyCost
def periodCostLabel: String = {
if (userAnswers.step2.isYearly) "yr" else "mo"
}
def selectedPlanCost: Int = planCost(userAnswers.step2.planType)
def planCost(plan: PlanType): Int = {
val monthlyPlanCost = plan.monthlyCost
if (userAnswers.step2.isYearly) yearlyCost(monthlyPlanCost)
else monthlyPlanCost
}
def addonCost(addon: Addons): Int = {
val monthCost = addon.monthlyCost
if (userAnswers.step2.isYearly) yearlyCost(monthCost) else monthCost
}
def fullPlanName: String = {
val period = if (userAnswers.step2.isYearly) "Yearly" else "Monthly"
s"${userAnswers.step2.planType} (${period})"
}
def fullOrderPrice: Int = {
selectedPlanCost + userAnswers.step3.addons.toList.map(addonCost).sum
}
def availablePlans = PlanType.values.toList.asJava
def availableAddons = Addons.values.toList.asJava
}
final case class Answers(
sessionId: String = "",
currentStep: Int = 1,
step1: StepAnswers.Step1 = StepAnswers.Step1(),
step2: StepAnswers.Step2 = StepAnswers.Step2(),
step3: StepAnswers.Step3 = StepAnswers.Step3(),
step4: StepAnswers.Step4 = StepAnswers.Step4()
) {
// this is not enforced by compiler, sad, maintain by hand in html template files
def fragmentName: String = s"step${currentStep}"
def updateStep(stepNum: Int, rawData: String, nextStep: Int): Answers = {
stepNum match {
case 1 =>
this.copy(
step1 = this.step1.fromFormData(rawData),
currentStep = nextStep
)
case 2 =>
this.copy(
step2 = this.step2.fromFormData(rawData),
currentStep = nextStep
)
case 3 =>
this.copy(
step3 = this.step3.fromFormData(rawData),
currentStep = nextStep
)
case 4 =>
this.copy(
step4 = this.step4.fromFormData(rawData),
currentStep = nextStep
)
case _ => this
}
}
}
/** TODO would be nice to connect answers to the steps enum in some helpful
* way.
*/
enum Steps(val index: Int, val name: String):
case Step1 extends Steps(1, "Your info")
case Step2 extends Steps(2, "Select plan")
case Step3 extends Steps(3, "Add-ons")
case Step4 extends Steps(4, "Summary")
enum PlanType(val monthlyCost: Int, val iconPath: String):
case Arcade extends PlanType(9, "public/images/icon-arcade.svg")
case Advanced extends PlanType(12, "public/images/icon-advanced.svg")
case Pro extends PlanType(15, "public/images/icon-pro.svg")
def name(): String = {
this.toString().replaceAll("([a-z])([A-Z])", "$1 $2")
}
enum Addons(val monthlyCost: Int, val description: String):
case OnlineService extends Addons(1, "Access to multiplayer games")
case LargerStorage extends Addons(2, "Extra 1TB of cloud storage")
case CustomProfile extends Addons(2, "Custom theme on your profile")
/** Change camel case into human readable. Adding single space before each
* uppercase
*/
def name(): String = {
this.toString().replaceAll("([a-z])([A-Z])", "$1 $2")
}
sealed trait StepAnswers {
def fromFormData(rawData: String): StepAnswers
def submitted: Boolean
}
object StepAnswers {
final case class Step1(
name: String = "",
email: String = "",
phone: String = "",
override val submitted: Boolean = false
) extends StepAnswers {
override def fromFormData(rawData: String): Step1 = {
println(s"parsing step 1 data $rawData")
val fieldValues = rawData
.split("&")
.filterNot(_.isEmpty())
.map { field =>
val Array(name, value) = field.split("=")
name -> value
}
.toMap
val name = fieldValues.getOrElse("name", "")
val email = fieldValues.getOrElse("email", "")
val phone = fieldValues.getOrElse("phone", "")
Step1(name, email, phone, submitted = true)
}
}
final case class Step2(
planType: PlanType = PlanType.Arcade,
isYearly: Boolean = false,
override val submitted: Boolean = false
) extends StepAnswers {
override def fromFormData(rawData: String): Step2 = {
println(s"parsing step 2 data $rawData")
val fieldValues = rawData
.split("&")
.filterNot(_.isEmpty())
.map { field =>
val Array(name, value) = field.split("=")
name -> value
}
.toMap
val planType =
PlanType.valueOf(fieldValues.getOrElse("plan-type", "Arcade"))
val isYearly = fieldValues.get("isPackageYearly").contains("on")
Step2(planType, isYearly, submitted = true)
}
}
final case class Step3(
addons: Set[Addons] = Set.empty,
override val submitted: Boolean = false
) extends StepAnswers {
def addonsAsJava = addons.asJava
def containsAddon(addonName: String): Boolean = {
addons.contains(Addons.valueOf(addonName))
}
override def fromFormData(rawData: String): Step3 = {
println(s"parsing step 3 data $rawData")
// for multiple checkboxes data comes in form of
// addon-services=OnlineService&addon-services=CustomProfile
val fieldValues = rawData
.split("&")
.filterNot(_.isEmpty())
.map { field =>
val Array(name, value) = field.split("=")
name -> value
}
val addonsStrings = fieldValues
.groupMap(_._1)(_._2)
.getOrElse("addon-services", Array.empty[String])
println(s"in step 3 got strings ${addonsStrings.mkString(", ")}")
val addons = addonsStrings.map(Addons.valueOf(_)).toSet
Step3(addons, submitted = true)
}
}
final case class Step4(
override val submitted: Boolean = false
) extends StepAnswers {
override def fromFormData(rawData: String): Step4 = {
val fieldValues = rawData
.split("&")
.filterNot(_.isEmpty())
.map { field =>
println(s"working with field $field")
val Array(name, value) = field.split("=")
name -> value
}
.toMap
val isConfirmed = fieldValues.contains("form-confirmed")
Step4(isConfirmed)
}
}
}
}

View File

@@ -1,222 +0,0 @@
package multistepform
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver
import org.thymeleaf.TemplateEngine
import org.thymeleaf.context.Context
import cask.endpoints.ParamReader
import java.util.UUID
import scala.jdk.CollectionConverters._
import multistepform.Models.Answers
import scala.annotation.internal.requiresCapability
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber.CountryCodeSource
import com.google.i18n.phonenumbers.PhoneNumberUtil
import java.net.URLDecoder
import scala.util.Try
case class Routes()(implicit cc: castor.Context, log: cask.Logger)
extends cask.Routes {
val templateResolver = new ClassLoaderTemplateResolver()
templateResolver.setPrefix("templates/");
templateResolver.setSuffix(".html")
templateResolver.setTemplateMode("HTML5")
val templateEngine = new TemplateEngine()
templateEngine.setTemplateResolver(templateResolver)
val sessoinCookieName = "sessionId"
/** This route works with and without 'sessionId' cookie present set's this
* cookie if not present, and returns initial 'index.html' where the form is
* not yet initialized, and will be requested for the session
*/
@cask.get("/")
def getIndex(ctx: cask.Request) = {
val sessionCookie = ctx.cookies.get(sessoinCookieName)
lazy val newSessionCookies = sessionCookie match {
case None =>
Seq(
cask.Cookie(
sessoinCookieName,
UUID.randomUUID().toString(),
path = "/"
)
)
case Some(_) => Seq.empty // don't set new cookies
}
println(s"getting cookie $sessionCookie will set new? ${newSessionCookies}")
val context = new Context()
val indexPage = templateEngine.process("index", context)
cask.Response(
indexPage,
headers = Seq("Content-Type" -> "text/html;charset=UTF-8"),
cookies = newSessionCookies
)
}
@cask.get("/force-new-session")
def forceNewSession() = {
val newSessionCookie =
cask.Cookie(sessoinCookieName, UUID.randomUUID().toString(), path = "/")
println(s"setting new session ${newSessionCookie.value}")
cask.Response(
s"New session forced. Force new session",
headers = Seq("Content-Type" -> "text/html;charset=UTF-8"),
cookies = Seq(newSessionCookie)
)
}
val formDataContextVarName = "formData"
/** This method only works when cookie 'sessionId' is present will get or init
* Form State for the session, and return last unsubmitted form step fragment
*/
@cask.get("/get-form")
def getForm(sessionId: cask.Cookie) = {
val id = sessionId.value
val state = Sessions.sessionReplies.getOrElse(id, Answers(id))
println(s"starting form for $state")
val context = new Context()
val formData = Models.FormData(state)
context.setVariable(formDataContextVarName, formData)
val formFragment = templateEngine.process(
state.fragmentName,
Set("formFragment").asJava,
context
)
cask.Response(
formFragment,
headers = Seq("Content-Type" -> "text/html;charset=UTF-8")
)
}
@cask.post("/submit-step/:stepNum/:nextStep")
def submitStep(
sessionId: cask.Cookie,
stepNum: Int,
nextStep: Int,
request: cask.Request
) = {
val id = sessionId.value
println(s"got $request for $id. it's data is ${request.text()}")
// note: this is nice at step #1 because not storing anything before first submission
// but on followup steps, if data lost - new default object is created
// and that is not nice
val userAnswers = Sessions.sessionReplies.getOrElse(id, Answers(id))
val submittedData = URLDecoder.decode(request.text(), "UTF-8")
val updatedAnswers =
userAnswers.updateStep(stepNum, submittedData, nextStep)
Sessions.sessionReplies.update(id, updatedAnswers)
val context = new Context()
val formData = Models.FormData(updatedAnswers)
context.setVariable(formDataContextVarName, formData)
val nextFormFragment = templateEngine.process(
updatedAnswers.fragmentName,
Set("formFragment").asJava,
context
)
println(s"the state now is $updatedAnswers")
cask.Response(
nextFormFragment,
headers = Seq("Content-Type" -> "text/html;charset=UTF-8")
)
}
@cask.post("/step1/phonenumber")
def validateStep1PhoneNumber(request: cask.Request) = {
val submittedData = URLDecoder.decode(request.text(), "UTF-8")
println(
s"getting data ${request.data} or ${request.text()} or $submittedData"
)
val fieldValues = submittedData
.split("&")
.filterNot(_.isEmpty())
.map { field =>
println(s"looking at field $field")
val (name, value) = field.split("=").toList match {
case List(name, value) => name -> value
case name :: tail => name -> tail.headOption.getOrElse("")
case Nil => ???
}
name -> value
}
.toMap
val name = fieldValues.getOrElse("name", "")
val email = fieldValues.getOrElse("email", "")
val phone = fieldValues.getOrElse("phone", "")
println(s"after parsing name=$name | email=$email | phone=$phone")
val phoneUtils = PhoneNumberUtil.getInstance()
val phoneNum = Try(
phoneUtils.parse(phone, CountryCodeSource.UNSPECIFIED.name())
).toOption
val isPhoneValid = phoneNum.map(phoneUtils.isValidNumber(_)).getOrElse(false)
val error = if (isPhoneValid) "" else "Please input valid phone number"
val context = new Context()
context.setVariable("value", phone)
context.setVariable("error", error)
val inputDiv =
templateEngine.process("step1", Set("email-input").asJava, context)
cask.Response(
inputDiv,
headers = Seq("Content-Type" -> "text/html;charset=UTF-8")
)
}
/** This endpoint re-renders 'plan type inputs' so that togglng monthly\yearly
* could redraw their html
*/
@cask.post("/step2/planTypeInputs")
def getPlanTypeInputs(sessionId: cask.Cookie, request: cask.Request) = {
val id = sessionId.value
val submittedData = URLDecoder.decode(request.text(), "UTF-8")
println(s"requesting plan type inputs for $id and $request")
Sessions.sessionReplies.get(id) match {
case None =>
cask.Response(
"Can't find answers for your session, please reload the page",
404
)
case Some(answers) => {
// here changing yearly/monthly part of state based on passed checkbox value
// and selected plan
// only for purposes of rendering the fragment
// not persisting, unless next or previous buttons are pressed
val withYearlyParamSetAndSelectedPlan =
answers.step2.fromFormData(submittedData)
val updatedState =
answers.copy(step2 = withYearlyParamSetAndSelectedPlan)
val formData = Models.FormData(updatedState)
val context = new Context()
context.setVariable(formDataContextVarName, formData)
val planTypesInputsHtml = templateEngine.process(
"step2",
Set("planTypesInputs").asJava,
context
)
println(s"updating plan type inputs for $answers")
cask.Response(
planTypesInputsHtml,
headers = Seq("Content-Type" -> "text/html;charset=UTF-8")
)
}
}
}
@cask.staticResources("/public")
def publicFiles() = "public"
initialize()
}

View File

@@ -1,11 +0,0 @@
package multistepform
import multistepform.Models.Answers
object Sessions {
// the simplest form of storing data
// i'll be relying on Render.com killing my app after 15 minutes of inactivity for GC
// no need to manage concurrency really, because requests for same session are really far apart
// and load will average to be 10req/day :shrug:
val sessionReplies = scala.collection.mutable.Map.empty[String, Answers]
}

View File

@@ -1,8 +0,0 @@
package example
class ExampleSuite extends munit.FunSuite:
test("addition") {
assert(1 + 1 == 2)
}
end ExampleSuite

View File

@@ -1,37 +0,0 @@
# Front-end Style Guide
## Layout
The designs were created to the following widths:
- Mobile: 375px
- Desktop: 1440px
## Colors
### Primary
- Marine blue: hsl(213, 96%, 18%)
- Purplish blue: hsl(243, 100%, 62%)
- Pastel blue: hsl(228, 100%, 84%)
- Light blue: hsl(206, 94%, 87%)
- Strawberry red: hsl(354, 84%, 57%)
### Neutral
- Cool gray: hsl(231, 11%, 63%)
- Light gray: hsl(229, 24%, 87%)
- Magnolia: hsl(217, 100%, 97%)
- Alabaster: hsl(231, 100%, 99%)
- White: hsl(0, 0%, 100%)
## Typography
### Body Copy
- Font size (paragraph): 16px
### Font
- Family: [Ubuntu](https://fonts.google.com/specimen/Ubuntu)
- Weights: 400, 500, 700

View File

@@ -1,41 +0,0 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ["./src/**/*.{scala,html}"],
theme: {
extend: {
colors: {
// ### Primary
"marine-blue": "hsl(213, 96%, 18%)",
"purplish-blue": "hsl(243, 100%, 62%)",
"pastel-blue": "hsl(228, 100%, 84%)",
"light-blue": "hsl(206, 94%, 87%)",
"strawberry-red": "hsl(354, 84%, 57%)",
// ### neutral
"cool-gray": "hsl(231, 11%, 63%)",
"light-gray": "hsl(229, 24%, 87%)",
magnolia: "hsl(217, 100%, 97%)",
alabaster: "hsl(231, 100%, 99%)",
},
backgroundImage: {
'sidebar-mobile': 'url("images/bg-sidebar-mobile.svg")',
'sidebar-desktop': 'url("images/bg-sidebar-desktop.svg")',
},
fontFamily: {
'sans': ['Ubuntu', 'sans-serif'], // This will set Roboto as the default sans font
},
fontWeight: {
'normal': 400,
'semibold': 600,
'bold': 700,
},
width: {
'desktop-form': '60rem',
},
height: {
'desktop-form': '38rem',
},
},
},
plugins: [],
};

View File

@@ -1,16 +0,0 @@
.bsp/
.scala-build/
.metals/
.direnv
*/dist/
/11-single-price-grid-component/.bloop/
**/.bloop
**/project/project/
**/project/metals.sbt
**/project/.bloop
**/project/target/
**/target/
*/result
result

View File

@@ -1,2 +0,0 @@
version = "3.7.10"
runner.dialect = scala3

View File

@@ -1,136 +0,0 @@
* Frontend Mentor - REST Countries API with color theme switcher solution
:PROPERTIES:
:CUSTOM_ID: frontend-mentor---rest-countries-api-with-color-theme-switcher-solution
:END:
This is a solution to the
[[https://www.frontendmentor.io/challenges/rest-countries-api-with-color-theme-switcher-5cacc469fec04111f7b848ca][REST
Countries API with color theme switcher challenge on Frontend Mentor]].
Frontend Mentor challenges help you improve your coding skills by
building realistic projects.
** Overview
:PROPERTIES:
:CUSTOM_ID: overview
:END:
*** The challenge
:PROPERTIES:
:CUSTOM_ID: the-challenge
:END:
Users should be able to:
- See all countries from the API on the homepage
- Search for a country using an =input= field
- Filter countries by region
- Click on a country to see more detailed information on a separate page
- Click through to the border countries on the detail page
- Toggle the color scheme between light and dark mode /(optional)/
*** Screenshot
:PROPERTIES:
:CUSTOM_ID: screenshot
:END:
[[mobile-main.png]]
[[mobile-single.png]]
[[desktop-main.png]]
[[desktop-single.png]]
*** Links
:PROPERTIES:
:CUSTOM_ID: links
:END:
- Solution URL: https://github.com/efim/Learning-HTMX/tree/master/16-countries-page-from-api
- Live Site URL: https://efim-frontentmentor-countries-page.onrender.com/
** My process
:PROPERTIES:
:CUSTOM_ID: my-process
:END:
*** Built with
:PROPERTIES:
:CUSTOM_ID: built-with
:END:
- Scala Server Side Rendering
- Htmx
- TailwindCSS
- Flexbox
- CSS Grid
- Mobile-first workflow
*** What I learned
:PROPERTIES:
:CUSTOM_ID: what-i-learned
:END:
**** polling download for 'infinite scroll'
https://htmx.org/examples/infinite-scroll/
I've done almost same thing as example,
but i'm appending additional empty div, that inserts responses instead of itself
this way i have one template fragment with repeater,
and don't have to add hx attributes to the last one,
i just have separate fragment that i append to response which will trigger new
load on enter view.
**** having html 5 native autocomplete with <datalist> tag
just server side rendering it with all country names is yay
**** inserting thymeleaf templates by css selector
https://www.thymeleaf.org/doc/tutorials/3.1/usingthymeleaf.html#appendix-c-markup-selector-syntax
this way i can insert <script> tag from index page, without declaring it as a fragment,
because i'll want is static anyway.
and can share 'dark mode' js code between pages
**** building docker image
First off: using nix docker tools, and sbt assembly to create 'uber jar'
now 'nix build .#countries-page-image' builds an image and symlinks it to ./result
$ docker load < result
loads the image
and it can be started
$ docker image list
$ docker run -d -p 9090:8080 <image-id>
**** deploying to render.com
need to auth the docker cli, then tag an image with my repository name
$ docker login
$ docker tag 141 efim1234/rock-paper-scissors:latest
$ podman push localhost/efim1234/countries-page:latest docker.io/efim1234/countries-page:latest
and now render.com, when creating "new service"
can find "efim1234/countries-page:latest" as public image and use it
**** using browser history
with either server side
HX-Push -> "some-url"
or
hx-push-url="true" in the html side
so that url is put into address bar,
and browser save the body into history
and now my website has forward and backward navigation
only bug - the 'filter by region' for some reason doesn't maintain the selected value
*** Continued development
:PROPERTIES:
:CUSTOM_ID: continued-development
:END:
In future project i'll probably want to lean and use go.
For smaller binaries of the server, using PocketBase as embedded backend functions,
and maybe having a better chances of just doing some real world small projects.
*** Useful resources
:PROPERTIES:
:CUSTOM_ID: useful-resources
:END:
- htmx documentation and examples
https://htmx.org/docs/#introduction
- thymeleaf documentation
https://www.thymeleaf.org/doc/tutorials/3.1/usingthymeleaf.html#introducing-thymeleaf
- TailwindCSS documentation
https://tailwindcss.com/docs/installation
- heroicons: MIT licensed svg icons
https://github.com/tailwindlabs/heroicons
- render.com for providing free hosting for services from docker images

View File

@@ -1,17 +0,0 @@
name := "countries-page"
val toolkitV = "0.1.7"
val toolkit = "org.scala-lang" %% "toolkit" % toolkitV
val toolkitTest = "org.scala-lang" %% "toolkit-test" % toolkitV
val cask = "com.lihaoyi" %% "cask" % "0.9.1"
val mainargs = "com.lihaoyi" %% "mainargs" % "0.5.4"
val requests = "com.lihaoyi" %% "requests" % "0.8.0"
ThisBuild / scalaVersion := "3.2.2"
libraryDependencies ++= Seq(cask, mainargs, requests)
libraryDependencies += toolkit
libraryDependencies += (toolkitTest % Test)
// https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf
libraryDependencies += "org.thymeleaf" % "thymeleaf" % "3.1.2.RELEASE"

View File

@@ -1,37 +0,0 @@
{ pkgs, lib, sbt-derivation }:
let pname = "countries-page";
in rec {
package = sbt-derivation.lib.mkSbtDerivation {
inherit pkgs pname;
# ...and the rest of the arguments
version = "0.0.1";
src = pkgs.nix-gitignore.gitignoreSource [ ] ./.;
nativeBuildInputs = [ pkgs.nodePackages.tailwindcss ];
buildPhase = ''
tailwindcss -i ./src/input.css -o ./src/main/resources/public/output.css
sbt assembly
'';
installPhase = ''
mkdir -p $out/bin
cp target/scala-*/${pname}-assembly-*.jar $out/bin/${pname}.jar
'';
depsSha256 = "sha256-PZYt1xvT8BKkFedA8nQvjvuE6JtmxNh0aSManAe4DpY=";
};
image = pkgs.dockerTools.buildLayeredImage {
name = pname;
tag = "latest";
created = "now";
config = {
Cmd = [
"${pkgs.jdk}/bin/java"
"-jar"
"${package}/bin/${pname}.jar"
"--host"
"0.0.0.0"
];
ExposedPorts = { "8080/tcp" = { }; };
};
};
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 203 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 216 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 194 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 83 KiB

Some files were not shown because too many files have changed in this diff Show More