Compare commits

..
51 Commits
Author SHA1 Message Date
Daniel-Garmig 4a3378573b Booking page - Migrated from Shadcn Form to Shadcn Field components 2026-01-13 21:18:06 +01:00
Daniel-Garmig 25364deb8e Updated Libs - Zod v3 to v4 2026-01-13 20:15:35 +01:00
Daniel-Garmig 53ddf1e73c Updated Libs - React-Router v6 to v7 2026-01-13 20:03:01 +01:00
Daniel-Garmig 899d27f468 Updated Prettier formatting 2026-01-13 15:00:22 +01:00
Daniel-Garmig 90fa82234d Removed Toast component 2026-01-13 14:14:22 +01:00
Daniel-Garmig b8ec6f7bdd General improvements:
- Search control - Improved error messages.
- Fixed lint errors.
2026-01-13 14:12:58 +01:00
Daniel-Garmig 94312de6e2 Contact flow:
- Added contact page for bookings over API limit.
- Added ContactUs dialog to redirect customers to contact page.
2026-01-07 22:25:27 +01:00
Daniel-Garmig d4094d09c6 Updated shadcn-ui components. 2026-01-05 22:01:53 +01:00
Daniel-Garmig 42437881c4 Updated deps (minor) 2026-01-05 20:35:39 +01:00
Daniel-Garmig 5d2eb2e635 General improvements in booking state management. 2026-01-05 20:11:42 +01:00
Daniel-Garmig 2b3d1eafd3 API - Use the new Prices API. 2026-01-05 15:08:05 +01:00
Daniel-Garmig 70e483bc45 API - Prices - Updated endpoint for prices "by RoomCategory". 2025-10-13 14:58:27 +02:00
Daniel-Garmig 99653371a8 Added config var usage: Use SomniaRooms config vars.
Improvements to app footer and header.
2025-10-13 13:51:27 +02:00
Daniel-Garmig 3e77426d1d Config Vars - Get config vars from API 2025-09-22 20:52:23 +02:00
Daniel-Garmig 550beffba8 Booking page state improvements. 2025-09-08 19:45:46 +02:00
Daniel-Garmig 590d7f6fa1 State Management - Improve state management for searchs. 2025-09-08 14:36:50 +02:00
Daniel-Garmig 4c21dc2764 Update Libs - Fixed TailwindCSS Animate not found 2025-06-12 22:07:48 +02:00
Daniel-Garmig 4d01112006 Update Libs - Updated Zustand v4 to v5 2025-06-12 21:38:39 +02:00
Daniel-Garmig 984c386588 Updated libs - Updated Zod v3 to v4. 2025-06-10 21:06:54 +02:00
Daniel-Garmig 0efe5bfa9e Update libs - Updated eslint v8 to v9 2025-06-09 19:48:33 +02:00
Daniel-Garmig 7ba7c4b04b Updated Libs - Updated shadcn UI components (again) after Tailwindcss 4 update. 2025-06-07 21:25:32 +02:00
Daniel-Garmig bb53ba6cb4 Update Libs - Updated Tailwindcss 3 to 4. 2025-06-07 21:23:24 +02:00
Daniel-Garmig 57dcbdec14 Update libs - Updated shadcn UI components. 2025-06-07 14:54:30 +02:00
Daniel-Garmig 825dc4365f Update Libs - Updated Vite v5.2.0 to 6.3.5 2025-06-07 14:54:03 +02:00
Daniel-Garmig 67f9e19eb8 Added Iconify "Icon" web component for dynamic icons. 2025-06-03 21:34:46 +02:00
Daniel-Garmig 06c1af92b3 Update API requests to last API changes. 2025-06-03 20:56:10 +02:00
Daniel-Garmig 532337a46a Improve booking form. 2024-09-09 09:27:09 +02:00
Daniel-Garmig 191379ed03 Included shadcn/UI form component. 2024-09-03 20:03:51 +02:00
Daniel-Garmig f476f4307a Added Prettier for TailwindCSS. 2024-09-03 19:05:45 +02:00
Daniel-Garmig dedfc1cdd8 Redesign some more pages and other improvements. 2024-09-03 18:58:47 +02:00
Daniel-Garmig 2d2992593a Refactor HomePage and more! 2024-08-30 21:20:40 +02:00
Daniel-Garmig b034d2e9c9 Add Prettier support. 2024-08-12 20:59:51 +02:00
Daniel-Garmig d4458e8f00 Little cleaning and fixes 2024-08-12 20:56:14 +02:00
Daniel-Garmig d3358c7c58 Fix Actions - Change image repository for push.
CI / Docker Lint (push) Successful in 22s
2024-05-13 01:18:26 +02:00
Daniel-Garmig 4e825c7ca7 Small fix pass. 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.
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: Somnia/SomniaRoomsApp#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
86 changed files with 17429 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
+2
View File
@@ -0,0 +1,2 @@
# EOL normalization
* text=auto
+22
View File
@@ -0,0 +1,22 @@
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
+7
View File
@@ -0,0 +1,7 @@
# Ignore artifacts:
**/dist
**/.git
**/.svn
**/.hg
**/node_modules
+5
View File
@@ -0,0 +1,5 @@
{
"endOfLine": "auto",
"plugins": ["prettier-plugin-tailwindcss"],
"tailwindStylesheet": "./src/index.css"
}
+26
View File
@@ -0,0 +1,26 @@
# Base Node Environment.
FROM node:22-alpine 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;"]
+67 -1
View File
@@ -1,3 +1,69 @@
# SomniaRoomsApp
Somnia Rooms - User App
User app for SomniaRooms.
## Podman Usage:
### Dev
**Build Image:**
```
podman build -t somniarooms-app:dev --target final-dev .
```
**Podman Run Image:**
```
podman 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**
```
podman build -t somniarooms-app:prod --target final-prod .
```
**Podman Run**
```
podman run -d -it -p 8080:80 --name somniarooms-app somniarooms-app:prod
```
**Podman run with env vars:**
```
podman 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 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)
+21
View File
@@ -0,0 +1,21 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/index.css",
"baseColor": "stone",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}
+55
View File
@@ -0,0 +1,55 @@
const { defineConfig, globalIgnores } = require("eslint/config");
const globals = require("globals");
const { fixupConfigRules } = require("@eslint/compat");
const tsParser = require("@typescript-eslint/parser");
const reactRefresh = require("eslint-plugin-react-refresh");
const js = require("@eslint/js");
const { FlatCompat } = require("@eslint/eslintrc");
const compat = new FlatCompat({
baseDirectory: __dirname,
recommendedConfig: js.configs.recommended,
allConfig: js.configs.all,
});
module.exports = defineConfig([
{
languageOptions: {
globals: {
...globals.browser,
...Object.fromEntries(
Object.entries(globals.node).map(([key]) => [key, "off"]),
),
},
parser: tsParser,
},
extends: fixupConfigRules(
compat.extends(
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:react-hooks/recommended",
"prettier",
),
),
plugins: {
"react-refresh": reactRefresh,
},
rules: {
"react-refresh/only-export-components": [
"warn",
{
allowConstantExport: true,
},
],
},
},
globalIgnores(["**/dist", "eslint.config.cjs"]),
]);
+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>
+6341
View File
File diff suppressed because it is too large Load Diff
+57
View File
@@ -0,0 +1,57 @@
{
"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 && npx prettier . --check",
"pretty": "npx prettier . --write",
"preview": "vite preview"
},
"dependencies": {
"@hookform/resolvers": "^5.2.2",
"@tailwindcss/vite": "^4.1.18",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"date-fns": "^4.1.0",
"embla-carousel-react": "^8.6.0",
"lucide-react": "^0.562.0",
"radix-ui": "^1.4.3",
"react": "^18.2.0",
"react-day-picker": "^9.13.0",
"react-dom": "^18.2.0",
"react-hook-form": "^7.71.0",
"react-router": "^7.12.0",
"swr": "^2.3.8",
"tailwind-merge": "^3.4.0",
"zod": "^4.3.5",
"zustand": "^5.0.9"
},
"devDependencies": {
"@eslint/compat": "^2.0.0",
"@eslint/eslintrc": "^3.3.3",
"@eslint/js": "^9.39.2",
"@iconify-icon/react": "^3.0.3",
"@tailwindcss/postcss": "^4.1.18",
"@types/node": "^22.15.30",
"@types/react": "^18.2.66",
"@types/react-dom": "^18.2.22",
"@typescript-eslint/eslint-plugin": "^8.52.0",
"@typescript-eslint/parser": "^8.52.0",
"@vitejs/plugin-react-swc": "^4.2.2",
"eslint": "^9.39.2",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.4.26",
"globals": "^17.0.0",
"postcss": "^8.5.6",
"prettier": "^3.7.4",
"prettier-plugin-tailwindcss": "^0.7.2",
"tailwindcss": "^4.1.18",
"tw-animate-css": "^1.4.0",
"typescript": "^5.9.3",
"vite": "^6.4.1"
}
}
+5
View File
@@ -0,0 +1,5 @@
export default {
plugins: {
"@tailwindcss/postcss": {},
},
};
+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
+29
View File
@@ -0,0 +1,29 @@
import { NewBooking, NewBookingResponse } from "@/model/Bookings";
import { fetcherWithFilter } from "./backend";
export async function APISendCreateBooking(bookingData: NewBooking | null) {
if (!bookingData) {
return {
bookingResponse: null,
isError: true,
};
}
try {
const rs = await fetcherWithFilter<NewBookingResponse>(
"/api/booking/create",
bookingData,
);
return {
bookingResponse: rs,
isError: false,
};
} catch (error) {
return {
bookingResponse: null,
isError: true,
errorMessage: error,
};
}
}
+28
View File
@@ -0,0 +1,28 @@
import { ConfigVar } from "@/model/ConfigVar";
import { fetcher, fetcherUnwraper } from "./backend";
import useSWR from "swr";
export function useAPIConfigVarList() {
const { data, error, isLoading } = useSWR<ConfigVar[]>(
"/api/config",
fetcherUnwraper,
);
return {
configVarList: data,
isLoading,
isError: error,
};
}
export function useAPIConfigVar(key: string) {
const url = `/api/config/var/${key}`;
const { data, error, isLoading } = useSWR<ConfigVar>(url, fetcher);
return {
configVar: data,
isLoading,
isError: error,
};
}
+28
View File
@@ -0,0 +1,28 @@
import { RoomCategory } from "@/model/RoomCategory";
import { fetcher, fetcherUnwraper } from "./backend";
import useSWR from "swr";
export function useAPIRoomCategoryList() {
const { data, error, isLoading } = useSWR<RoomCategory[]>(
"/api/room/category",
fetcherUnwraper,
);
return {
roomCategoryList: data,
isLoading,
isError: error,
};
}
export function useAPIRoomCategory(categoryId: number) {
const url = `/api/room/category/${categoryId}`;
const { data, error, isLoading } = useSWR<RoomCategory>(url, fetcher);
return {
roomCategory: data,
isLoading,
isError: error,
};
}
+35
View File
@@ -0,0 +1,35 @@
import { fetcherUnwraperWithFilter } from "./backend";
import useSWR from "swr";
import {
SearchPeriodRequest,
RoomAvailabity,
RoomPriceSearchResponse,
} from "@/model/RoomSearch";
export function useAPIRoomAvailability(filter: SearchPeriodRequest | null) {
const { data, isLoading, error } = useSWR(
filter ? ["/api/search/availability", filter] : null,
([url, request]) =>
fetcherUnwraperWithFilter<RoomAvailabity[]>(url, request),
);
return {
roomAvailabilityList: data,
isLoading,
isError: error,
};
}
export function useAPIRoomPrices(filter: SearchPeriodRequest | null) {
const { data, isLoading, error } = useSWR(
filter ? ["/api/search/prices", filter] : null,
([url, request]) =>
fetcherUnwraperWithFilter<RoomPriceSearchResponse[]>(url, request),
);
return {
roomPriceList: data,
isLoading,
isError: error,
};
}
+71
View File
@@ -0,0 +1,71 @@
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;
});
}
@@ -0,0 +1,65 @@
import { useNavigate } from "react-router";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "../ui/alert-dialog";
import { Button } from "../ui/button";
import { ConstsNav, ConstsTexts } from "@/utils/Consts";
type OnCancelClickFunction = () => void;
export function ContactUsDialog({
onCancelClick,
isOpen,
cancelButtonText = "Cancel",
}: {
cancelButtonText: string;
onCancelClick: OnCancelClickFunction;
isOpen: boolean;
}) {
const navigate = useNavigate();
const navToContactPage = (text: string) => {
navigate(ConstsNav.page_Contact, {
state: text,
});
};
return (
<AlertDialog open={isOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{ConstsTexts.contactUsAlertDialog_title}
</AlertDialogTitle>
<AlertDialogDescription>
{ConstsTexts.contactUsAlertDialog_text}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel asChild>
<Button variant={"secondary"} onClick={onCancelClick}>
{cancelButtonText}
</Button>
</AlertDialogCancel>
<AlertDialogAction asChild>
<Button
variant={"link"}
onClick={() =>
navToContactPage("Contact us for a personalized quote!")
}
>
Go to contact page
</Button>
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
);
}
+175
View File
@@ -0,0 +1,175 @@
import { Card, CardContent } from "../ui/card";
import { Typography } from "../ui/typography";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "../ui/table";
import { Skeleton } from "../ui/skeleton";
import { useAppStore } from "@/store";
import { NumberSelector } from "../ui/number-selector";
import { NewBooking, NewBookingRoom } from "@/model/Bookings";
import { RoomItemCard } from "./room-item-card";
import { IconWithTooltip } from "../ui/icon-number-tooltip";
import { UserIcon } from "lucide-react";
import { makeSearchPeriodRequestFromSearchFilter } from "@/utils/utils";
import { SearchFilter } from "@/model/InternalTypes";
import { useRoomCategory, useRoomPrice } from "@/utils/apiHooks";
function RoomBooking({
roomCategoryId,
availableAmount,
}: {
roomCategoryId: number;
availableAmount: number;
}) {
const appSearchFilter: SearchFilter = useAppStore(
(state) => state.searchFilter,
);
const addNewRoom = useAppStore((state) => state.currentBookingAddRoom);
const bookingRooms: NewBooking | null = useAppStore(
(state) => state.currentBooking,
);
function onSelectedAmountUpdate(
guestNumber: number,
newCount: number,
price: number,
) {
const newRoom: NewBookingRoom = {
roomCategory: roomCategoryId,
guestNumber: guestNumber,
amount: newCount,
price: price,
};
addNewRoom(newRoom);
}
const getSelectedRoomAmount = (guestNumber: number | null) => {
let sum = 0;
if (bookingRooms) {
//Rooms with same category and, if guestNumber is set, rooms with same guestNumber.
bookingRooms.rooms
.filter((v) => {
const isSameCat = v.roomCategory == roomCategoryId;
const isSameGuestNum =
guestNumber != null ? v.guestNumber == guestNumber : true;
return isSameCat && isSameGuestNum;
})
.forEach((v) => (sum += v.amount));
}
return sum;
};
const totalSelectAmount = getSelectedRoomAmount(null);
const canAddMoreRooms: boolean = availableAmount > totalSelectAmount;
//This seems a little bit overkill, but IDK.
const fareFilter = makeSearchPeriodRequestFromSearchFilter(appSearchFilter);
const { value: roomCategory, isLoading: isLoadingCategory } =
useRoomCategory(roomCategoryId);
const { value: roomPriceList, isLoading: isLoadingPrices } = useRoomPrice(
fareFilter,
roomCategoryId,
);
const isLoading = isLoadingCategory || isLoadingPrices;
const isError = roomCategory == null;
if (isLoading) {
return <Skeleton className="mx-auto h-[150px] w-[600px]" />;
}
if (isError) {
return (
<Typography variant={"h3"} as="h3">
Sorry, there was an error loading data.
</Typography>
);
}
const hasPrices = roomPriceList != null && roomPriceList?.length > 0;
let priceTable = null;
if (hasPrices) {
//A row for each room guestNumber.
let tableRows = null;
if (!isLoadingPrices) {
tableRows = roomPriceList?.map((el) => {
const selectedRoomAmount =
totalSelectAmount > 0 ? getSelectedRoomAmount(el.guestNumber) : 0;
return (
<TableRow key={roomCategoryId + "-" + el.guestNumber}>
<TableCell>
<IconWithTooltip
label={el.guestNumber?.toString()}
tooltipText={"Guest Number"}
labelPosition={"right"}
>
<UserIcon></UserIcon>
</IconWithTooltip>
</TableCell>
<TableCell>{el.price / 100} €</TableCell>
<TableCell>
<NumberSelector
updateCount={(count) =>
onSelectedAmountUpdate(el.guestNumber, count, el.price)
}
addEnabled={canAddMoreRooms}
initialValue={selectedRoomAmount}
></NumberSelector>
</TableCell>
</TableRow>
);
});
}
//Element for
priceTable = (
<Table className="overflow-hidden">
<TableHeader>
<TableRow>
<TableHead>Guest number</TableHead>
<TableHead>Price</TableHead>
<TableHead>Amount</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{isLoadingPrices ? <Skeleton className="h-full w-full" /> : tableRows}
</TableBody>
</Table>
);
}
let roomCard = null;
if (roomCategory) {
roomCard = (
<RoomItemCard
room={roomCategory}
key={roomCategoryId}
className="z-20 border-4"
></RoomItemCard>
);
}
return (
<div className="relative sm:grid sm:grid-cols-40/60">
{roomCard}
<Card className="relative mx-auto w-[95%] -translate-y-2 self-center rounded-none rounded-b-xl sm:mx-0 sm:h-4/5 sm:w-full sm:-translate-x-2 sm:translate-y-0 sm:rounded-e-xl">
<CardContent className="flex h-full w-full flex-col justify-center gap-4 p-5">
{hasPrices ? (
priceTable
) : (
<Typography variant={"largeText"}>No Prices available</Typography>
)}
<p>Rooms Available: {availableAmount}</p>
</CardContent>
</Card>
</div>
);
}
export default RoomBooking;
+100
View File
@@ -0,0 +1,100 @@
import { Separator } from "../ui/separator";
import { Card, CardContent } from "../ui/card";
import { Typography } from "../ui/typography";
import { UserIcon } from "lucide-react";
import { RoomCategory } from "@/model/RoomCategory";
import { IconWithTooltip } from "../ui/icon-number-tooltip";
import defaultRoomImg from "@/res/SomniaRoomImage.svg";
import { cn } from "@/lib/utils";
import { Icon } from "@iconify-icon/react";
import { useConfigVariable } from "@/utils/apiHooks";
import { eConfigVarKeys } from "@/model/ConfigVar";
interface RoomItemCardProps {
room: RoomCategory;
className?: string;
}
const defaultRoom: RoomCategory = {
id: -1,
name: "Sample Room",
description: "Lorem Ipsum",
maxGuestNum: 2,
orderHomePage: undefined,
roomCategoryPhotos: [],
roomCategoryBedTypes: [],
};
export function RoomItemCard({
room = defaultRoom,
className,
}: RoomItemCardProps) {
const { value: varPhotoAspect } = useConfigVariable(
eConfigVarKeys.varPhotoAspectRatio,
"4/3",
);
//FIXME: Use PhotoOrder.
const getRoomMainPhoto = () => {
if (room.roomCategoryPhotos.length < 0) {
return defaultRoomImg;
}
return room.roomCategoryPhotos.at(0)?.path ?? defaultRoomImg;
};
const bedTypeIconList = room.roomCategoryBedTypes.map((e) => {
return (
<IconWithTooltip
key={room.id.toString() + e.bedTypeIcon}
tooltipText={e.bedTypeName}
label={e.amount.toString()}
>
<Icon icon={e.bedTypeIcon} height="auto" />
</IconWithTooltip>
);
});
const photoAspectRationClassName = "aspect-" + varPhotoAspect;
return (
<Card key={room.id} className={cn(className, "relative", "py-0")}>
{/* <CardHeader className="p-0 m-0 mb-5">
</CardHeader> */}
<CardContent className="flex h-full w-full flex-col p-0">
<div className="">
<img
src={getRoomMainPhoto()}
className={
photoAspectRationClassName + " w-full rounded-t-md object-cover"
}
></img>
<Separator className="my-0 border-2" />
</div>
<div>
<Typography variant={"h2"} as="h2" className="border-none px-4 pt-4">
{room.name}
</Typography>
</div>
<div>
<Typography variant={"p"} as="h2" className="px-5">
{room.description}
</Typography>
</div>
<div className="mt-auto pb-4">
<Separator className="my-4" />
<div className="flex justify-around">
<div className="flex flex-row gap-2">{bedTypeIconList}</div>
<div className="flex flex-row">
<IconWithTooltip
tooltipText="Max. gests"
label={room.maxGuestNum?.toString()}
labelPosition={"right"}
>
<UserIcon />
</IconWithTooltip>
</div>
</div>
</div>
</CardContent>
</Card>
);
}
+152
View File
@@ -0,0 +1,152 @@
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 { useState } from "react";
import { SearchFilter } from "@/model/InternalTypes";
import { DateRange } from "react-day-picker";
import { isValidSearchFilter } from "@/utils/utils";
import { useNavigate } from "react-router";
import { ConstsNav, ConstsTexts } from "@/utils/Consts";
import { ContactUsDialog } from "../Dialogs/ContactUsDialog";
import { useCheckForNightCount } from "@/utils/hooks";
type funOnSearchClick = (newFilter: SearchFilter) => void;
export function SearchFilterCard({
onSearchClick,
initialsearchFilter,
}: {
onSearchClick?: funOnSearchClick;
initialsearchFilter?: SearchFilter;
}) {
//Local Filter state.
const [searchFilter, setSearchFilter] = useState<SearchFilter | null>(
initialsearchFilter ?? null,
);
const [errorMsg, setErrorMsg] = useState<string | null>(null);
const [isContactDialogOpen, setIsContactDialogOpen] =
useState<boolean>(false);
const {
isLoading: isNightCountLoading,
isOverApiMax: nightCountCheckIsOverApi,
shouldShowContactDialog: nightCountShowDialog,
} = useCheckForNightCount(searchFilter);
const navigate = useNavigate();
// Validate and call callback on btSearch click.
const btSearchClick = () => {
if (!isValidSearchFilter(searchFilter)) {
setErrorMsg("Select a valid 'from' and 'to' dates!");
return;
}
//Check for max night count.
//API Config vars values must be loaded before this! Unexpected behaviours may happen otherwise.
if (nightCountCheckIsOverApi) {
//Navigate to contact page and show info.
navigate(ConstsNav.page_Contact, {
state: ConstsTexts.navToContact_maxAllowedNightCount,
});
return;
}
if (nightCountShowDialog) {
//Show Alert dialog.
setIsContactDialogOpen(true);
//Page onSearch action will be executed based on the dialog result.
return;
}
//Execute page onSearch action.
if (onSearchClick) {
onSearchClick(searchFilter);
}
};
// Handle internal Searchfilter updates.
const updateDateRange = (newRange: DateRange) => {
const newSearchFilter = {
...searchFilter,
dateRange: newRange,
};
setSearchFilter(newSearchFilter);
if (isValidSearchFilter(newSearchFilter)) {
setErrorMsg(null);
}
};
const onContactDialogClose = () => {
setIsContactDialogOpen(false);
if (!isValidSearchFilter(searchFilter)) {
return;
}
if (onSearchClick) {
onSearchClick(searchFilter);
}
};
const isSearchButtonDisabled = isNightCountLoading;
const datePickerElement =
searchFilter == null ? (
<DatePickerWithRange
updateDateRange={updateDateRange}
allowPast={false}
></DatePickerWithRange>
) : (
<DatePickerWithRange
updateDateRange={updateDateRange}
allowPast={false}
startDate={searchFilter.dateRange.from}
endDate={searchFilter.dateRange.to}
></DatePickerWithRange>
);
const errorMsgLabel = (
<Typography variant={"errorText"} className="mt-2 text-lg">
{errorMsg}
</Typography>
);
const searchHasErrors = errorMsg != null;
return (
<>
<ContactUsDialog
isOpen={isContactDialogOpen}
onCancelClick={onContactDialogClose}
cancelButtonText="Continue Search"
/>
<Card>
<CardHeader className="m-0 mb-5 p-0">
<Typography variant={"h2"} as="h1" className="mx-5 py-2">
Reserva ahora
</Typography>
</CardHeader>
<CardContent>
{datePickerElement}
{searchHasErrors && errorMsgLabel}
<Separator className="my-4" />
<Button
size={"lg"}
onClick={btSearchClick}
disabled={isSearchButtonDisabled}
variant={searchHasErrors ? "destructive" : "default"}
>
<SearchIcon className="me-2 text-primary-foreground" />
<Typography variant={"h3"} className="text-primary-foreground">
Buscar
</Typography>
</Button>
</CardContent>
</Card>
</>
);
}
+130
View File
@@ -0,0 +1,130 @@
import { Separator } from "./ui/separator";
import { Typography } from "./ui/typography";
import { eConfigVarKeys } from "@/model/ConfigVar";
import {
c_sominaRooms_webpage,
c_somniaRooms_notice_text,
} from "@/utils/Consts";
import { Skeleton } from "./ui/skeleton";
import { Mail, Phone } from "lucide-react";
import { Link } from "react-router";
import { useConfigVariable } from "@/utils/apiHooks";
function AppFooter() {
const { value: varCompanyLogo, isLoading: isLogoLoading } = useConfigVariable(
eConfigVarKeys.varCompanyLogo,
"public/SR2.svg",
);
const { value: varCompanyLogoSize, isLoading: isLogoSizeLoading } =
useConfigVariable(eConfigVarKeys.varCompanyLogoSize, "64px");
const { value: varCompanyName, isLoading: isNameLoading } = useConfigVariable(
eConfigVarKeys.varCompanyName,
"Somnia Rooms",
);
const { value: varCompanyAddress, isLoading: isAddressLoading } =
useConfigVariable(eConfigVarKeys.varCompanyAddress, "");
const { value: varCompanyPhone, isLoading: isPhoneLoading } =
useConfigVariable(eConfigVarKeys.varCompanyPhone, "");
const { value: varCompanyMail, isLoading: isMailLoading } = useConfigVariable(
eConfigVarKeys.varCompanyEmail,
"",
);
const logoSizeClass = "w-[" + varCompanyLogoSize + "]";
const isLoading =
isLogoLoading ||
isLogoSizeLoading ||
isNameLoading ||
isAddressLoading ||
isPhoneLoading ||
isMailLoading;
const getCompanyElement = () => {
if (isLoading) {
return <Skeleton className="h-16" />;
}
return (
<>
<img
src={varCompanyLogo}
alt="company-logo"
className={logoSizeClass}
/>
<div>
<Typography variant={"p_inline"} className="text-nowrap">
{varCompanyName} - &copy; {new Date().getUTCFullYear()}
</Typography>
<Typography variant={"p_inline"}>{varCompanyAddress}</Typography>
</div>
</>
);
};
const getContactElement = () => {
if (isLoading) {
return <Skeleton className="w-16" />;
}
return (
<>
<li className="flex items-center gap-2">
<Phone size={"1.2em"} />
<Typography variant={"p_inline"}>{varCompanyPhone}</Typography>
</li>
<li className="flex items-center gap-2">
<Mail size={"1.2em"} />
<Typography variant={"p_inline"}>{varCompanyMail}</Typography>
</li>
</>
);
};
return (
<footer className="w-full p-8 pt-0">
<Separator className="my-4" />
<div className="flex flex-row flex-wrap items-center justify-center gap-x-12 gap-y-6 text-center lg:justify-between">
<div className="flex flex-row items-center gap-2">
{getCompanyElement()}
</div>
<ul className="flex flex-wrap items-start gap-x-10 gap-y-2 px-4 py-4">
<li>
<ul className="text-start">
<li>
<Typography variant={"largeText"} className="text-start">
Legal
</Typography>
</li>
<li>
<Typography asChild className="hover:text-blue-500">
<Link to={"terms"}>Terms and conditions</Link>
</Typography>
</li>
<li>
<Typography asChild className="hover:text-blue-500">
<Link to={"privacy"}>Privacy policy</Link>
</Typography>
</li>
</ul>
</li>
<li>
<ul>
<li>
<Typography variant={"largeText"} className="text-start">
Contact Us
</Typography>
</li>
{getContactElement()}
</ul>
</li>
</ul>
</div>
<Separator className="my-4" />
<Typography className="text-center" variant={"mutedText"}>
<a href={c_sominaRooms_webpage}>{c_somniaRooms_notice_text}</a>
</Typography>
</footer>
);
}
export default AppFooter;
+81
View File
@@ -0,0 +1,81 @@
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";
import { Bed, BookAIcon, HomeIcon } from "lucide-react";
import { eConfigVarKeys } from "@/model/ConfigVar";
import { Skeleton } from "./ui/skeleton";
import { useConfigVariable } from "@/utils/apiHooks";
function AppHeader() {
const { value: varCompanyLogo, isLoading: isLogoLoading } = useConfigVariable(
eConfigVarKeys.varCompanyLogo,
"public/SR2.svg",
);
const { value: varCompanyLogoSize, isLoading: isLogoSizeLoading } =
useConfigVariable(eConfigVarKeys.varCompanyLogoSize, "64px");
const { value: varCompanyName, isLoading: isNameLoading } = useConfigVariable(
eConfigVarKeys.varCompanyName,
"Somnia Rooms",
);
const { value: varCompanyWeb, isLoading: isWebLoading } = useConfigVariable(
eConfigVarKeys.varCompanyWebsite,
"#",
);
const isLoading =
isLogoLoading || isNameLoading || isWebLoading || isLogoSizeLoading;
const getElementLogo = () => {
if (isLoading) {
return <Skeleton className="w-16" />;
}
const logoSizeClass = "w-[" + varCompanyLogoSize + "]";
return (
<div className="relative flex flex-row items-center gap-2">
<img src={varCompanyLogo} className={logoSizeClass}></img>
<Typography variant={"largeText"} className="text-nowrap">
{varCompanyName}
</Typography>
<a href={varCompanyWeb} className="absolute h-full w-full"></a>
</div>
);
};
return (
<header>
<Card className="mx-10 my-4 items-center py-0">
<CardContent className="w-full py-2">
<div className="flex flex-col items-center justify-around gap-y-3 md:flex-row">
{getElementLogo()}
<div className="flex flex-row items-center">
<Link to={`home`}>
<Button variant="ghost" className="h-15 hover:cursor-pointer">
<HomeIcon className="mx-auto" />
Home
</Button>
</Link>
<Link to={`search`}>
<Button variant="ghost" className="h-15 hover:cursor-pointer">
<BookAIcon className="mx-auto" />
Reservar
</Button>
</Link>
<Link to={`home`}>
<Button variant="ghost" className="h-15 hover:cursor-pointer">
<Bed className="mx-auto" />
Mi reserva
</Button>
</Link>
</div>
<ModeToggle />
</div>
</CardContent>
</Card>
</header>
);
}
export default AppHeader;
@@ -0,0 +1,23 @@
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;
+174
View File
@@ -0,0 +1,174 @@
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 { Button } from "../ui/button";
import { useAPIRoomCategoryList } from "@/api/api-roomCategories";
import { IconWithTooltip } from "../ui/icon-number-tooltip";
import { UserIcon } from "lucide-react";
import { useCheckForGuestNumber } from "@/utils/hooks";
import { useState } from "react";
import { useNavigate } from "react-router";
import { ConstsNav, ConstsTexts } from "@/utils/Consts";
import { ContactUsDialog } from "../Dialogs/ContactUsDialog";
type OnBookingClickFunction = () => void;
type BookingDetailsModes = "Book" | "View";
export function BookingDetails({
onBookingConfirm,
mode,
}: {
onBookingConfirm?: OnBookingClickFunction;
mode: BookingDetailsModes;
}) {
const [isContactDialogOpen, setIsContactDialogOpen] =
useState<boolean>(false);
const bookingData = useAppStore((state) => state.currentBooking);
const { roomCategoryList } = useAPIRoomCategoryList();
const navigate = useNavigate();
const {
isLoading: isGuestNumberCheckLoading,
isOverApiMax: guestNumberCheckIsOverApi,
shouldShowContactDialog: guestNumberShowDialog,
} = useCheckForGuestNumber(bookingData);
const onBtBookingClick = () => {
//Check for Guest Number limits.
//API Config vars values must be loaded before this! Unexpected behaviours may happen otherwise.
if (guestNumberCheckIsOverApi) {
//Navigate to contact page and show info.
navigate(ConstsNav.page_Contact, {
state: ConstsTexts.navToContact_maxAllowedGuestNumber,
});
return;
}
if (guestNumberShowDialog) {
//Show Alert dialog.
setIsContactDialogOpen(true);
//Page onSearch action will be executed based on the dialog result.
return;
}
if (onBookingConfirm) {
onBookingConfirm();
}
};
const onContactDialogClose = () => {
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) => {
const category = roomCategoryList?.find((c) => c.id == room.roomCategory);
const photo = category?.roomCategoryPhotos.at(0);
return (
<Card
key={room.roomCategory.toString() + room.guestNumber.toString()}
className="my-3 flex flex-row bg-accent py-0"
>
{photo && (
<img
src={photo.path}
className="max-w-[30%] rounded-s-xl object-cover"
/>
)}
<div className="w-full p-3">
<Typography variant={"h3"} as="h3" className="m-2 text-center">
{category?.name}
</Typography>
<div className="flex w-full flex-row justify-around">
<IconWithTooltip
label={room.guestNumber.toString()}
labelPosition={"right"}
tooltipText={"Guest Number"}
>
<UserIcon />
</IconWithTooltip>
<Typography variant={"largeText"}>
{room.amount} x {room.price / 100}€
</Typography>
<Typography variant={"largeText"}>
{(room.amount * room.price) / 100}€
</Typography>
</div>
</div>
</Card>
);
});
const totalPrice = bookingData.rooms.reduce(
(acc, room) => acc + room.price * room.amount,
0,
);
return (
<>
<ContactUsDialog
isOpen={isContactDialogOpen}
cancelButtonText="Continue booking"
onCancelClick={onContactDialogClose}
/>
<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>
<div className="">{roomList}</div>
<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}
disabled={isGuestNumberCheckLoading}
>
<Typography
variant={"largeText"}
className="text-primary-foreground"
>
Book it!
</Typography>
</Button>
)}
</CardContent>
</Card>
</>
);
}
+40
View File
@@ -0,0 +1,40 @@
import { MonitorIcon, MoonIcon, SunIcon } from "lucide-react";
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>
<Button variant="outline" size="icon">
<SunIcon className="h-[1.2rem] w-[1.2rem] scale-100 rotate-0 transition-all dark:scale-0 dark:-rotate-90" />
<MoonIcon className="absolute h-[1.2rem] w-[1.2rem] scale-0 rotate-90 transition-all dark:scale-100 dark:rotate-0" />
<span className="sr-only">Toggle theme</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => setTheme("light")}>
<SunIcon className="h-[1.2rem] w-[1.2rem] scale-100" />
Light
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("dark")}>
<MoonIcon className="h-[1.2rem] w-[1.2rem] scale-100" />
Dark
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("system")}>
<MonitorIcon className="h-[1.2rem] w-[1.2rem] scale-100" />
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;
};
+155
View File
@@ -0,0 +1,155 @@
import * as React from "react";
import { AlertDialog as AlertDialogPrimitive } from "radix-ui";
import { cn } from "@/lib/utils";
import { buttonVariants } from "@/components/ui/button";
function AlertDialog({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />;
}
function AlertDialogTrigger({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
return (
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
);
}
function AlertDialogPortal({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
return (
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
);
}
function AlertDialogOverlay({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
return (
<AlertDialogPrimitive.Overlay
data-slot="alert-dialog-overlay"
className={cn(
"fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",
className,
)}
{...props}
/>
);
}
function AlertDialogContent({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
data-slot="alert-dialog-content"
className={cn(
"fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",
className,
)}
{...props}
/>
</AlertDialogPortal>
);
}
function AlertDialogHeader({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
);
}
function AlertDialogFooter({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className,
)}
{...props}
/>
);
}
function AlertDialogTitle({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
return (
<AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
className={cn("text-lg font-semibold", className)}
{...props}
/>
);
}
function AlertDialogDescription({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
return (
<AlertDialogPrimitive.Description
data-slot="alert-dialog-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
);
}
function AlertDialogAction({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
return (
<AlertDialogPrimitive.Action
className={cn(buttonVariants(), className)}
{...props}
/>
);
}
function AlertDialogCancel({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
return (
<AlertDialogPrimitive.Cancel
className={cn(buttonVariants({ variant: "outline" }), className)}
{...props}
/>
);
}
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
};
+63
View File
@@ -0,0 +1,63 @@
import * as React from "react";
import { Slot as SlotPrimitive } from "radix-ui";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9",
"icon-sm": "size-8",
"icon-lg": "size-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
);
function Button({
className,
variant = "default",
size = "default",
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean;
}) {
const Comp = asChild ? SlotPrimitive.Slot : "button";
return (
<Comp
data-slot="button"
data-variant={variant}
data-size={size}
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
);
}
// eslint-disable-next-line react-refresh/only-export-components
export { Button, buttonVariants };
+218
View File
@@ -0,0 +1,218 @@
import * as React from "react";
import {
ChevronDownIcon,
ChevronLeftIcon,
ChevronRightIcon,
} from "lucide-react";
import {
DayPicker,
getDefaultClassNames,
type DayButton,
} from "react-day-picker";
import { cn } from "@/lib/utils";
import { Button, buttonVariants } from "@/components/ui/button";
function Calendar({
className,
classNames,
showOutsideDays = true,
captionLayout = "label",
buttonVariant = "ghost",
formatters,
components,
...props
}: React.ComponentProps<typeof DayPicker> & {
buttonVariant?: React.ComponentProps<typeof Button>["variant"];
}) {
const defaultClassNames = getDefaultClassNames();
return (
<DayPicker
showOutsideDays={showOutsideDays}
className={cn(
"group/calendar bg-background p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
className,
)}
captionLayout={captionLayout}
formatters={{
formatMonthDropdown: (date) =>
date.toLocaleString("default", { month: "short" }),
...formatters,
}}
classNames={{
root: cn("w-fit", defaultClassNames.root),
months: cn(
"flex gap-4 flex-col md:flex-row relative",
defaultClassNames.months,
),
month: cn("flex flex-col w-full gap-4", defaultClassNames.month),
nav: cn(
"flex items-center gap-1 w-full absolute top-0 inset-x-0 justify-between",
defaultClassNames.nav,
),
button_previous: cn(
buttonVariants({ variant: buttonVariant }),
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
defaultClassNames.button_previous,
),
button_next: cn(
buttonVariants({ variant: buttonVariant }),
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
defaultClassNames.button_next,
),
month_caption: cn(
"flex items-center justify-center h-(--cell-size) w-full px-(--cell-size)",
defaultClassNames.month_caption,
),
dropdowns: cn(
"w-full flex items-center text-sm font-medium justify-center h-(--cell-size) gap-1.5",
defaultClassNames.dropdowns,
),
dropdown_root: cn(
"relative has-focus:border-ring border border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] rounded-md",
defaultClassNames.dropdown_root,
),
dropdown: cn(
"absolute bg-popover inset-0 opacity-0",
defaultClassNames.dropdown,
),
caption_label: cn(
"select-none font-medium",
captionLayout === "label"
? "text-sm"
: "rounded-md pl-2 pr-1 flex items-center gap-1 text-sm h-8 [&>svg]:text-muted-foreground [&>svg]:size-3.5",
defaultClassNames.caption_label,
),
table: "w-full border-collapse",
weekdays: cn("flex", defaultClassNames.weekdays),
weekday: cn(
"text-muted-foreground rounded-md flex-1 font-normal text-[0.8rem] select-none",
defaultClassNames.weekday,
),
week: cn("flex w-full mt-2", defaultClassNames.week),
week_number_header: cn(
"select-none w-(--cell-size)",
defaultClassNames.week_number_header,
),
week_number: cn(
"text-[0.8rem] select-none text-muted-foreground",
defaultClassNames.week_number,
),
day: cn(
"relative w-full h-full p-0 text-center [&:last-child[data-selected=true]_button]:rounded-r-md group/day aspect-square select-none",
props.showWeekNumber
? "[&:nth-child(2)[data-selected=true]_button]:rounded-l-md"
: "[&:first-child[data-selected=true]_button]:rounded-l-md",
defaultClassNames.day,
),
range_start: cn(
"rounded-l-md bg-accent",
defaultClassNames.range_start,
),
range_middle: cn("rounded-none", defaultClassNames.range_middle),
range_end: cn("rounded-r-md bg-accent", defaultClassNames.range_end),
today: cn(
"bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",
defaultClassNames.today,
),
outside: cn(
"text-muted-foreground aria-selected:text-muted-foreground",
defaultClassNames.outside,
),
disabled: cn(
"text-muted-foreground opacity-50",
defaultClassNames.disabled,
),
hidden: cn("invisible", defaultClassNames.hidden),
...classNames,
}}
components={{
Root: ({ className, rootRef, ...props }) => {
return (
<div
data-slot="calendar"
ref={rootRef}
className={cn(className)}
{...props}
/>
);
},
Chevron: ({ className, orientation, ...props }) => {
if (orientation === "left") {
return (
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
);
}
if (orientation === "right") {
return (
<ChevronRightIcon
className={cn("size-4", className)}
{...props}
/>
);
}
return (
<ChevronDownIcon className={cn("size-4", className)} {...props} />
);
},
DayButton: CalendarDayButton,
WeekNumber: ({ children, ...props }) => {
return (
<td {...props}>
<div className="flex size-(--cell-size) items-center justify-center text-center">
{children}
</div>
</td>
);
},
...components,
}}
{...props}
/>
);
}
function CalendarDayButton({
className,
day,
modifiers,
...props
}: React.ComponentProps<typeof DayButton>) {
const defaultClassNames = getDefaultClassNames();
const ref = React.useRef<HTMLButtonElement>(null);
React.useEffect(() => {
if (modifiers.focused) ref.current?.focus();
}, [modifiers.focused]);
return (
<Button
ref={ref}
variant="ghost"
size="icon"
data-day={day.date.toLocaleDateString()}
data-selected-single={
modifiers.selected &&
!modifiers.range_start &&
!modifiers.range_end &&
!modifiers.range_middle
}
data-range-start={modifiers.range_start}
data-range-end={modifiers.range_end}
data-range-middle={modifiers.range_middle}
className={cn(
"flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-[3px] group-data-[focused=true]/day:ring-ring/50 data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground data-[range-middle=true]:rounded-none data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground dark:hover:text-accent-foreground [&>span]:text-xs [&>span]:opacity-70",
defaultClassNames.day,
className,
)}
{...props}
/>
);
}
export { Calendar, CalendarDayButton };
+92
View File
@@ -0,0 +1,92 @@
import * as React from "react";
import { cn } from "@/lib/utils";
function Card({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card"
className={cn(
"flex flex-col gap-6 rounded-xl border bg-card py-6 text-card-foreground shadow-sm",
className,
)}
{...props}
/>
);
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
className,
)}
{...props}
/>
);
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn("leading-none font-semibold", className)}
{...props}
/>
);
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
);
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className,
)}
{...props}
/>
);
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-6", className)}
{...props}
/>
);
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
{...props}
/>
);
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
};
+239
View File
@@ -0,0 +1,239 @@
import * as React from "react";
import useEmblaCarousel, {
type UseEmblaCarouselType,
} from "embla-carousel-react";
import { ArrowLeft, ArrowRight } from "lucide-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;
}
function Carousel({
orientation = "horizontal",
opts,
setApi,
plugins,
className,
children,
...props
}: React.ComponentProps<"div"> & CarouselProps) {
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
onKeyDownCapture={handleKeyDown}
className={cn("relative", className)}
role="region"
aria-roledescription="carousel"
data-slot="carousel"
{...props}
>
{children}
</div>
</CarouselContext.Provider>
);
}
function CarouselContent({ className, ...props }: React.ComponentProps<"div">) {
const { carouselRef, orientation } = useCarousel();
return (
<div
ref={carouselRef}
className="overflow-hidden"
data-slot="carousel-content"
>
<div
className={cn(
"flex",
orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
className,
)}
{...props}
/>
</div>
);
}
function CarouselItem({ className, ...props }: React.ComponentProps<"div">) {
const { orientation } = useCarousel();
return (
<div
role="group"
aria-roledescription="slide"
data-slot="carousel-item"
className={cn(
"min-w-0 shrink-0 grow-0 basis-full",
orientation === "horizontal" ? "pl-4" : "pt-4",
className,
)}
{...props}
/>
);
}
function CarouselPrevious({
className,
variant = "outline",
size = "icon",
...props
}: React.ComponentProps<typeof Button>) {
const { orientation, scrollPrev, canScrollPrev } = useCarousel();
return (
<Button
data-slot="carousel-previous"
variant={variant}
size={size}
className={cn(
"absolute size-8 rounded-full",
orientation === "horizontal"
? "top-1/2 -left-12 -translate-y-1/2"
: "-top-12 left-1/2 -translate-x-1/2 rotate-90",
className,
)}
disabled={!canScrollPrev}
onClick={scrollPrev}
{...props}
>
<ArrowLeft />
<span className="sr-only">Previous slide</span>
</Button>
);
}
function CarouselNext({
className,
variant = "outline",
size = "icon",
...props
}: React.ComponentProps<typeof Button>) {
const { orientation, scrollNext, canScrollNext } = useCarousel();
return (
<Button
data-slot="carousel-next"
variant={variant}
size={size}
className={cn(
"absolute size-8 rounded-full",
orientation === "horizontal"
? "top-1/2 -right-12 -translate-y-1/2"
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
className,
)}
disabled={!canScrollNext}
onClick={scrollNext}
{...props}
>
<ArrowRight />
<span className="sr-only">Next slide</span>
</Button>
);
}
export {
type CarouselApi,
Carousel,
CarouselContent,
CarouselItem,
CarouselPrevious,
CarouselNext,
};
+30
View File
@@ -0,0 +1,30 @@
import * as React from "react";
import { Checkbox as CheckboxPrimitive } from "radix-ui";
import { CheckIcon } from "lucide-react";
import { cn } from "@/lib/utils";
function Checkbox({
className,
...props
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
return (
<CheckboxPrimitive.Root
data-slot="checkbox"
className={cn(
"peer size-4 shrink-0 rounded-[4px] border border-input shadow-xs transition-shadow outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[state=checked]:border-primary data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:bg-input/30 dark:aria-invalid:ring-destructive/40 dark:data-[state=checked]:bg-primary",
className,
)}
{...props}
>
<CheckboxPrimitive.Indicator
data-slot="checkbox-indicator"
className="grid place-content-center text-current transition-none"
>
<CheckIcon className="size-3.5" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
);
}
export { Checkbox };
+144
View File
@@ -0,0 +1,144 @@
"use client";
import * as React from "react";
import { format } from "date-fns";
import { DateBefore, DateRange, Matcher, Modifiers } 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";
import { CalendarIcon } from "lucide-react";
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: Modifiers) => {
const newDateRange: DateRange = {
from: mods.selected ? undefined : day,
to: undefined,
};
fnUpdateRange(newDateRange);
};
const handleDayClickTo = (day: Date, mods: Modifiers) => {
const newDateRange: DateRange = {
from: dateRange?.from,
to: mods.selected ? undefined : day,
};
fnUpdateRange(newDateRange);
};
const fnUpdateRange = (range: DateRange) => {
setDateRange(range);
if (updateDateRange !== undefined) {
updateDateRange(range);
}
};
// 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 grid-cols-2 grid-rows-2 gap-x-2", className)}>
<Typography variant={"largeText"} as="p">
Desde
</Typography>
<Typography variant={"largeText"} as="p">
Hasta
</Typography>
<Popover>
<PopoverTrigger>
<Button
id="dateFrom"
variant="outline"
data-empty={!dateRange}
className="w-full justify-start text-left font-normal data-[empty=true]:text-muted-foreground"
>
<CalendarIcon />
{dateRange?.from ? (
format(dateRange.from, "PPP")
) : (
<span>Pick a date</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="center">
<Calendar
mode="single"
defaultMonth={dateRange?.from}
selected={dateRange?.from}
onDayClick={handleDayClickFrom}
numberOfMonths={1}
disabled={pastMatcher}
/>
</PopoverContent>
</Popover>
<Popover>
<PopoverTrigger>
<Button
id="dateTo"
variant={"outline"}
data-empty={!dateRange}
className="w-full justify-start text-left font-normal data-[empty=true]:text-muted-foreground"
>
<CalendarIcon className="mr-2 h-4 w-4" />
{dateRange?.to ? (
format(dateRange.to, "PPP")
) : (
<span>Pick a date</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="center">
<Calendar
autoFocus
mode="single"
defaultMonth={dateRange?.to ?? dateRange?.from}
selected={dateRange?.to}
onDayClick={handleDayClickTo}
numberOfMonths={1}
disabled={beforeAndSelected}
/>
</PopoverContent>
</Popover>
</div>
);
}
+255
View File
@@ -0,0 +1,255 @@
import * as React from "react";
import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui";
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
import { cn } from "@/lib/utils";
function DropdownMenu({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />;
}
function DropdownMenuPortal({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
return (
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
);
}
function DropdownMenuTrigger({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
return (
<DropdownMenuPrimitive.Trigger
data-slot="dropdown-menu-trigger"
{...props}
/>
);
}
function DropdownMenuContent({
className,
sideOffset = 4,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
return (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
className={cn(
"z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md 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 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
className,
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
);
}
function DropdownMenuGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
return (
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
);
}
function DropdownMenuItem({
className,
inset,
variant = "default",
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean;
variant?: "default" | "destructive";
}) {
return (
<DropdownMenuPrimitive.Item
data-slot="dropdown-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:!text-destructive",
className,
)}
{...props}
/>
);
}
function DropdownMenuCheckboxItem({
className,
children,
checked,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
return (
<DropdownMenuPrimitive.CheckboxItem
data-slot="dropdown-menu-checkbox-item"
className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
checked={checked}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
);
}
function DropdownMenuRadioGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
return (
<DropdownMenuPrimitive.RadioGroup
data-slot="dropdown-menu-radio-group"
{...props}
/>
);
}
function DropdownMenuRadioItem({
className,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
return (
<DropdownMenuPrimitive.RadioItem
data-slot="dropdown-menu-radio-item"
className={cn(
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
)}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
);
}
function DropdownMenuLabel({
className,
inset,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean;
}) {
return (
<DropdownMenuPrimitive.Label
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn(
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
className,
)}
{...props}
/>
);
}
function DropdownMenuSeparator({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
return (
<DropdownMenuPrimitive.Separator
data-slot="dropdown-menu-separator"
className={cn("-mx-1 my-1 h-px bg-border", className)}
{...props}
/>
);
}
function DropdownMenuShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground",
className,
)}
{...props}
/>
);
}
function DropdownMenuSub({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />;
}
function DropdownMenuSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean;
}) {
return (
<DropdownMenuPrimitive.SubTrigger
data-slot="dropdown-menu-sub-trigger"
data-inset={inset}
className={cn(
"flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[inset]:pl-8 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
className,
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto size-4" />
</DropdownMenuPrimitive.SubTrigger>
);
}
function DropdownMenuSubContent({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
return (
<DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content"
className={cn(
"z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg 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 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
className,
)}
{...props}
/>
);
}
export {
DropdownMenu,
DropdownMenuPortal,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
};
+246
View File
@@ -0,0 +1,246 @@
import { useMemo } from "react";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) {
return (
<fieldset
data-slot="field-set"
className={cn(
"flex flex-col gap-6",
"has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",
className,
)}
{...props}
/>
);
}
function FieldLegend({
className,
variant = "legend",
...props
}: React.ComponentProps<"legend"> & { variant?: "legend" | "label" }) {
return (
<legend
data-slot="field-legend"
data-variant={variant}
className={cn(
"mb-3 font-medium",
"data-[variant=legend]:text-base",
"data-[variant=label]:text-sm",
className,
)}
{...props}
/>
);
}
function FieldGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-group"
className={cn(
"group/field-group @container/field-group flex w-full flex-col gap-7 data-[slot=checkbox-group]:gap-3 [&>[data-slot=field-group]]:gap-4",
className,
)}
{...props}
/>
);
}
const fieldVariants = cva(
"group/field flex w-full gap-3 data-[invalid=true]:text-destructive",
{
variants: {
orientation: {
vertical: ["flex-col [&>*]:w-full [&>.sr-only]:w-auto"],
horizontal: [
"flex-row items-center",
"[&>[data-slot=field-label]]:flex-auto",
"has-[>[data-slot=field-content]]:items-start has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
],
responsive: [
"flex-col [&>*]:w-full [&>.sr-only]:w-auto @md/field-group:flex-row @md/field-group:items-center @md/field-group:[&>*]:w-auto",
"@md/field-group:[&>[data-slot=field-label]]:flex-auto",
"@md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
],
},
},
defaultVariants: {
orientation: "vertical",
},
},
);
function Field({
className,
orientation = "vertical",
...props
}: React.ComponentProps<"div"> & VariantProps<typeof fieldVariants>) {
return (
<div
role="group"
data-slot="field"
data-orientation={orientation}
className={cn(fieldVariants({ orientation }), className)}
{...props}
/>
);
}
function FieldContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-content"
className={cn(
"group/field-content flex flex-1 flex-col gap-1.5 leading-snug",
className,
)}
{...props}
/>
);
}
function FieldLabel({
className,
...props
}: React.ComponentProps<typeof Label>) {
return (
<Label
data-slot="field-label"
className={cn(
"group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50",
"has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col has-[>[data-slot=field]]:rounded-md has-[>[data-slot=field]]:border [&>*]:data-[slot=field]:p-4",
"has-data-[state=checked]:border-primary has-data-[state=checked]:bg-primary/5 dark:has-data-[state=checked]:bg-primary/10",
className,
)}
{...props}
/>
);
}
function FieldTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-label"
className={cn(
"flex w-fit items-center gap-2 text-sm leading-snug font-medium group-data-[disabled=true]/field:opacity-50",
className,
)}
{...props}
/>
);
}
function FieldDescription({ className, ...props }: React.ComponentProps<"p">) {
return (
<p
data-slot="field-description"
className={cn(
"text-sm leading-normal font-normal text-muted-foreground group-has-[[data-orientation=horizontal]]/field:text-balance",
"last:mt-0 nth-last-2:-mt-1 [[data-variant=legend]+&]:-mt-1.5",
"[&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",
className,
)}
{...props}
/>
);
}
function FieldSeparator({
children,
className,
...props
}: React.ComponentProps<"div"> & {
children?: React.ReactNode;
}) {
return (
<div
data-slot="field-separator"
data-content={!!children}
className={cn(
"relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2",
className,
)}
{...props}
>
<Separator className="absolute inset-0 top-1/2" />
{children && (
<span
className="relative mx-auto block w-fit bg-background px-2 text-muted-foreground"
data-slot="field-separator-content"
>
{children}
</span>
)}
</div>
);
}
function FieldError({
className,
children,
errors,
...props
}: React.ComponentProps<"div"> & {
errors?: Array<{ message?: string } | undefined>;
}) {
const content = useMemo(() => {
if (children) {
return children;
}
if (!errors?.length) {
return null;
}
const uniqueErrors = [
...new Map(errors.map((error) => [error?.message, error])).values(),
];
if (uniqueErrors?.length == 1) {
return uniqueErrors[0]?.message;
}
return (
<ul className="ml-4 flex list-disc flex-col gap-1">
{uniqueErrors.map(
(error, index) =>
error?.message && <li key={index}>{error.message}</li>,
)}
</ul>
);
}, [children, errors]);
if (!content) {
return null;
}
return (
<div
role="alert"
data-slot="field-error"
className={cn("text-sm font-normal text-destructive", className)}
{...props}
>
{content}
</div>
);
}
export {
Field,
FieldLabel,
FieldDescription,
FieldError,
FieldGroup,
FieldLegend,
FieldSeparator,
FieldSet,
FieldContent,
FieldTitle,
};
+47
View File
@@ -0,0 +1,47 @@
import { Typography } from "./typography";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "./tooltip";
import { PropsWithChildren } from "react";
interface IconWithTooltipNumberProps {
label?: string | null | undefined;
labelPosition?: "left" | "right" | null | undefined;
tooltipText?: string | null | undefined;
}
export function IconWithTooltip({
label = undefined,
labelPosition = "left",
tooltipText = undefined,
children,
}: PropsWithChildren<IconWithTooltipNumberProps>) {
const iconElement = tooltipText ? (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>{children}</TooltipTrigger>
<TooltipContent>
<p className="inline">{tooltipText}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
) : (
<>{children}</>
);
const labelElement = (
<Typography variant={"p_inline"} className="px-1">
{label}
</Typography>
);
return (
<div className="flex flex-row items-center gap-1">
{label && labelPosition == "left" && labelElement}
{iconElement}
{label && labelPosition == "right" && labelElement}
</div>
);
}
+21
View File
@@ -0,0 +1,21 @@
import * as React from "react";
import { cn } from "@/lib/utils";
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
data-slot="input"
className={cn(
"h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30",
"focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",
"aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",
className,
)}
{...props}
/>
);
}
export { Input };
+22
View File
@@ -0,0 +1,22 @@
import * as React from "react";
import { Label as LabelPrimitive } from "radix-ui";
import { cn } from "@/lib/utils";
function Label({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className,
)}
{...props}
/>
);
}
export { Label };
+46
View File
@@ -0,0 +1,46 @@
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,
initialValue = 0,
}: {
updateCount: UpdateSelectedNumberFunction;
addEnabled?: boolean;
allowNegative?: boolean;
initialValue?: number;
}) {
const [count, setCount] = useState<number>(initialValue);
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>
);
}
+46
View File
@@ -0,0 +1,46 @@
import * as React from "react";
import { Popover as PopoverPrimitive } from "radix-ui";
import { cn } from "@/lib/utils";
function Popover({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
return <PopoverPrimitive.Root data-slot="popover" {...props} />;
}
function PopoverTrigger({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />;
}
function PopoverContent({
className,
align = "center",
sideOffset = 4,
...props
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
return (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
data-slot="popover-content"
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-hidden 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 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
className,
)}
{...props}
/>
</PopoverPrimitive.Portal>
);
}
function PopoverAnchor({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />;
}
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor };
+40
View File
@@ -0,0 +1,40 @@
import * as React from "react";
import { Separator as SeparatorPrimitive } from "radix-ui";
import { cn } from "@/lib/utils";
import { cva, VariantProps } from "class-variance-authority";
const separatorVariants = cva(
"shrink-0 bg-border data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
{
variants: {
variant: {
default: "my-10",
},
},
defaultVariants: {
variant: "default",
},
},
);
function Separator({
className,
variant,
orientation = "horizontal",
decorative = true,
...props
}: React.ComponentProps<typeof SeparatorPrimitive.Root> &
VariantProps<typeof separatorVariants>) {
return (
<SeparatorPrimitive.Root
data-slot="separator"
decorative={decorative}
orientation={orientation}
className={cn(separatorVariants({ variant, className }))}
{...props}
/>
);
}
export { Separator };
+13
View File
@@ -0,0 +1,13 @@
import { cn } from "@/lib/utils";
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="skeleton"
className={cn("animate-pulse rounded-md bg-accent", className)}
{...props}
/>
);
}
export { Skeleton };
+114
View File
@@ -0,0 +1,114 @@
import * as React from "react";
import { cn } from "@/lib/utils";
function Table({ className, ...props }: React.ComponentProps<"table">) {
return (
<div
data-slot="table-container"
className="relative w-full overflow-x-auto"
>
<table
data-slot="table"
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
);
}
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
return (
<thead
data-slot="table-header"
className={cn("[&_tr]:border-b", className)}
{...props}
/>
);
}
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
return (
<tbody
data-slot="table-body"
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
);
}
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
return (
<tfoot
data-slot="table-footer"
className={cn(
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
className,
)}
{...props}
/>
);
}
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
return (
<tr
data-slot="table-row"
className={cn(
"border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
className,
)}
{...props}
/>
);
}
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
return (
<th
data-slot="table-head"
className={cn(
"h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className,
)}
{...props}
/>
);
}
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
return (
<td
data-slot="table-cell"
className={cn(
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className,
)}
{...props}
/>
);
}
function TableCaption({
className,
...props
}: React.ComponentProps<"caption">) {
return (
<caption
data-slot="table-caption"
className={cn("mt-4 text-sm text-muted-foreground", className)}
{...props}
/>
);
}
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
};
+59
View File
@@ -0,0 +1,59 @@
import * as React from "react";
import { Tooltip as TooltipPrimitive } from "radix-ui";
import { cn } from "@/lib/utils";
function TooltipProvider({
delayDuration = 0,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
return (
<TooltipPrimitive.Provider
data-slot="tooltip-provider"
delayDuration={delayDuration}
{...props}
/>
);
}
function Tooltip({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
return (
<TooltipProvider>
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
</TooltipProvider>
);
}
function TooltipTrigger({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />;
}
function TooltipContent({
className,
sideOffset = 0,
children,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
return (
<TooltipPrimitive.Portal>
<TooltipPrimitive.Content
data-slot="tooltip-content"
sideOffset={sideOffset}
className={cn(
"z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 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 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",
className,
)}
{...props}
>
{children}
<TooltipPrimitive.Arrow className="z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground" />
</TooltipPrimitive.Content>
</TooltipPrimitive.Portal>
);
}
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };
+85
View File
@@ -0,0 +1,85 @@
"use client";
import * as React from "react";
import { VariantProps, cva } from "class-variance-authority";
import { cn } from "@/lib/utils";
import { Slot as SlotPrimitive } from "radix-ui";
const typographyVariants = cva("text-foreground", {
variants: {
variant: {
h1: "scroll-m-20 text-center text-4xl font-extrabold tracking-tight text-balance",
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:
"bg-muted relative rounded px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold",
lead: "text-muted-foreground text-xl",
largeText: "text-lg font-semibold",
smallText: "text-sm leading-none font-medium",
mutedText: "text-muted-foreground text-sm",
errorText: "text-destructive text-sm font-normal",
},
},
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",
errorText: "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
? SlotPrimitive.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 };
+224
View File
@@ -0,0 +1,224 @@
@import "tailwindcss";
@import "tw-animate-css";
@custom-variant dark (&:is(.dark *));
@theme inline {
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--color-chart-1: var(--chart-1);
--color-chart-2: var(--chart-2);
--color-chart-3: var(--chart-3);
--color-chart-4: var(--chart-4);
--color-chart-5: var(--chart-5);
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
}
:root {
--radius: 0.625rem;
--background: oklch(1 0 0);
--foreground: oklch(0.147 0.004 49.25);
--card: oklch(1 0 0);
--card-foreground: oklch(0.147 0.004 49.25);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.147 0.004 49.25);
--primary: oklch(0.216 0.006 56.043);
--primary-foreground: oklch(0.985 0.001 106.423);
--secondary: oklch(0.97 0.001 106.424);
--secondary-foreground: oklch(0.216 0.006 56.043);
--muted: oklch(0.97 0.001 106.424);
--muted-foreground: oklch(0.553 0.013 58.071);
--accent: oklch(0.97 0.001 106.424);
--accent-foreground: oklch(0.216 0.006 56.043);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.923 0.003 48.717);
--input: oklch(0.923 0.003 48.717);
--ring: oklch(0.709 0.01 56.259);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.985 0.001 106.423);
--sidebar-foreground: oklch(0.147 0.004 49.25);
--sidebar-primary: oklch(0.216 0.006 56.043);
--sidebar-primary-foreground: oklch(0.985 0.001 106.423);
--sidebar-accent: oklch(0.97 0.001 106.424);
--sidebar-accent-foreground: oklch(0.216 0.006 56.043);
--sidebar-border: oklch(0.923 0.003 48.717);
--sidebar-ring: oklch(0.709 0.01 56.259);
}
.dark {
--background: oklch(0.147 0.004 49.25);
--foreground: oklch(0.985 0.001 106.423);
--card: oklch(0.216 0.006 56.043);
--card-foreground: oklch(0.985 0.001 106.423);
--popover: oklch(0.216 0.006 56.043);
--popover-foreground: oklch(0.985 0.001 106.423);
--primary: oklch(0.923 0.003 48.717);
--primary-foreground: oklch(0.216 0.006 56.043);
--secondary: oklch(0.268 0.007 34.298);
--secondary-foreground: oklch(0.985 0.001 106.423);
--muted: oklch(0.268 0.007 34.298);
--muted-foreground: oklch(0.709 0.01 56.259);
--accent: oklch(0.268 0.007 34.298);
--accent-foreground: oklch(0.985 0.001 106.423);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.553 0.013 58.071);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.216 0.006 56.043);
--sidebar-foreground: oklch(0.985 0.001 106.423);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0.001 106.423);
--sidebar-accent: oklch(0.268 0.007 34.298);
--sidebar-accent-foreground: oklch(0.985 0.001 106.423);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.553 0.013 58.071);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
}
/* SomniaRooms Extended CSS */
@utility grid-cols-40/60 {
grid-template-columns: 40% 60%;
}
@utility grid-cols-60/40 {
grid-template-columns: 60% 40%;
}
+6
View File
@@ -0,0 +1,6 @@
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
+51
View File
@@ -0,0 +1,51 @@
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import { RouterProvider, createBrowserRouter } from "react-router";
import Root from "./routes/Root";
import ErrorPage from "./routes/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";
import ContactPage from "./routes/contact-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 />,
},
{
path: "/contact",
element: <ContactPage />,
},
],
},
]);
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>,
);
+24
View File
@@ -0,0 +1,24 @@
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;
};
+22
View File
@@ -0,0 +1,22 @@
export type ConfigVar = {
key: string;
value: string;
};
export enum eConfigVarKeys {
varCompanyName = "CompanyName",
varCompanyWebsite = "CompanyWebsite",
varCompanyContactFormUrl = "CompanyContactFormUrl",
varCompanyLogo = "CompanyLogo",
varCompanyLogoSize = "CompanyLogoSize",
varCompanyEmail = "CompanyEmail",
varCompanyPhone = "CompanyPhone",
varCompanyAddress = "CompanyAddress",
varNightCountForContactDialog = "NightCountForContactDialog",
varGuestNumberForContactDialog = "GuestNumberForContactDialog",
varShowNonAvailableRooms = "ShowNonAvailableRooms",
varSomniaAttributionNotice = "SomniaAttributionNotice",
varPhotoAspectRatio = "PhotoAspectRatio",
varAPIMaxAllowedNightAmount = "MaxAllowedNightAmount",
varAPIMaxAllowedGuestNumber = "MaxAllowedGuestNumber",
}
+10
View File
@@ -0,0 +1,10 @@
"use client";
import { z } from "zod";
export const BookingFormSchema = z.object({
name: z.string().min(2).max(50),
surname: z.string().min(2).max(50),
email: z.email(),
phone: z.string().min(8),
});
+5
View File
@@ -0,0 +1,5 @@
import { DateRange } from "react-day-picker";
export type SearchFilter = {
dateRange: DateRange;
};
+21
View File
@@ -0,0 +1,21 @@
export type RoomCategory = {
id: number;
name: string;
description: string | undefined;
maxGuestNum: number;
orderHomePage: number | undefined;
roomCategoryPhotos: RoomCategoryPhoto[];
roomCategoryBedTypes: RoomCategoryBedType[];
};
export type RoomCategoryPhoto = {
path: string;
altText: string | undefined;
photoOrder: string | undefined;
};
export type RoomCategoryBedType = {
amount: number;
bedTypeName: string;
bedTypeIcon: string;
};
+19
View File
@@ -0,0 +1,19 @@
export type RoomAvailabity = {
roomCategory: number;
availability: number;
};
export type RoomPrice = {
guestNumber: number;
price: number;
};
export type SearchPeriodRequest = {
startDate: string;
endDate: string;
};
export type RoomPriceSearchResponse = {
roomCategoryId: number;
prices: RoomPrice[];
};
File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 133 KiB

