19 Commits
Author SHA1 Message Date
Daniel-Garmig 5676262692 Generate Nightly Build - 202405131816
Publish_on_Tag / Build and Push (push) Successful in 3m24s
2024-05-13 18:16:20 +02:00
Daniel-Garmig d3358c7c58 Fix Actions - Change image repository for push.
CI / Docker Lint (push) Successful in 31s
2024-05-13 01:18:26 +02:00
Daniel-Garmig 4e825c7ca7 Small fix pass.
CI / Docker Lint (push) Successful in 28s
2024-05-13 00:49:54 +02:00
Daniel-Garmig b83af1b872 Copy "/public" to image on prod build. 2024-05-13 00:37:57 +02:00
Daniel-Garmig f8365e05af Env Vars - Support for container env vars.
CI / Docker Lint (push) Successful in 29s
Now you can configure your container using Environmet vars.
2024-05-12 13:21:28 +02:00
Daniel-Garmig 0039b09d98 Gitea Actions support (#1)
Add Gitea Actions support.

Reviewed-on: #1
Co-authored-by: Daniel García <[email protected]>
Co-committed-by: Daniel García <[email protected]>
2024-05-12 02:33:16 +02:00
Daniel-Garmig e9b67efd46 Fix build error. 2024-05-11 23:05:45 +02:00
Daniel-Garmig 0047099742 Booking lifecycle:
- Create bookings :)
2024-05-10 20:04:37 +02:00
Daniel-Garmig c753d1e9fa Add routes & navigation. 2024-05-09 22:45:34 +02:00
Daniel-Garmig fe7122b107 Booking process - Add and remove rooms from booking. 2024-05-09 21:47:12 +02:00
Daniel-Garmig 630d5cb708 State Management & RoomPrices
- Added zustand for global state management.
- New Component - NumberSelector.
- Implement Prices API.
2024-05-09 18:32:18 +02:00
Daniel-Garmig d6a9ac8d7c Search Page - Initial Implementation.
- Added components.
- Query API to get availability for selected period.
2024-05-05 22:45:15 +02:00
Daniel-Garmig e81660914f Homepage - Initial implementation. 2024-05-05 12:45:59 +02:00
Daniel-Garmig 391f2fb3ae Basic components and migration to Shadcn/ui. 2024-05-03 23:47:25 +02:00
Daniel-Garmig a20bee63f7 Added basic components from Shadcn/ui. 2024-05-02 22:50:09 +02:00
Daniel-Garmig 7c3959f07d Install and configure libs:
- TailwindCSS + postcss
- Shadcn/ui
2024-05-02 22:16:13 +02:00
Daniel-Garmig e0e64d039a React Router - Initial setup 2024-04-27 01:08:53 +02:00
Daniel-Garmig 4ab9f3669d Docker support. 2024-04-23 13:34:58 +02:00
Daniel-Garmig f366c2366a Initial Project Setup. 2024-04-23 12:12:08 +02:00
76 changed files with 10720 additions and 1 deletions
+6
View File
@@ -0,0 +1,6 @@
node_modules
build
.dockerignore
Dockerfile
.env
.env.local
+3
View File
@@ -0,0 +1,3 @@
# App config Variables (Will be visible by client):
VITE_BACKEND_HOST=https://somniaapi.example.org/
VITE_BACKEND_PORT=443
+3
View File
@@ -0,0 +1,3 @@
# App config Variables (Will be visible by client):
VITE_BACKEND_HOST=SOMNIAROOMS_BACKEND_HOST
VITE_BACKEND_PORT=SOMNIAROOMS_BACKEND_PORT
+18
View File
@@ -0,0 +1,18 @@
module.exports = {
root: true,
env: { browser: true, es2020: true, node: false },
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react-hooks/recommended',
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parser: '@typescript-eslint/parser',
plugins: ['react-refresh'],
rules: {
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
}
+23
View File
@@ -0,0 +1,23 @@
name: CI
on:
push:
branches:
- main
pull_request: ~
workflow_dispatch: ~
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
lint:
name: Docker Lint
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Lint Dockerfile
uses: hadolint/[email protected]
+45
View File
@@ -0,0 +1,45 @@
name: Publish_on_Tag
on:
push:
tags:
- devbuild_*
workflow_dispatch: ~
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
jobs:
build:
name: Build and Push
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
with:
platforms: arm64
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to local registry
uses: docker/login-action@v3
with:
registry: ${{vars.REGISTRY_INSTANCE}}
username: ${{gitea.repository_owner}}
password: ${{secrets.REGISTRY_TOKEN}} # It should be a user/org token with package perms.
- name: Build and push
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ${{vars.REGISTRY_INSTANCE}}/somnia/somniaroomsapp:devbuild
target: final-prod
platforms: linux/amd64,linux/arm64
secrets: |
GIT_AUTH_TOKEN=${{secrets.REGISTRY_TOKEN}}
+42
View File
@@ -0,0 +1,42 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
# Dependency directories
node_modules/
jspm_packages/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
# Runtime data
pids
*.pid
*.seed
*.pid.lock
Binary file not shown.
+6
View File
@@ -0,0 +1,6 @@
{
"ExpandedNodes": [
""
],
"PreviewInSolutionExplorer": false
}
BIN
View File
Binary file not shown.
+26
View File
@@ -0,0 +1,26 @@
# Base Node Environment.
FROM node:21.7-alpine3.19 as app-base
WORKDIR /app
ENV PATH /app/node_modules/.bin:$PATH
COPY package.json ./
COPY package-lock.json ./
COPY . ./
# Dev environment.
FROM app-base as final-dev
RUN npm install
ENV CHOKIDAR_USEPOLLING=true
CMD ["npm", "run", "dev"]
# Build app for production.
FROM app-base as builder
RUN npm ci && npm run build
# production environment
FROM nginx:stable-alpine as final-prod
COPY --from=builder /app/dist /usr/share/nginx/html
COPY /public /usr/share/nginx/html/public
COPY scripts/env.sh /docker-entrypoint.d/env.sh
EXPOSE 80
RUN chmod +x /docker-entrypoint.d/env.sh
CMD ["nginx", "-g", "daemon off;"]
+58 -1
View File
@@ -1,3 +1,60 @@
# SomniaRoomsApp # SomniaRoomsApp
Somnia Rooms - User App User app for SomniaRooms.
## Docker Usage:
### Dev
**Build Image:**
```
docker build -t somniarooms-app:dev --target final-dev .
```
**Docker Run Image:**
```
docker run -d -it --rm -v ${PWD}:/app -v /app/node_modules -p 3000:3000 --name somniarooms-app somniarooms-app:dev
```
Notas:
- Usar `-rm` para eliminar el contenedor y sus volúmenes en stop.
- Usar `-d` para modo detached.
### Prod:
**Build Image**
```
docker build -t somniarooms-app:prod --target final-prod .
```
**Docker Run**
```
docker run -d -it -p 8080:80 --name somniarooms-app somniarooms-app:prod
```
**Docker run with env vars:**
```
docker run -d -it -p 8080:80 --name somniarooms-app -e SOMNIAROOMS_BACKEND_HOST=https://somniaapi.example.org/ -e SOMNIAROOMS_BACKEND_PORT=443 somniarooms-app:prod
```
## Env Vars.
As this is distributed as a docker image ready to use, you must set some env variables to configure the app:
| Var | Default Value | Description |
| :------------------------: | :----------------------------: | :------------------------------------------------------------------------------------------: |
| `SOMNIAROOMS_BACKEND_HOST` | https://somniaapi.example.org/ | Host where uses can connect to the SomniaRoom API. API endpoint should be reachble for uses. |
| `SOMNIAROOMS_BACKEND_PORT` | 443 | Port to SomniarRooms API. |
## .env files
This project uses .env files to configure the app. As Vite only supports compile-time vars, we use some tricks to allow setting variables from container env variables.
### .env
Contains default values. It is just an example configuration.
For development is recomended to create a `.env.local` file based on `.env`.
### .env.production
Set varibles to certains placeholder, that are replace on container startup.
(We are using this solution: https://stackoverflow.com/a/77454537)
+18
View File
@@ -0,0 +1,18 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "tailwind.config.js",
"css": "src/index.css",
"baseColor": "stone",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "src/components/ui"
}
}
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/SR2.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+5085
View File
File diff suppressed because it is too large Load Diff
+53
View File
@@ -0,0 +1,53 @@
{
"name": "somniarooms",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
"dependencies": {
"@radix-ui/react-checkbox": "^1.0.4",
"@radix-ui/react-dropdown-menu": "^2.0.6",
"@radix-ui/react-icons": "^1.3.0",
"@radix-ui/react-label": "^2.0.2",
"@radix-ui/react-popover": "^1.0.7",
"@radix-ui/react-separator": "^1.0.3",
"@radix-ui/react-slot": "^1.0.2",
"@radix-ui/react-toast": "^1.1.5",
"@radix-ui/react-tooltip": "^1.0.7",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"date-fns": "^3.6.0",
"embla-carousel-react": "^8.0.2",
"lucide-react": "^0.378.0",
"react": "^18.2.0",
"react-day-picker": "^8.10.1",
"react-dom": "^18.2.0",
"react-router-dom": "^6.23.0",
"swr": "^2.2.5",
"tailwind-merge": "^2.3.0",
"zustand": "^4.5.2"
},
"devDependencies": {
"@types/node": "^20.12.8",
"@types/react": "^18.2.66",
"@types/react-dom": "^18.2.22",
"@types/react-router-dom": "^5.3.3",
"@typescript-eslint/eslint-plugin": "^7.2.0",
"@typescript-eslint/parser": "^7.2.0",
"@vitejs/plugin-react-swc": "^3.5.0",
"autoprefixer": "^10.4.19",
"eslint": "^8.57.0",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.6",
"postcss": "^8.4.38",
"tailwindcss": "^3.4.3",
"tailwindcss-animate": "^1.0.7",
"typescript": "^5.2.2",
"vite": "^5.2.0"
}
}
+6
View File
@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
+2121
View File
File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 96 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
for i in $(env | grep SOMNIAROOMS_)
do
key=$(echo $i | cut -d '=' -f 1)
value=$(echo $i | cut -d '=' -f 2-)
echo $key=$value
# sed All files
# find /usr/share/nginx/html -type f -exec sed -i "s|${key}|${value}|g" '{}' +
# sed JS and CSS only
find /usr/share/nginx/html -type f \( -name '*.js' -o -name '*.css' \) -exec sed -i "s|${key}|${value}|g" '{}' +
done
+19
View File
@@ -0,0 +1,19 @@
import { NewBooking, NewBookingResponse } from "@/model/Bookings";
import { fetcherWithFilter } from "./backend";
export async function APISendCreateBooking(bookingData: NewBooking | null) {
if (!bookingData) {
return {
bookingResponse: null,
isError: true
}
}
const rs = await fetcherWithFilter<NewBookingResponse>("/api/booking/create", bookingData);
return {
bookingResponse: rs,
isError: false
}
}
+25
View File
@@ -0,0 +1,25 @@
import { RoomCategory } from "@/model/RoomCategory";
import { fetcher, fetcherUnwraper } from "./backend";
import useSWR from 'swr';
export function useAPIRoomCategories() {
const { data, error, isLoading } = useSWR<RoomCategory[]>('/api/room/category', fetcherUnwraper)
return {
roomCategoryList: data,
isLoading,
isError: error
}
}
export function useAPIRoomCategoryId(categoryId: number) {
const url = categoryId ? '/api/room/category/' + categoryId : null;
const { data, error, isLoading } = useSWR<RoomCategory>(url, fetcher)
return {
roomCategory: data,
isLoading,
isError: error
}
}
+33
View File
@@ -0,0 +1,33 @@
import { fetcherUnwraperWithFilter } from "./backend";
import useSWR from 'swr';
import { AvailabilityFilter, AvailabilityRequest, FareFilter, FareRequest, RoomAvailabity, RoomPrice } from "@/model/RoomSearch";
export function useAPIRoomAvailability(filter: AvailabilityFilter | null) {
const request: AvailabilityRequest | null = filter ? {
filter: filter
} : null;
const { data, isLoading, error } = useSWR(request ? ['/api/search/availability', request] : null, ([url, request]) => fetcherUnwraperWithFilter<RoomAvailabity[]>(url, request))
return {
roomAvailabilityList: data,
isLoading,
isError: error
}
}
export function useAPIRoomPrices(filter: FareFilter | null) {
const request: FareRequest | null = filter ? {
filter: filter
} : null;
const { data, isLoading, error } = useSWR(request ? ['/api/search/fares', request] : null, ([url, request]) => fetcherUnwraperWithFilter<RoomPrice[]>(url, request))
return {
roomPriceList: data,
isLoading,
isError: error
}
}
+66
View File
@@ -0,0 +1,66 @@
const BACKEND_HOST = import.meta.env.VITE_BACKEND_HOST;
const BACKEND_PORT = import.meta.env.VITE_BACKEND_PORT;
const url = BACKEND_HOST + (BACKEND_PORT == 443 || BACKEND_PORT == 80 ? "" : ":" + BACKEND_PORT)
export function fetcher<T>(endpoint: string): Promise<T> {
return fetch(url + endpoint, {
method: "GET"
})
.then(r => {
if (!r.ok) {
throw new Error(r.statusText)
}
const data = r.json();
return data as Promise<T>;
})
}
export function fetcherUnwraper<T>(endpoint: string): Promise<T> {
return fetch(url + endpoint)
.then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json() as Promise<{ results: T }>
})
.then(data => {
return data.results
})
}
export function fetcherWithFilter<T>(endpoint: string, body: NonNullable<unknown>): Promise<T> {
return fetch(url + endpoint, {
method: "POST",
body: JSON.stringify(body),
headers: {
"Content-Type": "application/json",
},
})
.then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json() as Promise<T>
})
}
export function fetcherUnwraperWithFilter<T>(endpoint: string, body: NonNullable<unknown>): Promise<T> {
return fetch(url + endpoint, {
method: "POST",
body: JSON.stringify(body),
headers: {
"Content-Type": "application/json",
},
})
.then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json() as Promise<{ results: T }>
})
.then(data => {
return data.results
})
}
+144
View File
@@ -0,0 +1,144 @@
import { useAPIRoomCategoryId } from "@/api/api-roomCategories"
import { Card, CardContent, CardHeader } from "../ui/card"
import { useMemo, useState } from "react";
import { Typography } from "../ui/typography";
import { RoomCategoryPhoto } from "@/model/RoomCategory";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../ui/table";
import { Skeleton } from "../ui/skeleton";
import { useAppStore } from "@/store";
import { DateRange } from "react-day-picker";
import { FareFilter } from "@/model/RoomSearch";
import { useAPIRoomPrices } from "@/api/api-roomSearch";
import { NumberSelector } from "../ui/number-selector";
import { NewBookingRoom } from "@/model/Bookings";
function RoomBooking({ roomCategoryId, availableAmount }: { roomCategoryId: number, availableAmount: number }) {
const [selectedAmount, setSelectedAmount] = useState<Map<number, number>>(new Map());
const currentDates: DateRange = useAppStore((state) => (state.searchFilter.dateRange));
const addNewRoom = useAppStore((state) => (state.addNewBookingRoom));
function onSelectedAmountUpdate(guestNumber: number, newCount: number, price: number) {
console.log("Room " + roomCategoryId + " Guestnumber: " + guestNumber + " Count: " + newCount);
const newAmountMap = new Map(selectedAmount);
newAmountMap.set(guestNumber, newCount);
setSelectedAmount(newAmountMap)
const newRoom: NewBookingRoom = {
roomCategory: roomCategoryId,
guestNumber: guestNumber,
amount: newCount,
price: price
};
addNewRoom(newRoom);
}
const totalSelected = () => {
let sum = 0;
selectedAmount.forEach((v) => sum += v)
return sum;
};
const canAddMore: boolean = availableAmount > totalSelected();
//This seems a little bit overkill, but IDK.
const fareFilter: FareFilter | null = useMemo(
() => {
if (currentDates && currentDates.from && currentDates.to) {
const filter: FareFilter = {
startDate: currentDates.from?.toDateString(),
endDate: currentDates.to?.toDateString(),
roomCategory: roomCategoryId
}
return filter;
}
return null;
},
[currentDates, roomCategoryId]
);
const { roomCategory, isLoading: isLoadingCategory, isError: isErrorCategory } = useAPIRoomCategoryId(roomCategoryId);
const { roomPriceList, isLoading: isLoadingPrices, isError: isErrorPrices } = useAPIRoomPrices(fareFilter);
//TODOME: Gestionar también los estados al cargar los precios.
const isLoading = isLoadingCategory || isLoadingPrices;
const isError = isErrorCategory || isErrorPrices;
if (isLoading) {
return (
<Skeleton className="w-[600px] h-[150px] mx-auto" />
);
}
if (isError) {
return (
<Typography variant={"h3"} as="h3">Sorry, there was an error loading data.</Typography>
);
}
const mainPhoto: RoomCategoryPhoto | undefined = roomCategory?.roomCategoryPhotos.filter((p) => p.kind == "main")[0];
const photoElement = mainPhoto && (
<img src={mainPhoto.path} alt={mainPhoto.altText} className="rounded-md mx-0 px-0"></img>
);
const hasPrices = roomPriceList != null && roomPriceList?.length > 0;
let priceTable = null;
if (hasPrices) {
const tableRows = roomPriceList?.map((el) => {
return (
<TableRow key={el.guestNumber}>
<TableCell>{el.guestNumber}</TableCell>
<TableCell>{el.price / 100} €</TableCell>
<TableCell>
<NumberSelector updateCount={(count) => onSelectedAmountUpdate(el.guestNumber, count, el.price)} addEnabled={canAddMore}></NumberSelector>
</TableCell>
</TableRow>
);
});
priceTable = (
<>
<Table>
<TableHeader>
<TableRow>
<TableHead>Guest number</TableHead>
<TableHead>Price</TableHead>
<TableHead>Amount</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{isLoadingPrices ? <Skeleton className="w-[80%] h-[100%]" /> : tableRows}
</TableBody>
</Table>
<p>Rooms Available: {availableAmount}</p>
</>
);
}
return (
<Card>
<CardHeader>
<div className="flex flex-row gap-5 w-full">
<div className="w-[40%] flex-none">
{photoElement}
</div>
<div>
<Typography variant={"h3"} as="h3">{roomCategory?.name}</Typography>
<Typography >{roomCategory?.description}</Typography>
</div>
</div>
</CardHeader>
<CardContent>
{hasPrices ? priceTable : <Typography variant={"largeText"}>No Prices available</Typography>}
<div>
</div>
<p>Selected: {totalSelected()}</p>
</CardContent>
</Card>
);
}
export default RoomBooking
+65
View File
@@ -0,0 +1,65 @@
import { Separator } from "../ui/separator"
import { Card, CardContent, CardHeader } from "../ui/card"
import { Typography } from "../ui/typography"
import { BedDoubleIcon, BedSingleIcon, UserIcon } from "lucide-react"
import { RoomCategory, RoomCategoryPhoto } from "@/model/RoomCategory"
import { IconWithTooltipNumber } from "../ui/icon-number-tooltip"
interface RoomItemCardProps {
room: RoomCategory
}
const defaultRoom: RoomCategory = {
id: -1,
name: "Sample Room",
description: "Lorem Ipsum",
bedType: "0,1",
maxGuestNum: 2,
roomCategoryDetails: [],
roomCategoryPhotos: []
}
export function RoomItemCard({ room = defaultRoom }: RoomItemCardProps) {
const mainPhoto: RoomCategoryPhoto | undefined = room.roomCategoryPhotos.find((element) => {
return element.kind = "main"
});
const bedTypeList: number[] = room.bedType.split(",").map((e) => Number.parseInt(e));
const hasSingleBed: boolean = (bedTypeList.at(0) !== undefined && bedTypeList[0] > 0);
const hasDoubleBed: boolean = (bedTypeList.at(1) !== undefined && bedTypeList[1] > 0);
return (
<Card id={room.id.toString()}>
<CardHeader className="p-0 m-0 mb-5">
<img src={mainPhoto?.path ?? "https://images.unsplash.com/photo-1618773928121-c32242e63f39"} className="rounded-md"></img>
<Typography variant={"h2"} as="h1" className="mx-5 py-2">{room.name}</Typography>
</CardHeader>
<CardContent>
<Typography variant={"p"} as="p">
{room.description}
</Typography>
<Separator className="my-4" />
<div className="flex justify-around">
<div className="flex flex-row gap-2">
{hasSingleBed && (
<IconWithTooltipNumber altText="Single bed" amount={bedTypeList[0]}>
<BedSingleIcon />
</IconWithTooltipNumber>
)}
{hasDoubleBed && (
<>
<IconWithTooltipNumber altText="Double bed" amount={bedTypeList[1]}>
<BedDoubleIcon />
</IconWithTooltipNumber>
</>
)}
</div>
<div className="flex flex-row">
<UserIcon />
<Typography variant={"p_inline"} className="ml-3">{room.maxGuestNum}</Typography>
</div>
</div>
</CardContent>
</Card>
)
}
+101
View File
@@ -0,0 +1,101 @@
import { Separator } from "../ui/separator"
import { Card, CardContent, CardHeader } from "../ui/card"
import { Typography } from "../ui/typography"
import 'react-day-picker/dist/style.css';
import { DatePickerWithRange } from "../ui/dateRange-picker";
import { Button } from "../ui/button";
import { SearchIcon } from "lucide-react";
import { useEffect, useState } from "react";
import { SearchFilter } from "@/model/SearchFilter";
import { DateRange } from "react-day-picker";
import { useToast } from "../ui/use-toast";
import { useAppStore } from "@/store";
import { useLocation } from "react-router-dom";
type funOnSearchClick = (newFilter: SearchFilter) => void;
export function SearchFilterCard({ onSearchClick }: { onSearchClick?: funOnSearchClick }) {
//App filter. Updated on btSearchClick.
const appSearchFilter = useAppStore((state) => (state.searchFilter));
const setAppSearchFilter = useAppStore((state) => (state.setSearchFilter));
//Local Filter state.
const [searchFilter, setSearchFilter] = useState<SearchFilter>(appSearchFilter)
//On location change, try to load searchFilter from state.
//FIXME: Si llegamos sin state, hay que borrar el state global...
const location = useLocation();
useEffect(() => {
setSearchFilter(location.state);
}, [location]);
const { toast } = useToast();
// Validate and call callback on btSearch click.
//TODOME: Add data validations and show messages.
const btSearchClick = () => {
if (!searchFilter || !searchFilter.dateRange) {
toast({
variant: "destructive",
title: "Uh oh! Invalid Search.",
});
return;
}
if (!searchFilter.dateRange.from || !searchFilter.dateRange.to) {
toast({
variant: "destructive",
title: "Uh oh! Invalid Search.",
description: "You should select a 'from' and 'to' dates"
})
return;
}
if (onSearchClick) {
setAppSearchFilter(searchFilter);
onSearchClick(searchFilter);
}
}
// Handle Element updates.
const updateDateRange = (newRange: DateRange) => {
setSearchFilter({
...searchFilter,
dateRange: newRange,
});
console.log("SearchFilterCard filter UPDATED");
}
const datePickerElement = searchFilter == null ? (
<DatePickerWithRange
updateDateRange={updateDateRange}
allowPast={false}>
</DatePickerWithRange>
) : (
<DatePickerWithRange
updateDateRange={updateDateRange}
allowPast={false}
startDate={searchFilter.dateRange.from}
endDate={searchFilter.dateRange.to}>
</DatePickerWithRange>
);
return (
<Card>
<CardHeader className="p-0 m-0 mb-5">
<Typography variant={"h2"} as="h1" className="mx-5 py-2">Reserva ahora</Typography>
</CardHeader>
<CardContent>
{datePickerElement}
<Separator className="my-4" />
<Button size={"lg"} onClick={btSearchClick}>
<SearchIcon className="text-primary-foreground me-2" />
<Typography variant={"h3"} className="text-primary-foreground">Buscar</Typography>
</Button>
</CardContent>
</Card>
)
}
+21
View File
@@ -0,0 +1,21 @@
function AppFooter() {
return (
<div className="bg-secondary flex-col hidden">
<div className="">
Created with Love by me :)
</div>
<div className="">
<p>Más información</p>
<ul className="list-outside">
<li>Info</li>
<li>Info2</li>
<li>Info3</li>
</ul>
</div>
</div>
)
}
export default AppFooter
+32
View File
@@ -0,0 +1,32 @@
import { ModeToggle } from "./mode-toggle"
import { Button } from "./ui/button"
import { Card, CardContent } from "./ui/card"
import { Typography } from "./ui/typography"
import { Link } from "react-router-dom"
import { BookAIcon, HomeIcon } from "lucide-react"
function AppHeader() {
return (
<Card className="flex items-center mx-10 my-4">
<CardContent className="w-full py-2">
<div className="flex justify-around items-center">
<div className="flex flex-row items-center gap-2 relative">
<img src="public/SR2.svg" className="w-[64px]"></img>
<Typography variant={"largeText"}>Somnia Rooms</Typography>
<a href="https://duck.com" className="absolute w-[100%] h-[100%]"></a>
</div>
<Button variant="ghost" className="h-15">
<Link to={`home`}><HomeIcon className="mx-auto" />Home</Link>
</Button>
<Button variant="ghost" className="h-15">
<Link to={`search`}><BookAIcon className="mx-auto" />Reservar</Link>
</Button>
<ModeToggle />
</div>
</CardContent>
</Card>
)
}
export default AppHeader
@@ -0,0 +1,19 @@
function BackendConnectionStatus({ isLoading, isError }: { isLoading?: boolean, isError?: boolean }) {
const BACKEND_HOST = import.meta.env.VITE_BACKEND_HOST;
const BACKEND_PORT = import.meta.env.VITE_BACKEND_PORT;
return (
<div>
<p>
Conected to Back-End at: {BACKEND_HOST} - {BACKEND_PORT}
</p>
<p>
Conection Status: {isError ? "ERROR" : (isLoading ? "LOADING" : "LOADED")}
</p>
</div>
)
}
export default BackendConnectionStatus
@@ -0,0 +1,95 @@
import { useAppStore } from "@/store"
import { Card, CardContent, CardHeader } from "../ui/card"
import { Typography } from "../ui/typography"
import { differenceInDays } from "date-fns";
import { Separator } from "../ui/separator";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../ui/table";
import { Button } from "../ui/button";
type OnBookingClickFunction = () => void;
type BookingDetailsModes = "Book" | "View"
export function BookingDetails({ onBookingConfirm, mode }: { onBookingConfirm?: OnBookingClickFunction, mode: BookingDetailsModes }) {
const bookingData = useAppStore((state) => state.newBookingData);
const onBtBookingClick = () => {
if (onBookingConfirm) {
onBookingConfirm();
}
}
if (!bookingData || bookingData.rooms.length <= 0) {
return (
<Card>
<CardHeader>
<Typography variant={"h2"} as="h2">Your Booking</Typography>
</CardHeader>
<CardContent>
<Typography variant={"h3"}>No rooms added yet</Typography>
</CardContent>
</Card>
);
}
const roomList = bookingData.rooms.map((room) => {
return (
<TableRow key={room.roomCategory + "_" + room.guestNumber}>
<TableCell>{room.roomCategory}</TableCell>
<TableCell>{room.guestNumber}</TableCell>
<TableCell>{room.amount}</TableCell>
<TableCell>{room.price / 100} €</TableCell>
<TableCell>{(room.price * room.amount) / 100} €</TableCell>
</TableRow>
);
})
const roomTable = (
<Table>
<TableHeader>
<TableRow>
<TableHead>Room</TableHead>
<TableHead>Guests</TableHead>
<TableHead>Quantity</TableHead>
<TableHead>Unit price</TableHead>
<TableHead>Total price</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{roomList}
</TableBody>
</Table>
);
const totalPrice = bookingData.rooms.reduce((acc, room) => (acc + (room.price * room.amount)), 0);
return (
<Card>
<CardHeader>
<Typography variant={"h2"} as="h2">Your Booking</Typography>
</CardHeader>
<CardContent>
<Typography variant={"h3"}>Your Dates</Typography>
<Typography variant={"largeText"}>
Arrival: {bookingData.arrivalDate.toLocaleDateString()} -
Departure: {bookingData.departureDate.toLocaleDateString()} <br></br>
Number of nights: {differenceInDays(bookingData.departureDate, bookingData.arrivalDate)}
</Typography>
<Separator className="my-2"></Separator>
<Typography variant={"h3"}>Your Rooms</Typography>
{roomTable}
<Separator className="my-2"></Separator>
<Typography variant={"h3"}>Total Price</Typography>
<Typography variant={"h3"}>{totalPrice / 100} €</Typography>
{
mode == "Book" &&
<Button className="my-2" onClick={onBtBookingClick}>
<Typography variant={"largeText"} className="text-primary-foreground">Book it!</Typography>
</Button>
}
</CardContent>
</Card>
)
}
+37
View File
@@ -0,0 +1,37 @@
import { MoonIcon, SunIcon } from "@radix-ui/react-icons"
import { Button } from "@/components/ui/button"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { useTheme } from "@/components/theme-provider"
export function ModeToggle() {
const { setTheme } = useTheme()
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="icon">
<SunIcon className="h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
<MoonIcon className="absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
<span className="sr-only">Toggle theme</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => setTheme("light")}>
Light
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("dark")}>
Dark
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("system")}>
System
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
}
+74
View File
@@ -0,0 +1,74 @@
import { createContext, useContext, useEffect, useState } from "react"
type Theme = "dark" | "light" | "system"
type ThemeProviderProps = {
children: React.ReactNode
defaultTheme?: Theme
storageKey?: string
}
type ThemeProviderState = {
theme: Theme
setTheme: (theme: Theme) => void
}
const initialState: ThemeProviderState = {
theme: "system",
setTheme: () => null,
}
const ThemeProviderContext = createContext<ThemeProviderState>(initialState)
export function ThemeProvider({
children,
defaultTheme = "system",
storageKey = "vite-ui-theme",
...props
}: ThemeProviderProps) {
const [theme, setTheme] = useState<Theme>(
() => (localStorage.getItem(storageKey) as Theme) || defaultTheme
)
useEffect(() => {
const root = window.document.documentElement
root.classList.remove("light", "dark")
if (theme === "system") {
const systemTheme = window.matchMedia("(prefers-color-scheme: dark)")
.matches
? "dark"
: "light"
root.classList.add(systemTheme)
return
}
root.classList.add(theme)
}, [theme])
const value = {
theme,
setTheme: (theme: Theme) => {
localStorage.setItem(storageKey, theme)
setTheme(theme)
},
}
return (
<ThemeProviderContext.Provider {...props} value={value}>
{children}
</ThemeProviderContext.Provider>
)
}
// eslint-disable-next-line react-refresh/only-export-components
export const useTheme = () => {
const context = useContext(ThemeProviderContext)
if (context === undefined)
throw new Error("useTheme must be used within a ThemeProvider")
return context
}
+36
View File
@@ -0,0 +1,36 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
)
}
export { Badge, badgeVariants }
+57
View File
@@ -0,0 +1,57 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",
{
variants: {
variant: {
default:
"bg-primary text-primary-foreground shadow hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
outline:
"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2",
sm: "h-8 rounded-md px-3 text-xs",
lg: "h-10 rounded-md px-8",
icon: "h-9 w-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = "Button"
export { Button, buttonVariants }
+70
View File
@@ -0,0 +1,70 @@
import * as React from "react"
import { ChevronLeftIcon, ChevronRightIcon } from "@radix-ui/react-icons"
import { DayPicker } from "react-day-picker"
import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button"
export type CalendarProps = React.ComponentProps<typeof DayPicker>
function Calendar({
className,
classNames,
showOutsideDays = true,
...props
}: CalendarProps) {
return (
<DayPicker
showOutsideDays={showOutsideDays}
className={cn("p-3", className)}
classNames={{
months: "flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",
month: "space-y-4",
caption: "flex justify-center pt-1 relative items-center",
caption_label: "text-sm font-medium",
nav: "space-x-1 flex items-center",
nav_button: cn(
buttonVariants({ variant: "outline" }),
"h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"
),
nav_button_previous: "absolute left-1",
nav_button_next: "absolute right-1",
table: "w-full border-collapse space-y-1",
head_row: "flex",
head_cell:
"text-muted-foreground rounded-md w-8 font-normal text-[0.8rem]",
row: "flex w-full mt-2",
cell: cn(
"relative p-0 text-center text-sm focus-within:relative focus-within:z-20 [&:has([aria-selected])]:bg-accent [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected].day-range-end)]:rounded-r-md",
props.mode === "range"
? "[&:has(>.day-range-end)]:rounded-r-md [&:has(>.day-range-start)]:rounded-l-md first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md"
: "[&:has([aria-selected])]:rounded-md"
),
day: cn(
buttonVariants({ variant: "ghost" }),
"h-8 w-8 p-0 font-normal aria-selected:opacity-100"
),
day_range_start: "day-range-start",
day_range_end: "day-range-end",
day_selected:
"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",
day_today: "bg-accent text-accent-foreground",
day_outside:
"day-outside text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30",
day_disabled: "text-muted-foreground opacity-50",
day_range_middle:
"aria-selected:bg-accent aria-selected:text-accent-foreground",
day_hidden: "invisible",
...classNames,
}}
components={{
IconLeft: () => <ChevronLeftIcon className="h-4 w-4" />,
IconRight: () => <ChevronRightIcon className="h-4 w-4" />,
}}
{...props}
/>
)
}
Calendar.displayName = "Calendar"
export { Calendar }
+76
View File
@@ -0,0 +1,76 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"rounded-xl border bg-card text-card-foreground shadow",
className
)}
{...props}
/>
))
Card.displayName = "Card"
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
))
CardHeader.displayName = "CardHeader"
const CardTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h3
ref={ref}
className={cn("font-semibold leading-none tracking-tight", className)}
{...props}
/>
))
CardTitle.displayName = "CardTitle"
const CardDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<p
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
CardDescription.displayName = "CardDescription"
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
))
CardContent.displayName = "CardContent"
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
))
CardFooter.displayName = "CardFooter"
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
+260
View File
@@ -0,0 +1,260 @@
import * as React from "react"
import { ArrowLeftIcon, ArrowRightIcon } from "@radix-ui/react-icons"
import useEmblaCarousel, {
type UseEmblaCarouselType,
} from "embla-carousel-react"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
type CarouselApi = UseEmblaCarouselType[1]
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>
type CarouselOptions = UseCarouselParameters[0]
type CarouselPlugin = UseCarouselParameters[1]
type CarouselProps = {
opts?: CarouselOptions
plugins?: CarouselPlugin
orientation?: "horizontal" | "vertical"
setApi?: (api: CarouselApi) => void
}
type CarouselContextProps = {
carouselRef: ReturnType<typeof useEmblaCarousel>[0]
api: ReturnType<typeof useEmblaCarousel>[1]
scrollPrev: () => void
scrollNext: () => void
canScrollPrev: boolean
canScrollNext: boolean
} & CarouselProps
const CarouselContext = React.createContext<CarouselContextProps | null>(null)
function useCarousel() {
const context = React.useContext(CarouselContext)
if (!context) {
throw new Error("useCarousel must be used within a <Carousel />")
}
return context
}
const Carousel = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & CarouselProps
>(
(
{
orientation = "horizontal",
opts,
setApi,
plugins,
className,
children,
...props
},
ref
) => {
const [carouselRef, api] = useEmblaCarousel(
{
...opts,
axis: orientation === "horizontal" ? "x" : "y",
},
plugins
)
const [canScrollPrev, setCanScrollPrev] = React.useState(false)
const [canScrollNext, setCanScrollNext] = React.useState(false)
const onSelect = React.useCallback((api: CarouselApi) => {
if (!api) {
return
}
setCanScrollPrev(api.canScrollPrev())
setCanScrollNext(api.canScrollNext())
}, [])
const scrollPrev = React.useCallback(() => {
api?.scrollPrev()
}, [api])
const scrollNext = React.useCallback(() => {
api?.scrollNext()
}, [api])
const handleKeyDown = React.useCallback(
(event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.key === "ArrowLeft") {
event.preventDefault()
scrollPrev()
} else if (event.key === "ArrowRight") {
event.preventDefault()
scrollNext()
}
},
[scrollPrev, scrollNext]
)
React.useEffect(() => {
if (!api || !setApi) {
return
}
setApi(api)
}, [api, setApi])
React.useEffect(() => {
if (!api) {
return
}
onSelect(api)
api.on("reInit", onSelect)
api.on("select", onSelect)
return () => {
api?.off("select", onSelect)
}
}, [api, onSelect])
return (
<CarouselContext.Provider
value={{
carouselRef,
api: api,
opts,
orientation:
orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
scrollPrev,
scrollNext,
canScrollPrev,
canScrollNext,
}}
>
<div
ref={ref}
onKeyDownCapture={handleKeyDown}
className={cn("relative", className)}
role="region"
aria-roledescription="carousel"
{...props}
>
{children}
</div>
</CarouselContext.Provider>
)
}
)
Carousel.displayName = "Carousel"
const CarouselContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const { carouselRef, orientation } = useCarousel()
return (
<div ref={carouselRef} className="overflow-hidden">
<div
ref={ref}
className={cn(
"flex",
orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
className
)}
{...props}
/>
</div>
)
})
CarouselContent.displayName = "CarouselContent"
const CarouselItem = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const { orientation } = useCarousel()
return (
<div
ref={ref}
role="group"
aria-roledescription="slide"
className={cn(
"min-w-0 shrink-0 grow-0 basis-full",
orientation === "horizontal" ? "pl-4" : "pt-4",
className
)}
{...props}
/>
)
})
CarouselItem.displayName = "CarouselItem"
const CarouselPrevious = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<typeof Button>
>(({ className, variant = "outline", size = "icon", ...props }, ref) => {
const { orientation, scrollPrev, canScrollPrev } = useCarousel()
return (
<Button
ref={ref}
variant={variant}
size={size}
className={cn(
"absolute h-8 w-8 rounded-full",
orientation === "horizontal"
? "-left-12 top-1/2 -translate-y-1/2"
: "-top-12 left-1/2 -translate-x-1/2 rotate-90",
className
)}
disabled={!canScrollPrev}
onClick={scrollPrev}
{...props}
>
<ArrowLeftIcon className="h-4 w-4" />
<span className="sr-only">Previous slide</span>
</Button>
)
})
CarouselPrevious.displayName = "CarouselPrevious"
const CarouselNext = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<typeof Button>
>(({ className, variant = "outline", size = "icon", ...props }, ref) => {
const { orientation, scrollNext, canScrollNext } = useCarousel()
return (
<Button
ref={ref}
variant={variant}
size={size}
className={cn(
"absolute h-8 w-8 rounded-full",
orientation === "horizontal"
? "-right-12 top-1/2 -translate-y-1/2"
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
className
)}
disabled={!canScrollNext}
onClick={scrollNext}
{...props}
>
<ArrowRightIcon className="h-4 w-4" />
<span className="sr-only">Next slide</span>
</Button>
)
})
CarouselNext.displayName = "CarouselNext"
export {
type CarouselApi,
Carousel,
CarouselContent,
CarouselItem,
CarouselPrevious,
CarouselNext,
}
+28
View File
@@ -0,0 +1,28 @@
import * as React from "react"
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
import { CheckIcon } from "@radix-ui/react-icons"
import { cn } from "@/lib/utils"
const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, ...props }, ref) => (
<CheckboxPrimitive.Root
ref={ref}
className={cn(
"peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
className
)}
{...props}
>
<CheckboxPrimitive.Indicator
className={cn("flex items-center justify-center text-current")}
>
<CheckIcon className="h-4 w-4" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
))
Checkbox.displayName = CheckboxPrimitive.Root.displayName
export { Checkbox }
+138
View File
@@ -0,0 +1,138 @@
"use client"
import * as React from "react"
import { CalendarIcon } from "@radix-ui/react-icons"
import { format } from "date-fns"
import { ActiveModifiers, DateBefore, DateRange, Matcher } from "react-day-picker"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Calendar } from "@/components/ui/calendar"
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover"
import { Typography } from "./typography"
export type UpdateRangeFunction = (newRange: DateRange) => void;
export function DatePickerWithRange({
className, updateDateRange, startDate, endDate, allowPast = true
}: {
className?: React.HTMLAttributes<HTMLDivElement> | undefined, updateDateRange: UpdateRangeFunction | undefined,
startDate?: Date, endDate?: Date, allowPast?: boolean
}) {
// Date Range State.
const [dateRange, setDateRange] = React.useState<DateRange | undefined>({
from: startDate,
to: endDate,
});
//TODOME: Si el día es mods.outside, navegar al mes correspondiente.
// Handle Day change events.
const handleDayClickFrom = (day: Date, mods: ActiveModifiers) => {
const newDateRange: DateRange = {
from: mods.selected ? undefined : day,
to: dateRange?.to
}
setDateRange(newDateRange)
if (updateDateRange !== undefined) {
updateDateRange(newDateRange)
}
}
const handleDayClickTo = (day: Date, mods: ActiveModifiers) => {
const newDateRange: DateRange = {
from: dateRange?.from,
to: mods.selected ? undefined : day
}
setDateRange(newDateRange)
if (updateDateRange !== undefined) {
updateDateRange(newDateRange)
}
}
// Disable days from "To" before "From"
let beforeAndSelected: Matcher[] = [];
if (dateRange?.from) {
const beforeMatcher: DateBefore = { before: dateRange?.from };
const dateMatcher: Matcher = dateRange?.from;
beforeAndSelected = [beforeMatcher, dateMatcher];
}
let pastMatcher: DateBefore | undefined = undefined;
if (!allowPast) {
pastMatcher = { before: new Date() };
}
return (
<div className={cn("grid gap-x-2 grid-cols-2 grid-rows-2", className)}>
<Typography variant={"largeText"} as="p">Desde</Typography>
<Typography variant={"largeText"} as="p">Hasta</Typography>
<Popover>
<PopoverTrigger asChild>
<Button
id="dateFrom"
variant={"outline"}
className={cn(
"justify-start text-left font-normal",
!dateRange && "text-muted-foreground"
)}
>
<CalendarIcon className="mr-2 h-4 w-4" />
{dateRange?.from ? (
format(dateRange.from, "LLL dd, y")
) : (
<span>Pick a date</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
initialFocus
mode="single"
defaultMonth={dateRange?.from}
selected={dateRange?.from}
onDayClick={handleDayClickFrom}
numberOfMonths={1}
disabled={pastMatcher}
/>
</PopoverContent>
</Popover>
<Popover>
<PopoverTrigger asChild>
<Button
id="dateTo"
variant={"outline"}
className={cn(
"justify-start text-left font-normal",
!dateRange && "text-muted-foreground"
)}
>
<CalendarIcon className="mr-2 h-4 w-4" />
{dateRange?.to ? (
format(dateRange.to, "LLL dd, y")
) : (
<span>Pick a date</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
initialFocus
mode="single"
defaultMonth={dateRange?.to}
selected={dateRange?.to}
onDayClick={handleDayClickTo}
numberOfMonths={1}
disabled={beforeAndSelected}
/>
</PopoverContent>
</Popover>
</div>
)
}
+203
View File
@@ -0,0 +1,203 @@
import * as React from "react"
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
import {
CheckIcon,
ChevronRightIcon,
DotFilledIcon,
} from "@radix-ui/react-icons"
import { cn } from "@/lib/utils"
const DropdownMenu = DropdownMenuPrimitive.Root
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger
const DropdownMenuGroup = DropdownMenuPrimitive.Group
const DropdownMenuPortal = DropdownMenuPrimitive.Portal
const DropdownMenuSub = DropdownMenuPrimitive.Sub
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup
const DropdownMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean
}
>(({ className, inset, children, ...props }, ref) => (
<DropdownMenuPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",
inset && "pl-8",
className
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto h-4 w-4" />
</DropdownMenuPrimitive.SubTrigger>
))
DropdownMenuSubTrigger.displayName =
DropdownMenuPrimitive.SubTrigger.displayName
const DropdownMenuSubContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
))
DropdownMenuSubContent.displayName =
DropdownMenuPrimitive.SubContent.displayName
const DropdownMenuContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md",
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
))
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName
const DropdownMenuItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
inset && "pl-8",
className
)}
{...props}
/>
))
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName
const DropdownMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<DropdownMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CheckIcon className="h-4 w-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
))
DropdownMenuCheckboxItem.displayName =
DropdownMenuPrimitive.CheckboxItem.displayName
const DropdownMenuRadioItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<DropdownMenuPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<DotFilledIcon className="h-4 w-4 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
))
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName
const DropdownMenuLabel = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Label
ref={ref}
className={cn(
"px-2 py-1.5 text-sm font-semibold",
inset && "pl-8",
className
)}
{...props}
/>
))
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName
const DropdownMenuSeparator = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
))
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName
const DropdownMenuShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn("ml-auto text-xs tracking-widest opacity-60", className)}
{...props}
/>
)
}
DropdownMenuShortcut.displayName = "DropdownMenuShortcut"
export {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuGroup,
DropdownMenuPortal,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuRadioGroup,
}
+35
View File
@@ -0,0 +1,35 @@
import { Typography } from "./typography";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "./tooltip";
import { PropsWithChildren } from "react";
interface IconWithTooltipNumberProps {
amount?: number | null |undefined,
altText?: string | null | undefined
}
export function IconWithTooltipNumber({ amount = undefined, altText = undefined, children }: PropsWithChildren<IconWithTooltipNumberProps>) {
const iconElement = altText ? (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
{children}
</TooltipTrigger>
<TooltipContent>
<p>{altText}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
) : (
<>
{children}
</>
);
return (
<>
{amount && <Typography variant={"p_inline"}>{amount}</Typography>}
{iconElement}
</>
)
}
+25
View File
@@ -0,0 +1,25 @@
import * as React from "react"
import { cn } from "@/lib/utils"
export interface InputProps
extends React.InputHTMLAttributes<HTMLInputElement> {}
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = "Input"
export { Input }
+24
View File
@@ -0,0 +1,24 @@
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
)
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
))
Label.displayName = LabelPrimitive.Root.displayName
export { Label }
+33
View File
@@ -0,0 +1,33 @@
import { useState } from "react"
import { Button } from "./button";
import { Typography } from "./typography";
export type UpdateSelectedNumberFunction = (newCount: number) => void;
export function NumberSelector(
{ updateCount, addEnabled = true, allowNegative = false }:
{ updateCount: UpdateSelectedNumberFunction, addEnabled?: boolean, allowNegative?: boolean }) {
const [count, setCount] = useState<number>(0);
const counterUpdated = (newAmount: number) => {
setCount(newAmount);
if (updateCount != undefined) {
updateCount(newAmount);
}
}
const minusDisabled = (!allowNegative && count <= 0)
return (
<div className="flex flex-row items-center gap-2">
<Button disabled={minusDisabled}
onClick={() => counterUpdated(count - 1)}>-</Button>
<Typography variant={"largeText"} className="mx-2">{count}</Typography>
<Button disabled={!addEnabled}
onClick={() => counterUpdated(count + 1)}>+</Button>
</div>
)
}
+31
View File
@@ -0,0 +1,31 @@
import * as React from "react"
import * as PopoverPrimitive from "@radix-ui/react-popover"
import { cn } from "@/lib/utils"
const Popover = PopoverPrimitive.Root
const PopoverTrigger = PopoverPrimitive.Trigger
const PopoverAnchor = PopoverPrimitive.Anchor
const PopoverContent = React.forwardRef<
React.ElementRef<typeof PopoverPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
))
PopoverContent.displayName = PopoverPrimitive.Content.displayName
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }
+29
View File
@@ -0,0 +1,29 @@
import * as React from "react"
import * as SeparatorPrimitive from "@radix-ui/react-separator"
import { cn } from "@/lib/utils"
const Separator = React.forwardRef<
React.ElementRef<typeof SeparatorPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
>(
(
{ className, orientation = "horizontal", decorative = true, ...props },
ref
) => (
<SeparatorPrimitive.Root
ref={ref}
decorative={decorative}
orientation={orientation}
className={cn(
"shrink-0 bg-border",
orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
className
)}
{...props}
/>
)
)
Separator.displayName = SeparatorPrimitive.Root.displayName
export { Separator }
+15
View File
@@ -0,0 +1,15 @@
import { cn } from "@/lib/utils"
function Skeleton({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) {
return (
<div
className={cn("animate-pulse rounded-md bg-primary/10", className)}
{...props}
/>
)
}
export { Skeleton }
+120
View File
@@ -0,0 +1,120 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Table = React.forwardRef<
HTMLTableElement,
React.HTMLAttributes<HTMLTableElement>
>(({ className, ...props }, ref) => (
<div className="relative w-full overflow-auto">
<table
ref={ref}
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
))
Table.displayName = "Table"
const TableHeader = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
))
TableHeader.displayName = "TableHeader"
const TableBody = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tbody
ref={ref}
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
))
TableBody.displayName = "TableBody"
const TableFooter = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tfoot
ref={ref}
className={cn(
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
className
)}
{...props}
/>
))
TableFooter.displayName = "TableFooter"
const TableRow = React.forwardRef<
HTMLTableRowElement,
React.HTMLAttributes<HTMLTableRowElement>
>(({ className, ...props }, ref) => (
<tr
ref={ref}
className={cn(
"border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
className
)}
{...props}
/>
))
TableRow.displayName = "TableRow"
const TableHead = React.forwardRef<
HTMLTableCellElement,
React.ThHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<th
ref={ref}
className={cn(
"h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
))
TableHead.displayName = "TableHead"
const TableCell = React.forwardRef<
HTMLTableCellElement,
React.TdHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<td
ref={ref}
className={cn(
"p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
))
TableCell.displayName = "TableCell"
const TableCaption = React.forwardRef<
HTMLTableCaptionElement,
React.HTMLAttributes<HTMLTableCaptionElement>
>(({ className, ...props }, ref) => (
<caption
ref={ref}
className={cn("mt-4 text-sm text-muted-foreground", className)}
{...props}
/>
))
TableCaption.displayName = "TableCaption"
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}
+127
View File
@@ -0,0 +1,127 @@
import * as React from "react"
import { Cross2Icon } from "@radix-ui/react-icons"
import * as ToastPrimitives from "@radix-ui/react-toast"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const ToastProvider = ToastPrimitives.Provider
const ToastViewport = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Viewport>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Viewport
ref={ref}
className={cn(
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
className
)}
{...props}
/>
))
ToastViewport.displayName = ToastPrimitives.Viewport.displayName
const toastVariants = cva(
"group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",
{
variants: {
variant: {
default: "border bg-background text-foreground",
destructive:
"destructive group border-destructive bg-destructive text-destructive-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
const Toast = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &
VariantProps<typeof toastVariants>
>(({ className, variant, ...props }, ref) => {
return (
<ToastPrimitives.Root
ref={ref}
className={cn(toastVariants({ variant }), className)}
{...props}
/>
)
})
Toast.displayName = ToastPrimitives.Root.displayName
const ToastAction = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Action>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Action
ref={ref}
className={cn(
"inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",
className
)}
{...props}
/>
))
ToastAction.displayName = ToastPrimitives.Action.displayName
const ToastClose = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Close>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Close
ref={ref}
className={cn(
"absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
className
)}
toast-close=""
{...props}
>
<Cross2Icon className="h-4 w-4" />
</ToastPrimitives.Close>
))
ToastClose.displayName = ToastPrimitives.Close.displayName
const ToastTitle = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Title>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Title
ref={ref}
className={cn("text-sm font-semibold [&+div]:text-xs", className)}
{...props}
/>
))
ToastTitle.displayName = ToastPrimitives.Title.displayName
const ToastDescription = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Description>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Description
ref={ref}
className={cn("text-sm opacity-90", className)}
{...props}
/>
))
ToastDescription.displayName = ToastPrimitives.Description.displayName
type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>
type ToastActionElement = React.ReactElement<typeof ToastAction>
export {
type ToastProps,
type ToastActionElement,
ToastProvider,
ToastViewport,
Toast,
ToastTitle,
ToastDescription,
ToastClose,
ToastAction,
}
+33
View File
@@ -0,0 +1,33 @@
import {
Toast,
ToastClose,
ToastDescription,
ToastProvider,
ToastTitle,
ToastViewport,
} from "@/components/ui/toast"
import { useToast } from "@/components/ui/use-toast"
export function Toaster() {
const { toasts } = useToast()
return (
<ToastProvider>
{toasts.map(function ({ id, title, description, action, ...props }) {
return (
<Toast key={id} {...props}>
<div className="grid gap-1">
{title && <ToastTitle>{title}</ToastTitle>}
{description && (
<ToastDescription>{description}</ToastDescription>
)}
</div>
{action}
<ToastClose />
</Toast>
)
})}
<ToastViewport />
</ToastProvider>
)
}
+28
View File
@@ -0,0 +1,28 @@
import * as React from "react"
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
import { cn } from "@/lib/utils"
const TooltipProvider = TooltipPrimitive.Provider
const Tooltip = TooltipPrimitive.Root
const TooltipTrigger = TooltipPrimitive.Trigger
const TooltipContent = React.forwardRef<
React.ElementRef<typeof TooltipPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<TooltipPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
))
TooltipContent.displayName = TooltipPrimitive.Content.displayName
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
+82
View File
@@ -0,0 +1,82 @@
'use client';
import * as React from 'react';
import { VariantProps, cva } from 'class-variance-authority';
import { cn } from '@/lib/utils';
import { Slot } from '@radix-ui/react-slot';
const typographyVariants = cva('text-foreground', {
variants: {
variant: {
h1: 'scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl',
h2: 'scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0',
h3: 'scroll-m-20 text-2xl font-semibold tracking-tight',
h4: 'scroll-m-20 text-xl font-semibold tracking-tight',
h5: 'scroll-m-20 text-lg font-semibold tracking-tight',
h6: 'scroll-m-20 text-base font-semibold tracking-tight',
p: 'leading-7 [&:not(:first-child)]:mt-6',
p_inline: 'leading-7',
blockquote: 'mt-6 border-l-2 pl-6 italic',
ul: 'my-6 ml-6 list-disc [&>li]:mt-2',
inlineCode:
'relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold',
lead: 'text-xl text-muted-foreground',
largeText: 'text-lg font-semibold',
smallText: 'text-sm font-medium leading-none',
mutedText: 'text-sm text-muted-foreground',
},
},
defaultVariants: {
variant: "p",
},
});
type VariantPropType = VariantProps<typeof typographyVariants>;
const variantElementMap: Record<
NonNullable<VariantPropType['variant']>,
string
> = {
h1: 'h1',
h2: 'h2',
h3: 'h3',
h4: 'h4',
h5: 'h5',
h6: 'h6',
p: 'p',
p_inline: 'p',
blockquote: 'blockquote',
inlineCode: 'code',
largeText: 'div',
smallText: 'small',
lead: 'p',
mutedText: 'p',
ul: 'ul',
};
export interface TypographyProps
extends React.HTMLAttributes<HTMLElement>,
VariantProps<typeof typographyVariants> {
asChild?: boolean;
as?: string;
}
const Typography = React.forwardRef<HTMLElement, TypographyProps>(
({ className, variant, as, asChild, ...props }, ref) => {
const Comp = asChild
? Slot
: as ?? (variant ? variantElementMap[variant] : undefined) ?? 'div';
return (
<Comp
className={cn(typographyVariants({ variant, className }))}
ref={ref}
{...props}
/>
);
}
);
Typography.displayName = 'Typography';
// eslint-disable-next-line react-refresh/only-export-components
export { Typography, typographyVariants };
+192
View File
@@ -0,0 +1,192 @@
// Inspired by react-hot-toast library
import * as React from "react"
import type {
ToastActionElement,
ToastProps,
} from "src/components/ui/toast"
const TOAST_LIMIT = 1
const TOAST_REMOVE_DELAY = 1000000
type ToasterToast = ToastProps & {
id: string
title?: React.ReactNode
description?: React.ReactNode
action?: ToastActionElement
}
const actionTypes = {
ADD_TOAST: "ADD_TOAST",
UPDATE_TOAST: "UPDATE_TOAST",
DISMISS_TOAST: "DISMISS_TOAST",
REMOVE_TOAST: "REMOVE_TOAST",
} as const
let count = 0
function genId() {
count = (count + 1) % Number.MAX_SAFE_INTEGER
return count.toString()
}
type ActionType = typeof actionTypes
type Action =
| {
type: ActionType["ADD_TOAST"]
toast: ToasterToast
}
| {
type: ActionType["UPDATE_TOAST"]
toast: Partial<ToasterToast>
}
| {
type: ActionType["DISMISS_TOAST"]
toastId?: ToasterToast["id"]
}
| {
type: ActionType["REMOVE_TOAST"]
toastId?: ToasterToast["id"]
}
interface State {
toasts: ToasterToast[]
}
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()
const addToRemoveQueue = (toastId: string) => {
if (toastTimeouts.has(toastId)) {
return
}
const timeout = setTimeout(() => {
toastTimeouts.delete(toastId)
dispatch({
type: "REMOVE_TOAST",
toastId: toastId,
})
}, TOAST_REMOVE_DELAY)
toastTimeouts.set(toastId, timeout)
}
export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case "ADD_TOAST":
return {
...state,
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
}
case "UPDATE_TOAST":
return {
...state,
toasts: state.toasts.map((t) =>
t.id === action.toast.id ? { ...t, ...action.toast } : t
),
}
case "DISMISS_TOAST": {
const { toastId } = action
// ! Side effects ! - This could be extracted into a dismissToast() action,
// but I'll keep it here for simplicity
if (toastId) {
addToRemoveQueue(toastId)
} else {
state.toasts.forEach((toast) => {
addToRemoveQueue(toast.id)
})
}
return {
...state,
toasts: state.toasts.map((t) =>
t.id === toastId || toastId === undefined
? {
...t,
open: false,
}
: t
),
}
}
case "REMOVE_TOAST":
if (action.toastId === undefined) {
return {
...state,
toasts: [],
}
}
return {
...state,
toasts: state.toasts.filter((t) => t.id !== action.toastId),
}
}
}
const listeners: Array<(state: State) => void> = []
let memoryState: State = { toasts: [] }
function dispatch(action: Action) {
memoryState = reducer(memoryState, action)
listeners.forEach((listener) => {
listener(memoryState)
})
}
type Toast = Omit<ToasterToast, "id">
function toast({ ...props }: Toast) {
const id = genId()
const update = (props: ToasterToast) =>
dispatch({
type: "UPDATE_TOAST",
toast: { ...props, id },
})
const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id })
dispatch({
type: "ADD_TOAST",
toast: {
...props,
id,
open: true,
onOpenChange: (open) => {
if (!open) dismiss()
},
},
})
return {
id: id,
dismiss,
update,
}
}
function useToast() {
const [state, setState] = React.useState<State>(memoryState)
React.useEffect(() => {
listeners.push(setState)
return () => {
const index = listeners.indexOf(setState)
if (index > -1) {
listeners.splice(index, 1)
}
}
}, [state])
return {
...state,
toast,
dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
}
}
export { useToast, toast }
+18
View File
@@ -0,0 +1,18 @@
import { useRouteError } from "react-router-dom";
export default function ErrorPage() {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const error : any = useRouteError();
console.error(error);
return (
<div id="error-page">
<h1>Oops!</h1>
<p>Sorry, an unexpected error has occurred.</p>
<p>
<i>{error.statusText || error.message}</i>
</p>
</div>
);
}
+61
View File
@@ -0,0 +1,61 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 240 10% 3.9%;
--card: 0 0% 100%;
--card-foreground: 240 10% 3.9%;
--popover: 0 0% 100%;
--popover-foreground: 240 10% 3.9%;
--primary: 142.1 76.2% 36.3%;
--primary-foreground: 355.7 100% 97.3%;
--secondary: 240 4.8% 95.9%;
--secondary-foreground: 240 5.9% 10%;
--muted: 240 4.8% 95.9%;
--muted-foreground: 240 3.8% 46.1%;
--accent: 240 4.8% 95.9%;
--accent-foreground: 240 5.9% 10%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 0 0% 98%;
--border: 240 5.9% 90%;
--input: 240 5.9% 90%;
--ring: 142.1 76.2% 36.3%;
--radius: 0.75rem;
}
.dark {
--background: 20 14.3% 4.1%;
--foreground: 0 0% 95%;
--card: 24 9.8% 10%;
--card-foreground: 0 0% 95%;
--popover: 0 0% 9%;
--popover-foreground: 0 0% 95%;
--primary: 142.1 70.6% 45.3%;
--primary-foreground: 144.9 80.4% 10%;
--secondary: 240 3.7% 15.9%;
--secondary-foreground: 0 0% 98%;
--muted: 0 0% 15%;
--muted-foreground: 240 5% 64.9%;
--accent: 12 6.5% 15.1%;
--accent-foreground: 0 0% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 0 85.7% 97.3%;
--border: 240 3.7% 15.9%;
--input: 240 3.7% 15.9%;
--ring: 142.4 71.8% 29.2%;
}
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
}
}
+6
View File
@@ -0,0 +1,6 @@
import { type ClassValue, clsx } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
+48
View File
@@ -0,0 +1,48 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import './index.css'
import { RouterProvider, createBrowserRouter } from 'react-router-dom';
import Root from './routes/Root';
import ErrorPage from './error-page';
import Homepage from './routes/home-page';
import SearchPage from './routes/search-page';
import BookPage from './routes/book-page';
import SuccessPage from './routes/success-page';
const router = createBrowserRouter([
{
path: "/",
element: <Root />,
errorElement: <ErrorPage />,
children: [
{
path: "/",
element: <Homepage />
},
{
path: "/home",
element: <Homepage />
},
{
path: "/search",
element: <SearchPage />
},
{
path: "/book",
element: <BookPage />
},
{
path: "/success",
element: <SuccessPage />
}
]
},
]);
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>,
)
+25
View File
@@ -0,0 +1,25 @@
export type NewBooking = {
arrivalDate: Date,
departureDate: Date,
customerDetails: NewBookingCustomerDetails,
rooms: NewBookingRoom[]
};
export type NewBookingCustomerDetails = {
name: string | null,
surname: string | null,
email: string | null,
phoneNumber: string | null
};
export type NewBookingRoom = {
roomCategory: number,
guestNumber: number,
amount: number,
price: number
};
export type NewBookingResponse = {
refNumber: number,
}
+24
View File
@@ -0,0 +1,24 @@
export type RoomCategory = {
id: number,
name: string,
description: string,
bedType: string,
maxGuestNum: number,
roomCategoryPhotos: RoomCategoryPhoto[],
roomCategoryDetails: RoomCategoryDetails[],
}
export type RoomCategoryDetails = {
id: number,
detailsSection: string,
detailValue: string,
}
export type RoomCategoryPhoto = {
id: number,
path: string,
altText: string | undefined,
kind: string,
}
+30
View File
@@ -0,0 +1,30 @@
export type RoomAvailabity = {
roomCategory: number,
availability: number
}
export type RoomPrice = {
guestNumber: number,
price: number
}
export type AvailabilityRequest = {
filter: AvailabilityFilter
}
export type AvailabilityFilter = {
startDate: string,
endDate: string
}
export type FareRequest = {
filter: FareFilter
}
export type FareFilter = {
roomCategory: number,
startDate: string,
endDate: string
}
+5
View File
@@ -0,0 +1,5 @@
import { DateRange } from "react-day-picker"
export type SearchFilter = {
dateRange: DateRange
}
+17
View File
@@ -0,0 +1,17 @@
html {
box-sizing: border-box;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
.appPage {
width: 80%;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
+24
View File
@@ -0,0 +1,24 @@
import { Outlet } from 'react-router-dom'
import './Root.css'
import AppHeader from '../components/app-header'
import AppFooter from '../components/app-footer'
import { ThemeProvider } from '@/components/theme-provider'
import { Toaster } from '@/components/ui/toaster'
function Root() {
return (
<>
<ThemeProvider defaultTheme="dark" storageKey="vite-ui-theme">
<AppHeader />
<div className='appPage bg-background text-foreground'>
<Outlet />
</div>
<Toaster />
<AppFooter />
</ThemeProvider>
</>
)
}
export default Root
+125
View File
@@ -0,0 +1,125 @@
import { APISendCreateBooking } from "@/api/api-booking"
import { BookingDetails } from "@/components/booking/booking-details"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Separator } from "@/components/ui/separator"
import { Typography } from "@/components/ui/typography"
import { useToast } from "@/components/ui/use-toast"
import { useAppStore } from "@/store"
import { ChangeEvent, useState } from "react"
import { useNavigate } from "react-router-dom"
enum PageState {
noData, showForm, sending, created, error
}
function BookPage() {
const [pageState, setPageState] = useState<PageState>(PageState.showForm);
const bookingData = useAppStore((state) => state.newBookingData)
const setCustomerData = useAppStore((state) => state.setBookingCustomer);
const { toast } = useToast();
const navigate = useNavigate();
if (!bookingData || !bookingData.customerDetails) {
return (
<Typography variant={"h2"}>You must select some rooms...</Typography>
)
}
function handleOnChange(e: ChangeEvent<HTMLInputElement>) {
if (bookingData == null) {
return;
}
const newCustomerData = bookingData.customerDetails;
switch (e.target.name) {
case "name":
newCustomerData.name = e.target.value;
break;
case "surname":
newCustomerData.surname = e.target.value;
break;
case "email":
newCustomerData.email = e.target.value;
break;
case "phoneNumber":
newCustomerData.phoneNumber = e.target.value;
break;
default:
break;
}
setCustomerData(newCustomerData);
}
function handleOnBookingSubmit() {
const customerDetails = bookingData?.customerDetails;
if (!customerDetails ||
customerDetails.name == "" || customerDetails.surname == "" || customerDetails.phoneNumber == "" || customerDetails.email == "") {
toast({
variant: "destructive",
title: "Uh oh! You must fill all fields.",
});
return;
}
setPageState(PageState.sending);
console.log(bookingData);
sendCreateRequest();
}
const sendCreateRequest = async () => {
const rs = await APISendCreateBooking(bookingData);
if (rs.isError) {
setPageState(PageState.error);
} else {
navigate("/success", { state: rs.bookingResponse })
}
}
return (
<>
<Typography variant={"h1"}>Booking Details</Typography>
<Separator className="my-10" />
<div>
<Typography variant={"h3"}>Personal Details</Typography>
<div>
<div>
<Label htmlFor="name">Name</Label>
<Input type="text" name="name" id="name" placeholder="Name" value={bookingData.customerDetails.name ?? ""}
onChange={handleOnChange} />
</div>
<div>
<Label htmlFor="surname">Surname</Label>
<Input type="text" name="surname" id="surname" placeholder="Surname" value={bookingData.customerDetails.surname ?? ""}
onChange={handleOnChange} />
</div>
<div>
<Label htmlFor="email">Email</Label>
<Input type="email" name="email" id="email" placeholder="Email" value={bookingData.customerDetails.email ?? ""}
onChange={handleOnChange} />
</div>
<div>
<Label htmlFor="phone">Phone Number</Label>
<Input type="tel" name="phoneNumber" id="phone" placeholder="Number" value={bookingData.customerDetails.phoneNumber ?? ""}
onChange={handleOnChange} />
</div>
</div>
</div>
<Separator className="my-10" />
<BookingDetails mode="View"></BookingDetails>
<Separator className="my-10" />
<Button onClick={handleOnBookingSubmit} disabled={pageState == PageState.sending}>
<Typography variant={"h3"} className="text-primary-foreground">Book it now!</Typography>
</Button>
</>
)
}
export default BookPage
+48
View File
@@ -0,0 +1,48 @@
import { useAPIRoomCategories } from "@/api/api-roomCategories"
import { RoomItemCard } from "@/components/Rooms/room-item-card"
import { SearchFilterCard } from "@/components/Search/SearchFilterCard"
import BackendConnectionStatus from "@/components/backend-conection-status"
import { Separator } from "@/components/ui/separator"
import { Skeleton } from "@/components/ui/skeleton"
import { Typography } from "@/components/ui/typography"
import { RoomCategory } from "@/model/RoomCategory"
import { SearchFilter } from "@/model/SearchFilter"
import { useNavigate } from "react-router-dom"
function Homepage() {
const { roomCategoryList, isLoading, isError } = useAPIRoomCategories();
const navigate = useNavigate();
const onBtSearchClick = (filter: SearchFilter) => {
navigate("/search", {state: filter})
}
const roomList = roomCategoryList?.map((element: RoomCategory) => {
return (
<RoomItemCard key={element.id} room={element} />
);
});
return (
<>
<Typography variant={"h1"}>Somnia Rooms</Typography>
<Separator className="my-10" />
<SearchFilterCard onSearchClick={onBtSearchClick}/>
<Separator className="my-10" />
<div className="grid grid-cols-2 gap-4">
{roomList}
</div>
{isLoading && (
<>
<Typography variant={"h3"} as="h2">Loading...</Typography>
<Skeleton className="w-[400px] h-[200px] mx-auto" />
</>
)}
<Separator className="my-10" />
<BackendConnectionStatus isLoading={isLoading} isError={isError} />
</>
)
}
export default Homepage
+95
View File
@@ -0,0 +1,95 @@
import { useAPIRoomAvailability } from "@/api/api-roomSearch"
import RoomBooking from "@/components/Rooms/room-booking"
import { SearchFilterCard } from "@/components/Search/SearchFilterCard"
import BackendConnectionStatus from "@/components/backend-conection-status"
import { BookingDetails } from "@/components/booking/booking-details"
import { Separator } from "@/components/ui/separator"
import { Skeleton } from "@/components/ui/skeleton"
import { Typography } from "@/components/ui/typography"
import { AvailabilityFilter } from "@/model/RoomSearch"
import { SearchFilter } from "@/model/SearchFilter"
import { useAppStore } from "@/store"
import { useMemo, useState } from "react"
import { useNavigate } from "react-router-dom"
//TODOME: Igual podemos crear un StateMachine conjunta para los siguiente estados de la página: Sin Buscar, Sin disponibilidad, error, cargando.
function SearchPage() {
//const [availabilityFilter, setAvailabilityFilter] = useState<AvailabilityFilter>();
const searchFilter = useAppStore((state) => (state.searchFilter));
const resetBooking = useAppStore((state) => (state.resetBookingState));
const navigate = useNavigate();
const [isSearched, setIsSearched] = useState<boolean>(false);
const onBtSearchClick = (newFilter: SearchFilter) => {
console.log("onBtSearchClick: ");
console.log(newFilter);
if (newFilter.dateRange && newFilter.dateRange.from && newFilter.dateRange.to) {
setIsSearched(true);
resetBooking(newFilter.dateRange.from, newFilter.dateRange.to);
}
}
const onBookingContinue = () => {
navigate("/book");
}
//This seems a little bit overkill, but IDK.
const availabilityFilter: AvailabilityFilter | null = useMemo(
() => {
if (searchFilter && searchFilter.dateRange && searchFilter.dateRange.from && searchFilter.dateRange.to) {
const newAvailabilityFilter: AvailabilityFilter = {
startDate: searchFilter.dateRange.from.toDateString(),
endDate: searchFilter.dateRange.to.toDateString()
};
return newAvailabilityFilter;
}
return null;
},
[searchFilter]
);
const { roomAvailabilityList, isLoading: isLoadingAvailability, isError: isErrorAvailability } = useAPIRoomAvailability(availabilityFilter ?? null);
const isLoading = isLoadingAvailability;
const isError = isErrorAvailability;
const roomList = roomAvailabilityList?.map((element) => {
return (
<RoomBooking key={element.roomCategory} availableAmount={element.availability} roomCategoryId={element.roomCategory} />
);
});
const noRoomsAvailable = (
<>
<Typography variant={"h3"} as="h3">Sorry 😔, there aren't rooms available for selected period.
You can contact us for more info.</Typography>
</>
);
const hasRooms = (roomAvailabilityList?.length && roomAvailabilityList?.length > 0);
console.log(hasRooms);
return (
<div className="bg-background text-foreground">
<SearchFilterCard onSearchClick={onBtSearchClick} />
<Separator className="my-10" />
{isLoading && (
<>
<Typography variant={"h3"} as="h2">Loading...</Typography>
<Skeleton className="w-[400px] h-[200px] mx-auto" />
</>
)}
<div className="flex flex-col gap-5">
{hasRooms ? roomList : (isSearched && noRoomsAvailable)}
</div>
<Separator className="my-10" />
<BookingDetails onBookingConfirm={onBookingContinue} mode={"Book"}></BookingDetails>
<Separator className="my-10" />
<BackendConnectionStatus isLoading={isLoading} isError={isError} />
</div>
)
}
export default SearchPage
+47
View File
@@ -0,0 +1,47 @@
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader } from "@/components/ui/card"
import { Typography } from "@/components/ui/typography"
import { NewBookingResponse } from "@/model/Bookings"
import { useAppStore } from "@/store"
import { addDays } from "date-fns"
import { useEffect, useState } from "react"
import { useLocation, useNavigate } from "react-router-dom"
function SuccessPage() {
const [pageState, setPageState] = useState<NewBookingResponse|null>(null)
const resetBookingState = useAppStore((state) => state.resetBookingState);
const location = useLocation();
const navigate = useNavigate();
useEffect(() => {
if(location.state == null) {
navigate("/home");
}
setPageState(location.state);
}, [location, navigate])
const handleBtBackClick = () => {
resetBookingState(new Date(), addDays(new Date(), 2));
navigate("/home");
}
return (
<Card>
<CardHeader>
<Typography variant={"h2"}>Booking Completed</Typography>
</CardHeader>
<CardContent>
<Typography variant={"largeText"}>Booking ref: {pageState?.refNumber}</Typography>
<Button className="my-4" onClick={handleBtBackClick}>
<Typography variant={"largeText"} className="text-primary-foreground">Go Back</Typography>
</Button>
</CardContent>
</Card>
)
}
export default SuccessPage
+95
View File
@@ -0,0 +1,95 @@
import { create } from 'zustand'
import { SearchFilter } from './model/SearchFilter'
import { NewBooking, NewBookingCustomerDetails, NewBookingRoom } from './model/Bookings'
interface AppState {
searchFilter: SearchFilter
setSearchFilter: (newFilter: SearchFilter) => void
newBookingData: NewBooking | null
setNewBooking: (newBooking: NewBooking) => void
resetBookingState: (arrival: Date, departure: Date) => void
addNewBookingRoom: (newRoom: NewBookingRoom) => void
setBookingCustomer: (newCustomer: NewBookingCustomerDetails) => void
}
const defaultSearchFilter: SearchFilter = {
dateRange: { from: new Date() }
}
const defaultNewBooking: NewBooking = {
arrivalDate: new Date(),
departureDate: new Date(),
customerDetails: {
name: null,
surname: null,
email: null,
phoneNumber: null
},
rooms: []
}
function getDefaultBookingData(arrivalDate: Date, departureDate: Date) {
return {
...defaultNewBooking,
arrivalDate: arrivalDate,
departureDate: departureDate
}
}
function addNewBookingRoomToCurrentState(newRoom: NewBookingRoom, currentState: NewBooking | null): NewBooking | null {
if (currentState == null) {
return currentState;
}
//Remove rooms with "same key".
const filteredRooms = currentState.rooms.filter((room) => {
const diffRoom = room.roomCategory != newRoom.roomCategory;
const diffAmount = room.guestNumber != newRoom.guestNumber;
if(diffRoom || (!diffRoom && diffAmount)) {
return true;
}
return false;
})
console.log(filteredRooms);
if (newRoom.amount > 0) {
filteredRooms.push(newRoom);
}
const newState: NewBooking = {
...currentState,
rooms: filteredRooms ?? []
}
console.log("AddRoomNewState:");
console.log(newState);
return newState;
}
function setBookingCustomer(newCustomer: NewBookingCustomerDetails, currentState: NewBooking | null) {
if(currentState == null) {
return currentState;
}
const newState: NewBooking = {
...currentState,
customerDetails: newCustomer
};
return newState;
}
export const useAppStore = create<AppState>()((set) => ({
searchFilter: defaultSearchFilter,
setSearchFilter: (newFilter) => set(() => ({ searchFilter: newFilter })),
newBookingData: null,
setNewBooking: (newBooking) => set(() => ({ newBookingData: newBooking })),
resetBookingState: (arrival, departure) =>
set(() => ({ newBookingData: getDefaultBookingData(arrival, departure) })),
addNewBookingRoom: (newRoom: NewBookingRoom) =>
set((state) => ({ newBookingData: addNewBookingRoomToCurrentState(newRoom, state.newBookingData) })),
setBookingCustomer: (newCustomer: NewBookingCustomerDetails) =>
set((state) => ({newBookingData: setBookingCustomer(newCustomer, state.newBookingData)}))
}))
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+79
View File
@@ -0,0 +1,79 @@
import plugin from 'tailwindcss-animate';
/** @type {import('tailwindcss').Config} */
export default {
darkMode: ["class"],
content: [
'./pages/**/*.{ts,tsx}',
'./components/**/*.{ts,tsx}',
'./app/**/*.{ts,tsx}',
'./src/**/*.{ts,tsx}',
],
prefix: "",
theme: {
container: {
center: true,
padding: "2rem",
screens: {
"2xl": "1400px",
},
},
extend: {
colors: {
border: "hsl(var(--border))",
input: "hsl(var(--input))",
ring: "hsl(var(--ring))",
background: "hsl(var(--background))",
foreground: "hsl(var(--foreground))",
primary: {
DEFAULT: "hsl(var(--primary))",
foreground: "hsl(var(--primary-foreground))",
},
secondary: {
DEFAULT: "hsl(var(--secondary))",
foreground: "hsl(var(--secondary-foreground))",
},
destructive: {
DEFAULT: "hsl(var(--destructive))",
foreground: "hsl(var(--destructive-foreground))",
},
muted: {
DEFAULT: "hsl(var(--muted))",
foreground: "hsl(var(--muted-foreground))",
},
accent: {
DEFAULT: "hsl(var(--accent))",
foreground: "hsl(var(--accent-foreground))",
},
popover: {
DEFAULT: "hsl(var(--popover))",
foreground: "hsl(var(--popover-foreground))",
},
card: {
DEFAULT: "hsl(var(--card))",
foreground: "hsl(var(--card-foreground))",
},
},
borderRadius: {
lg: "var(--radius)",
md: "calc(var(--radius) - 2px)",
sm: "calc(var(--radius) - 4px)",
},
keyframes: {
"accordion-down": {
from: { height: "0" },
to: { height: "var(--radix-accordion-content-height)" },
},
"accordion-up": {
from: { height: "var(--radix-accordion-content-height)" },
to: { height: "0" },
},
},
animation: {
"accordion-down": "accordion-down 0.2s ease-out",
"accordion-up": "accordion-up 0.2s ease-out",
},
},
},
plugins: [plugin],
}
+31
View File
@@ -0,0 +1,31 @@
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": [
"./src/*"
]
},
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}
+11
View File
@@ -0,0 +1,11 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true,
"strict": true
},
"include": ["vite.config.ts"]
}
+17
View File
@@ -0,0 +1,17 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'
import path from "path"
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
server: {
host: true,
port: 3000,
},
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
})