File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 96 KiB

+22
View File
@@ -0,0 +1,22 @@
html {
box-sizing: border-box;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
.appPage {
width: 80%;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
iconify-icon {
display: inline-block;
min-width: 1em;
min-height: 1em;
}
+21
View File
@@ -0,0 +1,21 @@
import { Outlet } from "react-router";
import "./Root.css";
import AppHeader from "../components/app-header";
import AppFooter from "../components/app-footer";
import { ThemeProvider } from "@/components/theme-provider";
function Root() {
return (
<>
<ThemeProvider defaultTheme="dark" storageKey="vite-ui-theme">
<AppHeader />
<div className="mx-auto min-h-screen w-full bg-background p-8 text-center text-foreground sm:w-[90%] md:w-[80%]">
<Outlet />
</div>
<AppFooter />
</ThemeProvider>
</>
);
}
export default Root;
+222
View File
@@ -0,0 +1,222 @@
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 { Separator } from "@/components/ui/separator";
import { Typography } from "@/components/ui/typography";
import { BookingFormSchema } from "@/model/FormSchema";
import { useAppStore } from "@/store";
import { useEffect, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { useNavigate } from "react-router";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { eBookingState } from "@/utils/AppStateManager";
import { useBookingStateDispacher } from "@/utils/hooks";
import { ConstsNav } from "@/utils/Consts";
import { NewBookingCustomerDetails } from "@/model/Bookings";
import {
Field,
FieldError,
FieldGroup,
FieldLabel,
FieldLegend,
FieldSet,
} from "@/components/ui/field";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
enum PageState {
showForm,
sending,
error,
}
function BookPage() {
const [pageState, setPageState] = useState<PageState>(PageState.showForm);
const bookingData = useAppStore((state) => state.currentBooking);
const appBookingState = useAppStore((state) => state.bookingState);
const setCustomerData = useAppStore(
(state) => state.currentBookingSetCustomer,
);
const navigate = useNavigate();
const { setBookingStateBooked } = useBookingStateDispacher();
const bookingFormId = "booking-form";
const bookingForm = useForm<z.infer<typeof BookingFormSchema>>({
resolver: zodResolver(BookingFormSchema),
defaultValues: {
email: "",
name: "",
surname: "",
phone: "",
},
});
//Redirect to home if no booking is active.
useEffect(() => {
if (
!appBookingState ||
!bookingData ||
(appBookingState.state != eBookingState.Booking &&
appBookingState.state != eBookingState.Booked)
) {
navigate(ConstsNav.page_Home);
}
}, [appBookingState, bookingData, navigate]);
//Send booking request to API
useEffect(() => {
async function sendCreateRequestAsync() {
const rs = await APISendCreateBooking(bookingData);
if (rs.isError) {
setPageState(PageState.error);
} else {
setBookingStateBooked();
navigate(ConstsNav.page_Success, { state: rs.bookingResponse });
}
}
if (pageState != PageState.sending) {
return;
}
sendCreateRequestAsync();
}, [pageState, bookingData, navigate, setBookingStateBooked]);
function onSubmit(values: z.infer<typeof BookingFormSchema>) {
if (bookingData == null) {
return;
}
const newCustomerData: NewBookingCustomerDetails = {
...bookingData.customerDetails,
name: values.name,
surname: values.surname,
email: values.email,
phoneNumber: values.phone,
};
setCustomerData(newCustomerData);
setPageState(PageState.sending);
}
const errorMsg = (
<div>
<Typography variant={"inlineCode"}>
Server error. Try again later!
</Typography>
</div>
);
return (
<>
<Typography variant={"h1"}>Booking Details</Typography>
<Separator className="my-8" />
<div className="lg:grid lg:grid-cols-40/60 lg:gap-x-10">
<Card>
<CardHeader>
<Typography variant={"h2"}>Personal Details</Typography>
</CardHeader>
<CardContent>
<form
id={bookingFormId}
onSubmit={bookingForm.handleSubmit(onSubmit)}
className="space-y-8"
>
<FieldSet>
<FieldLegend>Customer Details</FieldLegend>
<FieldGroup className="flex flex-row">
<Controller
name="name"
control={bookingForm.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor={field.name}>Name</FieldLabel>
<Input
{...field}
id={field.name}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
name="surname"
control={bookingForm.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor={field.name}>Surname</FieldLabel>
<Input
{...field}
id={field.name}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
</FieldGroup>
<FieldGroup className="flex flex-col">
<Controller
name="email"
control={bookingForm.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor={field.name}>Email</FieldLabel>
<Input
{...field}
id={field.name}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
<Controller
name="phone"
control={bookingForm.control}
render={({ field, fieldState }) => (
<Field data-invalid={fieldState.invalid}>
<FieldLabel htmlFor={field.name}>
Phone Number
</FieldLabel>
<Input
{...field}
id={field.name}
aria-invalid={fieldState.invalid}
/>
{fieldState.invalid && (
<FieldError errors={[fieldState.error]} />
)}
</Field>
)}
/>
</FieldGroup>
</FieldSet>
<Field orientation="vertical">
<Button
type="submit"
form={bookingFormId}
disabled={pageState == PageState.sending}
>
Submit
</Button>
</Field>
</form>
{pageState == PageState.error && errorMsg}
</CardContent>
</Card>
<Separator className="my-10 lg:hidden" />
<BookingDetails mode="View"></BookingDetails>
</div>
</>
);
}
export default BookPage;
+63
View File
@@ -0,0 +1,63 @@
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { Typography } from "@/components/ui/typography";
import { eConfigVarKeys } from "@/model/ConfigVar";
import { useConfigVariable } from "@/utils/apiHooks";
import { Mail, Phone } from "lucide-react";
import { useLocation } from "react-router";
function ContactPage() {
const location = useLocation();
const { value: varCompanyPhone, isLoading: isPhoneLoading } =
useConfigVariable(eConfigVarKeys.varCompanyPhone, "");
const { value: varCompanyMail, isLoading: isMailLoading } = useConfigVariable(
eConfigVarKeys.varCompanyEmail,
"",
);
const { value: varCompanyContactPage, isLoading: isContactPageLoading } =
useConfigVariable(eConfigVarKeys.varCompanyContactFormUrl, "");
const isDataLoading = isPhoneLoading || isMailLoading || isContactPageLoading;
const mainText = location.state ?? "Contact us for a personalized quote!";
const LoadingContent = <Skeleton className="h-25 w-full" />;
const MainContent = (
<div className="mx-auto">
<div className="mx-auto">
<Typography variant={"largeText"}>{mainText}</Typography>
<div className="my-4 flex justify-center gap-4">
<Card className="flex flex-col items-center gap-2 px-5 hover:bg-secondary">
<Phone size={"1.2em"} />
<Typography variant={"p_inline"}>{varCompanyPhone}</Typography>
</Card>
<Card className="flex flex-col items-center gap-2 px-5 hover:bg-secondary">
<Mail size={"1.2em"} />
<Typography variant={"p_inline"}>{varCompanyMail}</Typography>
</Card>
</div>
</div>
{varCompanyContactPage !== "" && (
<Button className="my-4" variant={"link"}>
<a href={varCompanyContactPage}>
<Typography variant={"largeText"}>Go to contact form</Typography>
</a>
</Button>
)}
</div>
);
return (
<Card>
<CardHeader>
<Typography variant={"h2"}>Contact us!</Typography>
</CardHeader>
<CardContent>{isDataLoading ? LoadingContent : MainContent}</CardContent>
</Card>
);
}
export default ContactPage;
+17
View File
@@ -0,0 +1,17 @@
import { useRouteError } from "react-router";
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>
);
}
+3
View File
@@ -0,0 +1,3 @@
.homePageRoomGrid {
grid-template-columns: repeat(auto-fit, minmax(300px, 3fr));
}
+72
View File
@@ -0,0 +1,72 @@
import { useAPIRoomCategoryList } 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/InternalTypes";
import { useNavigate } from "react-router";
import { LoaderIcon } from "lucide-react";
import "./home-page.css";
import { useAppStore } from "@/store";
import { useBookingStateDispacher } from "@/utils/hooks";
import { eConfigVarKeys } from "@/model/ConfigVar";
import { useConfigVariable } from "@/utils/apiHooks";
import { ConstsNav } from "@/utils/Consts";
function Homepage() {
const appSearchFilter = useAppStore((state) => state.searchFilter);
const navigate = useNavigate();
const { setBookingStateSearched } = useBookingStateDispacher();
const { value: varCompanyName } = useConfigVariable(
eConfigVarKeys.varCompanyName,
"",
);
const {
roomCategoryList,
isLoading: isLoadingCategories,
isError,
} = useAPIRoomCategoryList();
const onBtSearchClick = (filter: SearchFilter) => {
setBookingStateSearched(filter);
navigate(ConstsNav.page_Search, { state: filter });
};
const roomList = roomCategoryList?.map((element: RoomCategory) => {
return <RoomItemCard key={element.id} room={element} />;
});
return (
<>
<Typography variant={"h1"}>{varCompanyName}</Typography>
<Separator />
<SearchFilterCard
onSearchClick={onBtSearchClick}
initialsearchFilter={appSearchFilter}
/>
<Separator />
<div className="homePageRoomGrid grid gap-4">{roomList}</div>
{isLoadingCategories && (
<>
<Skeleton className="mx-auto flex h-50 w-full flex-col items-center justify-center">
<LoaderIcon />
<Typography variant={"h3"} as="h2">
Loading...
</Typography>
</Skeleton>
</>
)}
<Separator />
<BackendConnectionStatus
isLoading={isLoadingCategories}
isError={isError}
/>
</>
);
}
export default Homepage;
+122
View File
@@ -0,0 +1,122 @@
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 { SearchFilter } from "@/model/InternalTypes";
import { eBookingState } from "@/utils/AppStateManager";
import { useAppStore } from "@/store";
import { makeSearchPeriodRequestFromSearchFilter } from "@/utils/utils";
import { useNavigate } from "react-router";
import { useBookingStateDispacher } from "@/utils/hooks";
import { ConstsNav } from "@/utils/Consts";
//TODOME: Al pulsar el botón "buscar", si ya existen datos en la reserva (se han añadido habitaciones) mostrar un cuadro de aviso de que si se busca se borrará la selección actual.
//TODOME: Mediante los estados globales de la reserva, si ya está en estado "booking" añadiendo los datos, mostrar un mensaje y permitir redirigir directamente para que continue donde lo dejó.
function SearchPage() {
const appBookingState = useAppStore((state) => state.bookingState);
const appSearchFilter = useAppStore((state) => state.searchFilter);
const navigate = useNavigate();
const { setBookingStateSearched, setBookingStateBooking } =
useBookingStateDispacher();
const {
roomAvailabilityList,
isLoading: isLoadingAvailability,
isError: isErrorAvailability,
} = useAPIRoomAvailability(
makeSearchPeriodRequestFromSearchFilter(appSearchFilter) ?? null,
);
const isLoading = isLoadingAvailability;
const isError = isErrorAvailability;
const hasRooms =
roomAvailabilityList?.length && roomAvailabilityList?.length > 0;
const onBtSearchClick = (newFilter: SearchFilter) => {
setBookingStateSearched(newFilter);
};
const onBookingContinue = () => {
setBookingStateBooking();
navigate(ConstsNav.page_Book);
};
const roomList =
roomAvailabilityList?.map((element) => {
return (
<RoomBooking
key={element.roomCategory + "-" + appBookingState.lastSearchDate}
availableAmount={element.availability}
roomCategoryId={element.roomCategory}
/>
);
}) ?? null;
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 pageContentSearch = (
<Typography>
Realiza una búsqueda para ver la disponibilidad y los precios.
</Typography>
);
const pageContentLoading = (
<>
<Typography variant={"h3"} as="h2">
Loading...
</Typography>
<Skeleton className="mx-auto h-50 w-full" />
</>
);
const pageContentLoaded = (
<div className="2xl:grid 2xl:grid-cols-60/40 2xl:gap-6">
<div className="flex flex-col gap-5">{roomList}</div>
<Separator className="2xl:hidden" />
<BookingDetails
onBookingConfirm={onBookingContinue}
mode={"Book"}
></BookingDetails>
</div>
);
const getPageContent = () => {
const isSearched =
appBookingState.state == eBookingState.Searched ||
appBookingState.state == eBookingState.Booking;
if (!isSearched) {
return pageContentSearch;
}
if (isLoading) {
return pageContentLoading;
}
if (!hasRooms) {
return noRoomsAvailable;
}
return pageContentLoaded;
};
return (
<div className="bg-background text-foreground">
<SearchFilterCard
onSearchClick={onBtSearchClick}
initialsearchFilter={appSearchFilter}
/>
<Separator />
{getPageContent()}
<Separator />
<BackendConnectionStatus isLoading={isLoading} isError={isError} />
</div>
);
}
export default SearchPage;
+51
View File
@@ -0,0 +1,51 @@
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 { ConstsNav } from "@/utils/Consts";
import { useEffect, useState } from "react";
import { useLocation, useNavigate } from "react-router";
function SuccessPage() {
const [pageState, setPageState] = useState<NewBookingResponse | null>(null);
const resetBookingState = useAppStore((state) => state.resetCurrentBooking);
const location = useLocation();
const navigate = useNavigate();
if (pageState == null && location.state != null) {
setPageState(location.state);
}
useEffect(() => {
if (location.state == null) {
navigate(ConstsNav.page_Home);
}
}, [location, navigate]);
const handleBtBackClick = () => {
resetBookingState();
navigate(ConstsNav.page_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;
+131
View File
@@ -0,0 +1,131 @@
import { create } from "zustand";
import { SearchFilter } from "@/model/InternalTypes";
import {
BookingState,
eBookingState,
SetBookingState,
} from "./utils/AppStateManager";
import {
NewBooking,
NewBookingCustomerDetails,
NewBookingRoom,
} from "./model/Bookings";
interface State {
searchFilter: SearchFilter;
currentBooking: NewBooking | null;
bookingState: BookingState;
}
interface Actions {
setSearchFilter: (newFilter: SearchFilter) => void;
resetSearchFilter: () => void;
setCurrentBooking: (newBooking: NewBooking) => void;
resetCurrentBooking: () => void;
initCurrentBooking: (arrival: Date, departure: Date) => void;
currentBookingAddRoom: (newRoom: NewBookingRoom) => void;
currentBookingSetCustomer: (newCustomer: NewBookingCustomerDetails) => void;
setBookingState: (newState: eBookingState) => 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: [],
};
const defaultBookingState: BookingState = {
state: eBookingState.None,
lastSearchDate: new Date(),
};
function getDefaultBooking(arrivalDate: Date, departureDate: Date) {
return {
...defaultNewBooking,
arrivalDate: arrivalDate,
departureDate: departureDate,
};
}
function addNewBookingRoom(
newRoom: NewBookingRoom,
currentBookingState: NewBooking | null,
): NewBooking | null {
if (currentBookingState == null) {
return currentBookingState;
}
//Remove rooms with "same key".
const filteredRooms = currentBookingState.rooms.filter((room) => {
const isDiffRoom = room.roomCategory != newRoom.roomCategory;
const isDiffAmount = room.guestNumber != newRoom.guestNumber;
if (isDiffRoom || (!isDiffRoom && isDiffAmount)) {
return true;
}
return false;
});
if (newRoom.amount > 0) {
filteredRooms.push(newRoom);
}
const newState: NewBooking = {
...currentBookingState,
rooms: filteredRooms ?? [],
};
return newState;
}
function setBookingCustomer(
newCustomer: NewBookingCustomerDetails,
currentBookingState: NewBooking | null,
) {
if (currentBookingState == null) {
return currentBookingState;
}
const newState: NewBooking = {
...currentBookingState,
customerDetails: newCustomer,
};
return newState;
}
export const useAppStore = create<State & Actions>()((set) => ({
searchFilter: defaultSearchFilter,
currentBooking: null,
bookingState: defaultBookingState,
setSearchFilter: (newFilter) => set(() => ({ searchFilter: newFilter })),
resetSearchFilter: () => set(() => ({ searchFilter: defaultSearchFilter })),
setCurrentBooking: (newBooking) =>
set(() => ({ currentBooking: newBooking })),
resetCurrentBooking: () => set(() => ({ currentBooking: null })),
initCurrentBooking: (arrival, departure) =>
set(() => ({ currentBooking: getDefaultBooking(arrival, departure) })),
currentBookingAddRoom: (newRoom) =>
set((state) => ({
currentBooking: addNewBookingRoom(newRoom, state.currentBooking),
})),
currentBookingSetCustomer: (newCustomer) =>
set((state) => ({
currentBooking: setBookingCustomer(newCustomer, state.currentBooking),
})),
setBookingState: (newState) =>
set((state) => ({
bookingState: SetBookingState(newState, state.bookingState),
})),
}));
+27
View File
@@ -0,0 +1,27 @@
export type BookingState = {
state: eBookingState;
lastSearchDate: Date;
};
export enum eBookingState {
None = "NONE",
Searched = "SEARCHED",
Booking = "BOOKING",
Booked = "BOOKED",
}
export function SetBookingState(
newState: eBookingState,
currentAppBookingState: BookingState,
) {
const newAppState: BookingState = {
...currentAppBookingState,
state: newState,
};
if (newState == eBookingState.Searched) {
newAppState.lastSearchDate = new Date();
}
return newAppState;
}
+22
View File
@@ -0,0 +1,22 @@
export const c_somniaRooms_notice_text =
"Powered by SomniaRooms, an Open-Source hospitality booking platform!";
export const c_sominaRooms_webpage = "https://somnia.dev";
export const ConstsNav = {
page_Home: "/home",
page_Contact: "/contact",
page_Search: "/search",
page_Book: "/book",
page_Success: "/success",
};
//TMP - The following texts should be replaced for a proper intl system.
export const ConstsTexts = {
navToContact_maxAllowedNightCount:
"We are sorry, but the selected date range is too large. Search for a smaller range or contact us for a personalized quote.",
navToContact_maxAllowedGuestNumber:
"We are sorry, group bookings are not allowed. Contact us for a personalized quote.",
contactUsAlertDialog_title: "Contact us!",
contactUsAlertDialog_text:
"This booking seems like a big deal... Contact us for a personalized quote!",
};
+97
View File
@@ -0,0 +1,97 @@
import { useAPIConfigVarList } from "@/api/api-configVars";
import { getConfigVarFromList } from "./utils";
import { eConfigVarKeys } from "@/model/ConfigVar";
import { useAPIRoomCategoryList } from "@/api/api-roomCategories";
import { useAPIRoomPrices } from "@/api/api-roomSearch";
import { RoomCategory } from "@/model/RoomCategory";
import { RoomPrice, SearchPeriodRequest } from "@/model/RoomSearch";
export function useConfigVariable(
key: eConfigVarKeys,
defaultValue: string,
): {
value: string;
isLoading: boolean;
} {
const { configVarList, isLoading } = useAPIConfigVarList();
if (isLoading) {
return {
value: defaultValue,
isLoading: true,
};
}
const configVar = getConfigVarFromList(configVarList, key);
return { value: configVar?.value ?? defaultValue, isLoading: isLoading };
}
export function useConfigVariableAsNumber(
key: eConfigVarKeys,
defaultValue: number,
): {
value: number;
isLoading: boolean;
} {
const rs = useConfigVariable(key, defaultValue.toString());
return {
value: rs.isLoading ? defaultValue : parseFloat(rs.value),
isLoading: rs.isLoading,
};
}
export function useRoomCategory(roomCategoryId: number): {
value: RoomCategory | null;
isLoading: boolean;
} {
const { roomCategoryList, isLoading, isError } = useAPIRoomCategoryList();
if (isLoading) {
return {
value: null,
isLoading: true,
};
}
if (isError) {
return {
value: null,
isLoading: false,
};
}
const roomCategoryItem = roomCategoryList?.find(
(i) => i.id == roomCategoryId,
);
return { value: roomCategoryItem ?? null, isLoading: isLoading };
}
export function useRoomPrice(
filter: SearchPeriodRequest | null,
roomCategoryId: number,
): {
value: RoomPrice[];
isLoading: boolean;
} {
const { roomPriceList, isLoading, isError } = useAPIRoomPrices(filter);
if (isLoading) {
return {
value: [],
isLoading: true,
};
}
if (isError) {
return {
value: [],
isLoading: false,
};
}
const roomPrice = roomPriceList?.find(
(i) => i.roomCategoryId == roomCategoryId,
);
return { value: roomPrice?.prices ?? [], isLoading: isLoading };
}
+131
View File
@@ -0,0 +1,131 @@
import { SearchFilter } from "@/model/InternalTypes";
import { useAppStore } from "@/store";
import { getNightCountFromSearchFilter, makeDayUTCDate } from "./utils";
import { useCallback } from "react";
import { eBookingState } from "./AppStateManager";
import { useConfigVariableAsNumber } from "./apiHooks";
import { eConfigVarKeys } from "@/model/ConfigVar";
import { NewBooking } from "@/model/Bookings";
export function useBookingStateDispacher(): {
setBookingStateSearched: (sf: SearchFilter) => void;
setBookingStateBooking: () => void;
setBookingStateBooked: () => void;
} {
const setAppBookingState = useAppStore((state) => state.setBookingState);
const setAppSearchFilter = useAppStore((state) => state.setSearchFilter);
const initAppBooking = useAppStore((state) => state.initCurrentBooking);
const fnSearched = useCallback(
(sf: SearchFilter) => {
setAppSearchFilter(sf);
setAppBookingState(eBookingState.Searched);
initAppBooking(
makeDayUTCDate(sf.dateRange.from),
makeDayUTCDate(sf.dateRange.to),
);
},
[setAppBookingState, setAppSearchFilter, initAppBooking],
);
const fnBooking = useCallback(() => {
setAppBookingState(eBookingState.Booking);
}, [setAppBookingState]);
const fnBooked = useCallback(() => {
setAppBookingState(eBookingState.Booked);
}, [setAppBookingState]);
return {
setBookingStateSearched: fnSearched,
setBookingStateBooking: fnBooking,
setBookingStateBooked: fnBooked,
};
}
//This checks may be moved into "useBookingStateDispacher".
// That way, the logic may be more general and separated from the components and buttons
// and the dialog may use global state.
export function useCheckForNightCount(sf: SearchFilter | null): {
isOverApiMax: boolean;
shouldShowContactDialog: boolean;
isLoading: boolean;
} {
const {
value: varApiMaxAllowedNights,
isLoading: isLoadingVarMaxAllowedNights,
} = useConfigVariableAsNumber(eConfigVarKeys.varAPIMaxAllowedNightAmount, -1);
const {
value: varNightCountForContactDialog,
isLoading: isLoadingVarNightCountForContact,
} = useConfigVariableAsNumber(
eConfigVarKeys.varNightCountForContactDialog,
-1,
);
const areVariablesLoading =
isLoadingVarMaxAllowedNights || isLoadingVarNightCountForContact;
const filterNightCount = getNightCountFromSearchFilter(sf);
if (filterNightCount == null || areVariablesLoading) {
return {
isOverApiMax: false,
shouldShowContactDialog: false,
isLoading: areVariablesLoading,
};
}
const doCheckForMaxAllowedNights = varApiMaxAllowedNights > -1;
const doCheckForContactAlert = varNightCountForContactDialog > -1;
return {
isOverApiMax:
doCheckForMaxAllowedNights && filterNightCount > varApiMaxAllowedNights,
shouldShowContactDialog:
doCheckForContactAlert &&
filterNightCount >= varNightCountForContactDialog,
isLoading: areVariablesLoading,
};
}
export function useCheckForGuestNumber(bookingData: NewBooking | null): {
isOverApiMax: boolean;
shouldShowContactDialog: boolean;
isLoading: boolean;
} {
const {
value: varApiMaxAllowedGuests,
isLoading: isLoadingVarMaxAllowedGuests,
} = useConfigVariableAsNumber(eConfigVarKeys.varAPIMaxAllowedGuestNumber, -1);
const {
value: varGuestNumberForContactDialog,
isLoading: isLoadingVarGuestNumberForContact,
} = useConfigVariableAsNumber(
eConfigVarKeys.varGuestNumberForContactDialog,
-1,
);
const areVariablesLoading =
isLoadingVarMaxAllowedGuests || isLoadingVarGuestNumberForContact;
if (bookingData == null || areVariablesLoading) {
return {
isOverApiMax: false,
shouldShowContactDialog: false,
isLoading: areVariablesLoading,
};
}
//Calculate guest number in current booking data.
const totalGuestNumber = bookingData.rooms.reduce((acc, r) => {
return acc + r.guestNumber * r.amount;
}, 0);
const doCheckForMaxAllowedGuests = varApiMaxAllowedGuests > -1;
const doCheckForContactAlert = varGuestNumberForContactDialog > -1;
return {
isOverApiMax:
doCheckForMaxAllowedGuests && totalGuestNumber > varApiMaxAllowedGuests,
shouldShowContactDialog:
doCheckForContactAlert &&
totalGuestNumber >= varGuestNumberForContactDialog,
isLoading: areVariablesLoading,
};
}
+61
View File
@@ -0,0 +1,61 @@
import { SearchPeriodRequest } from "@/model/RoomSearch";
import { SearchFilter } from "@/model/InternalTypes";
import { ConfigVar } from "@/model/ConfigVar";
import { differenceInDays } from "date-fns";
export function makeDayUTCDate(date: Date | undefined): Date {
if (!date) {
return new Date();
}
return new Date(
date.getFullYear(),
date.getMonth(),
date.getDate(),
23,
59,
59,
999,
);
}
export function isValidSearchFilter(
sf: SearchFilter | null,
): sf is SearchFilter {
if (sf?.dateRange?.from && sf?.dateRange?.to) {
return true;
}
return false;
}
export function getNightCountFromSearchFilter(
sf: SearchFilter | null,
): number | null {
if (!isValidSearchFilter(sf)) {
return null;
}
return differenceInDays(sf.dateRange.to!, sf.dateRange.from!);
}
export function makeSearchPeriodRequestFromSearchFilter(
sf: SearchFilter,
): SearchPeriodRequest | null {
if (!isValidSearchFilter(sf)) {
return null;
}
return {
startDate: sf.dateRange.from!.toISOString(),
endDate: sf.dateRange.to!.toISOString(),
};
}
export function getConfigVarFromList(
varList: ConfigVar[] | undefined,
key: string,
): ConfigVar | undefined {
if (!varList) {
return undefined;
}
return varList.find((v) => v.key === key);
}
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+10
View File
@@ -0,0 +1,10 @@
{
"compilerOptions": {
// ...
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
// ...
}
}
+29
View File
@@ -0,0 +1,29 @@
{
"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"]
}
+18
View File
@@ -0,0 +1,18 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";
import path from "path";
import tailwindcss from "@tailwindcss/vite";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react(), tailwindcss()],
server: {
host: true,
port: 3000,
},
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
});