Author SHA1 Message Date
Daniel-Garmig 5676262692 Generate Nightly Build - 202405131816
Publish_on_Tag / Build and Push (push) Successful in 3m24s
2024-05-13 18:16:20 +02:00
71 changed files with 1265 additions and 5595 deletions
+9 -10
View File
@@ -2,18 +2,17 @@ module.exports = {
root: true, root: true,
env: { browser: true, es2020: true, node: false }, env: { browser: true, es2020: true, node: false },
extends: [ extends: [
"eslint:recommended", 'eslint:recommended',
"plugin:@typescript-eslint/recommended", 'plugin:@typescript-eslint/recommended',
"plugin:react-hooks/recommended", 'plugin:react-hooks/recommended',
"prettier",
], ],
ignorePatterns: ["dist", ".eslintrc.cjs"], ignorePatterns: ['dist', '.eslintrc.cjs'],
parser: "@typescript-eslint/parser", parser: '@typescript-eslint/parser',
plugins: ["react-refresh"], plugins: ['react-refresh'],
rules: { rules: {
"react-refresh/only-export-components": [ 'react-refresh/only-export-components': [
"warn", 'warn',
{ allowConstantExport: true }, { allowConstantExport: true },
], ],
}, },
}; }
-2
View File
@@ -1,2 +0,0 @@
# EOL normalization
* text=auto
+1
View File
@@ -12,6 +12,7 @@ concurrency:
cancel-in-progress: true cancel-in-progress: true
jobs: jobs:
lint: lint:
name: Docker Lint name: Docker Lint
runs-on: ubuntu-latest runs-on: ubuntu-latest
+1 -1
View File
@@ -41,5 +41,5 @@ jobs:
tags: ${{vars.REGISTRY_INSTANCE}}/somnia/somniaroomsapp:devbuild tags: ${{vars.REGISTRY_INSTANCE}}/somnia/somniaroomsapp:devbuild
target: final-prod target: final-prod
platforms: linux/amd64,linux/arm64 platforms: linux/amd64,linux/arm64
secrets: | secrets: |
GIT_AUTH_TOKEN=${{secrets.REGISTRY_TOKEN}} GIT_AUTH_TOKEN=${{secrets.REGISTRY_TOKEN}}
-7
View File
@@ -1,7 +0,0 @@
# Ignore artifacts:
**/dist
**/.git
**/.svn
**/.hg
**/node_modules
-4
View File
@@ -1,4 +0,0 @@
{
"endOfLine": "lf",
"plugins": ["prettier-plugin-tailwindcss"]
}
Binary file not shown.
+6
View File
@@ -0,0 +1,6 @@
{
"ExpandedNodes": [
""
],
"PreviewInSolutionExplorer": false
}
BIN
View File
Binary file not shown.
+5 -5
View File
@@ -1,23 +1,23 @@
# Base Node Environment. # Base Node Environment.
FROM node:21.7-alpine3.19 AS app-base FROM node:21.7-alpine3.19 as app-base
WORKDIR /app WORKDIR /app
ENV PATH=/app/node_modules/.bin:$PATH ENV PATH /app/node_modules/.bin:$PATH
COPY package.json ./ COPY package.json ./
COPY package-lock.json ./ COPY package-lock.json ./
COPY . ./ COPY . ./
# Dev environment. # Dev environment.
FROM app-base AS final-dev FROM app-base as final-dev
RUN npm install RUN npm install
ENV CHOKIDAR_USEPOLLING=true ENV CHOKIDAR_USEPOLLING=true
CMD ["npm", "run", "dev"] CMD ["npm", "run", "dev"]
# Build app for production. # Build app for production.
FROM app-base AS builder FROM app-base as builder
RUN npm ci && npm run build RUN npm ci && npm run build
# production environment # production environment
FROM nginx:stable-alpine AS final-prod FROM nginx:stable-alpine as final-prod
COPY --from=builder /app/dist /usr/share/nginx/html COPY --from=builder /app/dist /usr/share/nginx/html
COPY /public /usr/share/nginx/html/public COPY /public /usr/share/nginx/html/public
COPY scripts/env.sh /docker-entrypoint.d/env.sh COPY scripts/env.sh /docker-entrypoint.d/env.sh
+2 -11
View File
@@ -2,49 +2,42 @@
User app for SomniaRooms. User app for SomniaRooms.
## Docker Usage: ## Docker Usage:
### Dev ### Dev
**Build Image:** **Build Image:**
``` ```
docker build -t somniarooms-app:dev --target final-dev . docker build -t somniarooms-app:dev --target final-dev .
``` ```
**Docker Run Image:** **Docker Run Image:**
``` ```
docker run -d -it --rm -v ${PWD}:/app -v /app/node_modules -p 3000:3000 --name somniarooms-app somniarooms-app:dev docker run -d -it --rm -v ${PWD}:/app -v /app/node_modules -p 3000:3000 --name somniarooms-app somniarooms-app:dev
``` ```
Notas: Notas:
- Usar `-rm` para eliminar el contenedor y sus volúmenes en stop. - Usar `-rm` para eliminar el contenedor y sus volúmenes en stop.
- Usar `-d` para modo detached. - Usar `-d` para modo detached.
### Prod: ### Prod:
**Build Image** **Build Image**
``` ```
docker build -t somniarooms-app:prod --target final-prod . docker build -t somniarooms-app:prod --target final-prod .
``` ```
**Docker Run** **Docker Run**
``` ```
docker run -d -it -p 8080:80 --name somniarooms-app somniarooms-app:prod docker run -d -it -p 8080:80 --name somniarooms-app somniarooms-app:prod
``` ```
**Docker run with env vars:** **Docker run with env vars:**
``` ```
docker run -d -it -p 8080:80 --name somniarooms-app -e SOMNIAROOMS_BACKEND_HOST=https://somniaapi.example.org/ -e SOMNIAROOMS_BACKEND_PORT=443 somniarooms-app:prod docker run -d -it -p 8080:80 --name somniarooms-app -e SOMNIAROOMS_BACKEND_HOST=https://somniaapi.example.org/ -e SOMNIAROOMS_BACKEND_PORT=443 somniarooms-app:prod
``` ```
## Env Vars. ## Env Vars.
As this is distributed as a docker image ready to use, you must set some env variables to configure the app: As this is distributed as a docker image ready to use, you must set some env variables to configure the app:
| Var | Default Value | Description | | Var | Default Value | Description |
@@ -56,14 +49,12 @@ As this is distributed as a docker image ready to use, you must set some env var
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. 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 ### .env
Contains default values. It is just an example configuration. Contains default values. It is just an example configuration.
For development is recomended to create a `.env.local` file based on `.env`. For development is recomended to create a `.env.local` file based on `.env`.
### .env.production ### .env.production
Set varibles to certains placeholder, that are replace on container startup. Set varibles to certains placeholder, that are replace on container startup.
(We are using this solution: https://stackoverflow.com/a/77454537) (We are using this solution: https://stackoverflow.com/a/77454537)
+1 -1
View File
@@ -15,4 +15,4 @@
"utils": "@/lib/utils", "utils": "@/lib/utils",
"ui": "src/components/ui" "ui": "src/components/ui"
} }
} }
+11 -127
View File
@@ -40,12 +40,9 @@
"@vitejs/plugin-react-swc": "^3.5.0", "@vitejs/plugin-react-swc": "^3.5.0",
"autoprefixer": "^10.4.19", "autoprefixer": "^10.4.19",
"eslint": "^8.57.0", "eslint": "^8.57.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-react-hooks": "^4.6.0", "eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.6", "eslint-plugin-react-refresh": "^0.4.6",
"postcss": "^8.4.38", "postcss": "^8.4.38",
"prettier": "^3.3.3",
"prettier-plugin-tailwindcss": "^0.6.6",
"tailwindcss": "^3.4.3", "tailwindcss": "^3.4.3",
"tailwindcss-animate": "^1.0.7", "tailwindcss-animate": "^1.0.7",
"typescript": "^5.2.2", "typescript": "^5.2.2",
@@ -2398,13 +2395,12 @@
} }
}, },
"node_modules/braces": { "node_modules/braces": {
"version": "3.0.3", "version": "3.0.2",
"resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz",
"integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==",
"dev": true, "dev": true,
"license": "MIT",
"dependencies": { "dependencies": {
"fill-range": "^7.1.1" "fill-range": "^7.0.1"
}, },
"engines": { "engines": {
"node": ">=8" "node": ">=8"
@@ -2859,19 +2855,6 @@
"url": "https://opencollective.com/eslint" "url": "https://opencollective.com/eslint"
} }
}, },
"node_modules/eslint-config-prettier": {
"version": "9.1.0",
"resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-9.1.0.tgz",
"integrity": "sha512-NSWl5BFQWEPi1j4TjVNItzYV7dZXZ+wP6I6ZhrBGpChQhZRUaElihE9uRRkcbRnNb76UMKDF3r+WTmNcGPKsqw==",
"dev": true,
"license": "MIT",
"bin": {
"eslint-config-prettier": "bin/cli.js"
},
"peerDependencies": {
"eslint": ">=7.0.0"
}
},
"node_modules/eslint-plugin-react-hooks": { "node_modules/eslint-plugin-react-hooks": {
"version": "4.6.2", "version": "4.6.2",
"resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-4.6.2.tgz", "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-4.6.2.tgz",
@@ -3070,11 +3053,10 @@
} }
}, },
"node_modules/fill-range": { "node_modules/fill-range": {
"version": "7.1.1", "version": "7.0.1",
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz",
"integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==",
"dev": true, "dev": true,
"license": "MIT",
"dependencies": { "dependencies": {
"to-regex-range": "^5.0.1" "to-regex-range": "^5.0.1"
}, },
@@ -3417,7 +3399,6 @@
"resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz",
"integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",
"dev": true, "dev": true,
"license": "MIT",
"engines": { "engines": {
"node": ">=0.12.0" "node": ">=0.12.0"
} }
@@ -3598,13 +3579,12 @@
} }
}, },
"node_modules/micromatch": { "node_modules/micromatch": {
"version": "4.0.8", "version": "4.0.5",
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz",
"integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==",
"dev": true, "dev": true,
"license": "MIT",
"dependencies": { "dependencies": {
"braces": "^3.0.3", "braces": "^3.0.2",
"picomatch": "^2.3.1" "picomatch": "^2.3.1"
}, },
"engines": { "engines": {
@@ -4047,101 +4027,6 @@
"node": ">= 0.8.0" "node": ">= 0.8.0"
} }
}, },
"node_modules/prettier": {
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.3.3.tgz",
"integrity": "sha512-i2tDNA0O5IrMO757lfrdQZCc2jPNDVntV0m/+4whiDfWaTKfMNgR7Qz0NAeGz/nRqF4m5/6CLzbP4/liHt12Ew==",
"dev": true,
"license": "MIT",
"bin": {
"prettier": "bin/prettier.cjs"
},
"engines": {
"node": ">=14"
},
"funding": {
"url": "https://github.com/prettier/prettier?sponsor=1"
}
},
"node_modules/prettier-plugin-tailwindcss": {
"version": "0.6.6",
"resolved": "https://registry.npmjs.org/prettier-plugin-tailwindcss/-/prettier-plugin-tailwindcss-0.6.6.tgz",
"integrity": "sha512-OPva5S7WAsPLEsOuOWXATi13QrCKACCiIonFgIR6V4lYv4QLp++UXVhZSzRbZxXGimkQtQT86CC6fQqTOybGng==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=14.21.3"
},
"peerDependencies": {
"@ianvs/prettier-plugin-sort-imports": "*",
"@prettier/plugin-pug": "*",
"@shopify/prettier-plugin-liquid": "*",
"@trivago/prettier-plugin-sort-imports": "*",
"@zackad/prettier-plugin-twig-melody": "*",
"prettier": "^3.0",
"prettier-plugin-astro": "*",
"prettier-plugin-css-order": "*",
"prettier-plugin-import-sort": "*",
"prettier-plugin-jsdoc": "*",
"prettier-plugin-marko": "*",
"prettier-plugin-multiline-arrays": "*",
"prettier-plugin-organize-attributes": "*",
"prettier-plugin-organize-imports": "*",
"prettier-plugin-sort-imports": "*",
"prettier-plugin-style-order": "*",
"prettier-plugin-svelte": "*"
},
"peerDependenciesMeta": {
"@ianvs/prettier-plugin-sort-imports": {
"optional": true
},
"@prettier/plugin-pug": {
"optional": true
},
"@shopify/prettier-plugin-liquid": {
"optional": true
},
"@trivago/prettier-plugin-sort-imports": {
"optional": true
},
"@zackad/prettier-plugin-twig-melody": {
"optional": true
},
"prettier-plugin-astro": {
"optional": true
},
"prettier-plugin-css-order": {
"optional": true
},
"prettier-plugin-import-sort": {
"optional": true
},
"prettier-plugin-jsdoc": {
"optional": true
},
"prettier-plugin-marko": {
"optional": true
},
"prettier-plugin-multiline-arrays": {
"optional": true
},
"prettier-plugin-organize-attributes": {
"optional": true
},
"prettier-plugin-organize-imports": {
"optional": true
},
"prettier-plugin-sort-imports": {
"optional": true
},
"prettier-plugin-style-order": {
"optional": true
},
"prettier-plugin-svelte": {
"optional": true
}
}
},
"node_modules/punycode": { "node_modules/punycode": {
"version": "2.3.1", "version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
@@ -4785,7 +4670,6 @@
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
"integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
"dev": true, "dev": true,
"license": "MIT",
"dependencies": { "dependencies": {
"is-number": "^7.0.0" "is-number": "^7.0.0"
}, },
+1 -5
View File
@@ -6,8 +6,7 @@
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"build": "tsc && vite build", "build": "tsc && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0 && npx prettier . --check", "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"pretty": "npx prettier . --write",
"preview": "vite preview" "preview": "vite preview"
}, },
"dependencies": { "dependencies": {
@@ -43,12 +42,9 @@
"@vitejs/plugin-react-swc": "^3.5.0", "@vitejs/plugin-react-swc": "^3.5.0",
"autoprefixer": "^10.4.19", "autoprefixer": "^10.4.19",
"eslint": "^8.57.0", "eslint": "^8.57.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-react-hooks": "^4.6.0", "eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.6", "eslint-plugin-react-refresh": "^0.4.6",
"postcss": "^8.4.38", "postcss": "^8.4.38",
"prettier": "^3.3.3",
"prettier-plugin-tailwindcss": "^0.6.6",
"tailwindcss": "^3.4.3", "tailwindcss": "^3.4.3",
"tailwindcss-animate": "^1.0.7", "tailwindcss-animate": "^1.0.7",
"typescript": "^5.2.2", "typescript": "^5.2.2",
+1 -1
View File
@@ -3,4 +3,4 @@ export default {
tailwindcss: {}, tailwindcss: {},
autoprefixer: {}, autoprefixer: {},
}, },
}; }
+14 -16
View File
@@ -2,20 +2,18 @@ import { NewBooking, NewBookingResponse } from "@/model/Bookings";
import { fetcherWithFilter } from "./backend"; import { fetcherWithFilter } from "./backend";
export async function APISendCreateBooking(bookingData: NewBooking | null) { export async function APISendCreateBooking(bookingData: NewBooking | null) {
if (!bookingData) {
if (!bookingData) {
return {
bookingResponse: null,
isError: true
}
}
const rs = await fetcherWithFilter<NewBookingResponse>("/api/booking/create", bookingData);
return { return {
bookingResponse: null, bookingResponse: rs,
isError: true, isError: false
}; }
} }
const rs = await fetcherWithFilter<NewBookingResponse>(
"/api/booking/create",
bookingData,
);
return {
bookingResponse: rs,
isError: false,
};
}
+9 -12
View File
@@ -1,28 +1,25 @@
import { RoomCategory } from "@/model/RoomCategory"; import { RoomCategory } from "@/model/RoomCategory";
import { fetcher, fetcherUnwraper } from "./backend"; import { fetcher, fetcherUnwraper } from "./backend";
import useSWR from "swr"; import useSWR from 'swr';
export function useAPIRoomCategories() { export function useAPIRoomCategories() {
const { data, error, isLoading } = useSWR<RoomCategory[]>( const { data, error, isLoading } = useSWR<RoomCategory[]>('/api/room/category', fetcherUnwraper)
"/api/room/category",
fetcherUnwraper,
);
return { return {
roomCategoryList: data, roomCategoryList: data,
isLoading, isLoading,
isError: error, isError: error
}; }
} }
export function useAPIRoomCategoryId(categoryId: number) { export function useAPIRoomCategoryId(categoryId: number) {
const url = categoryId ? "/api/room/category/" + categoryId : null; const url = categoryId ? '/api/room/category/' + categoryId : null;
const { data, error, isLoading } = useSWR<RoomCategory>(url, fetcher); const { data, error, isLoading } = useSWR<RoomCategory>(url, fetcher)
return { return {
roomCategory: data, roomCategory: data,
isLoading, isLoading,
isError: error, isError: error
}; }
} }
+23 -39
View File
@@ -1,49 +1,33 @@
import { fetcherUnwraperWithFilter } from "./backend"; import { fetcherUnwraperWithFilter } from "./backend";
import useSWR from "swr"; import useSWR from 'swr';
import { import { AvailabilityFilter, AvailabilityRequest, FareFilter, FareRequest, RoomAvailabity, RoomPrice } from "@/model/RoomSearch";
AvailabilityFilter,
AvailabilityRequest,
FareFilter,
FareRequest,
RoomAvailabity,
RoomPrice,
} from "@/model/RoomSearch";
export function useAPIRoomAvailability(filter: AvailabilityFilter | null) { export function useAPIRoomAvailability(filter: AvailabilityFilter | null) {
const request: AvailabilityRequest | null = filter
? {
filter: filter,
}
: null;
const { data, isLoading, error } = useSWR( const request: AvailabilityRequest | null = filter ? {
request ? ["/api/search/availability", request] : null, filter: filter
([url, request]) => } : null;
fetcherUnwraperWithFilter<RoomAvailabity[]>(url, request),
);
return { const { data, isLoading, error } = useSWR(request ? ['/api/search/availability', request] : null, ([url, request]) => fetcherUnwraperWithFilter<RoomAvailabity[]>(url, request))
roomAvailabilityList: data,
isLoading, return {
isError: error, roomAvailabilityList: data,
}; isLoading,
isError: error
}
} }
export function useAPIRoomPrices(filter: FareFilter | null) { export function useAPIRoomPrices(filter: FareFilter | null) {
const request: FareRequest | null = filter
? {
filter: filter,
}
: null;
const { data, isLoading, error } = useSWR( const request: FareRequest | null = filter ? {
request ? ["/api/search/fares", request] : null, filter: filter
([url, request]) => fetcherUnwraperWithFilter<RoomPrice[]>(url, request), } : null;
);
return { const { data, isLoading, error } = useSWR(request ? ['/api/search/fares', request] : null, ([url, request]) => fetcherUnwraperWithFilter<RoomPrice[]>(url, request))
roomPriceList: data,
isLoading, return {
isError: error, roomPriceList: data,
}; isLoading,
} isError: error
}
}
+53 -58
View File
@@ -1,71 +1,66 @@
const BACKEND_HOST = import.meta.env.VITE_BACKEND_HOST; const BACKEND_HOST = import.meta.env.VITE_BACKEND_HOST;
const BACKEND_PORT = import.meta.env.VITE_BACKEND_PORT; const BACKEND_PORT = import.meta.env.VITE_BACKEND_PORT;
const url = const url = BACKEND_HOST + (BACKEND_PORT == 443 || BACKEND_PORT == 80 ? "" : ":" + BACKEND_PORT)
BACKEND_HOST +
(BACKEND_PORT == 443 || BACKEND_PORT == 80 ? "" : ":" + BACKEND_PORT);
export function fetcher<T>(endpoint: string): Promise<T> { export function fetcher<T>(endpoint: string): Promise<T> {
return fetch(url + endpoint, { return fetch(url + endpoint, {
method: "GET", method: "GET"
}).then((r) => { })
if (!r.ok) { .then(r => {
throw new Error(r.statusText); if (!r.ok) {
} throw new Error(r.statusText)
const data = r.json(); }
return data as Promise<T>; const data = r.json();
}); return data as Promise<T>;
})
} }
export function fetcherUnwraper<T>(endpoint: string): Promise<T> { export function fetcherUnwraper<T>(endpoint: string): Promise<T> {
return fetch(url + endpoint) return fetch(url + endpoint)
.then((response) => { .then(response => {
if (!response.ok) { if (!response.ok) {
throw new Error(response.statusText); throw new Error(response.statusText)
} }
return response.json() as Promise<{ results: T }>; return response.json() as Promise<{ results: T }>
}) })
.then((data) => { .then(data => {
return data.results; return data.results
}); })
} }
export function fetcherWithFilter<T>( export function fetcherWithFilter<T>(endpoint: string, body: NonNullable<unknown>): Promise<T> {
endpoint: string, return fetch(url + endpoint, {
body: NonNullable<unknown>, method: "POST",
): Promise<T> { body: JSON.stringify(body),
return fetch(url + endpoint, { headers: {
method: "POST", "Content-Type": "application/json",
body: JSON.stringify(body), },
headers: { })
"Content-Type": "application/json", .then(response => {
}, if (!response.ok) {
}).then((response) => { throw new Error(response.statusText)
if (!response.ok) { }
throw new Error(response.statusText); return response.json() as Promise<T>
} })
return response.json() as Promise<T>;
});
} }
export function fetcherUnwraperWithFilter<T>( export function fetcherUnwraperWithFilter<T>(endpoint: string, body: NonNullable<unknown>): Promise<T> {
endpoint: string, return fetch(url + endpoint, {
body: NonNullable<unknown>, method: "POST",
): Promise<T> { body: JSON.stringify(body),
return fetch(url + endpoint, { headers: {
method: "POST", "Content-Type": "application/json",
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) => { .then(response => {
return data.results; if (!response.ok) {
}); throw new Error(response.statusText)
} }
return response.json() as Promise<{ results: T }>
})
.then(data => {
return data.results
})
}
+84 -123
View File
@@ -1,183 +1,144 @@
import { useAPIRoomCategoryId } from "@/api/api-roomCategories"; import { useAPIRoomCategoryId } from "@/api/api-roomCategories"
import { Card, CardContent } from "../ui/card"; import { Card, CardContent, CardHeader } from "../ui/card"
import { useMemo } from "react"; import { useMemo, useState } from "react";
import { Typography } from "../ui/typography"; import { Typography } from "../ui/typography";
import { import { RoomCategoryPhoto } from "@/model/RoomCategory";
Table, import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../ui/table";
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "../ui/table";
import { Skeleton } from "../ui/skeleton"; import { Skeleton } from "../ui/skeleton";
import { useAppStore } from "@/store"; import { useAppStore } from "@/store";
import { DateRange } from "react-day-picker"; import { DateRange } from "react-day-picker";
import { FareFilter } from "@/model/RoomSearch"; import { FareFilter } from "@/model/RoomSearch";
import { useAPIRoomPrices } from "@/api/api-roomSearch"; import { useAPIRoomPrices } from "@/api/api-roomSearch";
import { NumberSelector } from "../ui/number-selector"; import { NumberSelector } from "../ui/number-selector";
import { NewBooking, NewBookingRoom } from "@/model/Bookings"; import { NewBookingRoom } from "@/model/Bookings";
import { RoomItemCard } from "./room-item-card";
import { IconWithTooltip } from "../ui/icon-number-tooltip";
import { UserIcon } from "lucide-react";
function RoomBooking({ function RoomBooking({ roomCategoryId, availableAmount }: { roomCategoryId: number, availableAmount: number }) {
roomCategoryId,
availableAmount,
}: {
roomCategoryId: number;
availableAmount: number;
}) {
const currentDates: DateRange = useAppStore(
(state) => state.searchFilter.dateRange,
);
const addNewRoom = useAppStore((state) => state.addNewBookingRoom);
const bookingRooms: NewBooking | null = useAppStore(
(state) => state.newBookingData,
);
function onSelectedAmountUpdate( const [selectedAmount, setSelectedAmount] = useState<Map<number, number>>(new Map());
guestNumber: number,
newCount: number, const currentDates: DateRange = useAppStore((state) => (state.searchFilter.dateRange));
price: number, const addNewRoom = useAppStore((state) => (state.addNewBookingRoom));
) {
console.log( function onSelectedAmountUpdate(guestNumber: number, newCount: number, price: number) {
"Room " + console.log("Room " + roomCategoryId + " Guestnumber: " + guestNumber + " Count: " + newCount);
roomCategoryId +
" Guestnumber: " + const newAmountMap = new Map(selectedAmount);
guestNumber + newAmountMap.set(guestNumber, newCount);
" Count: " + setSelectedAmount(newAmountMap)
newCount,
);
const newRoom: NewBookingRoom = { const newRoom: NewBookingRoom = {
roomCategory: roomCategoryId, roomCategory: roomCategoryId,
guestNumber: guestNumber, guestNumber: guestNumber,
amount: newCount, amount: newCount,
price: price, price: price
}; };
addNewRoom(newRoom); addNewRoom(newRoom);
} }
const totalSelected = () => { const totalSelected = () => {
let sum = 0; let sum = 0;
bookingRooms && selectedAmount.forEach((v) => sum += v)
bookingRooms.rooms
.filter((v) => v.roomCategory == roomCategoryId)
.forEach((v) => (sum += v.amount));
return sum; return sum;
}; };
const canAddMore: boolean = availableAmount > totalSelected(); const canAddMore: boolean = availableAmount > totalSelected();
//This seems a little bit overkill, but IDK. //This seems a little bit overkill, but IDK.
const fareFilter: FareFilter | null = useMemo(() => { const fareFilter: FareFilter | null = useMemo(
if (currentDates && currentDates.from && currentDates.to) { () => {
const filter: FareFilter = { if (currentDates && currentDates.from && currentDates.to) {
startDate: currentDates.from?.toDateString(), const filter: FareFilter = {
endDate: currentDates.to?.toDateString(), startDate: currentDates.from?.toDateString(),
roomCategory: roomCategoryId, endDate: currentDates.to?.toDateString(),
}; roomCategory: roomCategoryId
return filter; }
} return filter;
return null; }
}, [currentDates, roomCategoryId]); return null;
},
[currentDates, roomCategoryId]
);
const { const { roomCategory, isLoading: isLoadingCategory, isError: isErrorCategory } = useAPIRoomCategoryId(roomCategoryId);
roomCategory, const { roomPriceList, isLoading: isLoadingPrices, isError: isErrorPrices } = useAPIRoomPrices(fareFilter);
isLoading: isLoadingCategory,
isError: isErrorCategory,
} = useAPIRoomCategoryId(roomCategoryId);
const {
roomPriceList,
isLoading: isLoadingPrices,
isError: isErrorPrices,
} = useAPIRoomPrices(fareFilter);
//TODOME: Gestionar también los estados al cargar los precios.
const isLoading = isLoadingCategory || isLoadingPrices; const isLoading = isLoadingCategory || isLoadingPrices;
const isError = isErrorCategory || isErrorPrices; const isError = isErrorCategory || isErrorPrices;
if (isLoading) { if (isLoading) {
return <Skeleton className="mx-auto h-[150px] w-[600px]" />; return (
<Skeleton className="w-[600px] h-[150px] mx-auto" />
);
} }
if (isError) { if (isError) {
return ( return (
<Typography variant={"h3"} as="h3"> <Typography variant={"h3"} as="h3">Sorry, there was an error loading data.</Typography>
Sorry, there was an error loading data.
</Typography>
); );
} }
const mainPhoto: RoomCategoryPhoto | undefined = roomCategory?.roomCategoryPhotos.filter((p) => p.kind == "main")[0];
const photoElement = mainPhoto && (
<img src={mainPhoto.path} alt={mainPhoto.altText} className="rounded-md mx-0 px-0"></img>
);
const hasPrices = roomPriceList != null && roomPriceList?.length > 0; const hasPrices = roomPriceList != null && roomPriceList?.length > 0;
let priceTable = null; let priceTable = null;
if (hasPrices) { if (hasPrices) {
const tableRows = roomPriceList?.map((el) => { const tableRows = roomPriceList?.map((el) => {
return ( return (
<TableRow key={el.guestNumber}> <TableRow key={el.guestNumber}>
<TableCell> <TableCell>{el.guestNumber}</TableCell>
<IconWithTooltip
label={el.guestNumber?.toString()}
tooltipText={"Guest Number"}
labelPosition={"right"}
>
<UserIcon></UserIcon>
</IconWithTooltip>
</TableCell>
<TableCell>{el.price / 100} €</TableCell> <TableCell>{el.price / 100} €</TableCell>
<TableCell> <TableCell>
<NumberSelector <NumberSelector updateCount={(count) => onSelectedAmountUpdate(el.guestNumber, count, el.price)} addEnabled={canAddMore}></NumberSelector>
updateCount={(count) =>
onSelectedAmountUpdate(el.guestNumber, count, el.price)
}
addEnabled={canAddMore}
></NumberSelector>
</TableCell> </TableCell>
</TableRow> </TableRow>
); );
}); });
priceTable = ( priceTable = (
<Table className="overflow-hidden"> <>
<TableHeader> <Table>
<TableRow> <TableHeader>
<TableHead>Guest number</TableHead> <TableRow>
<TableHead>Price</TableHead> <TableHead>Guest number</TableHead>
<TableHead>Amount</TableHead> <TableHead>Price</TableHead>
</TableRow> <TableHead>Amount</TableHead>
</TableHeader> </TableRow>
<TableBody> </TableHeader>
{isLoadingPrices ? <Skeleton className="h-full w-full" /> : tableRows} <TableBody>
</TableBody> {isLoadingPrices ? <Skeleton className="w-[80%] h-[100%]" /> : tableRows}
</Table> </TableBody>
</Table>
<p>Rooms Available: {availableAmount}</p>
</>
); );
} }
let roomCard = null;
if (roomCategory) {
roomCard = (
<RoomItemCard
room={roomCategory}
key={roomCategoryId}
className="z-20 border-4"
></RoomItemCard>
);
}
return ( return (
<div className="relative sm:grid sm:grid-cols-40/60"> <Card>
{roomCard} <CardHeader>
<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"> <div className="flex flex-row gap-5 w-full">
<CardContent className="flex h-full w-full flex-col justify-center gap-4 p-5"> <div className="w-[40%] flex-none">
{hasPrices ? ( {photoElement}
priceTable </div>
) : ( <div>
<Typography variant={"largeText"}>No Prices available</Typography> <Typography variant={"h3"} as="h3">{roomCategory?.name}</Typography>
)} <Typography >{roomCategory?.description}</Typography>
<p>Rooms Available: {availableAmount}</p> </div>
</CardContent> </div>
</Card> </CardHeader>
</div> <CardContent>
{hasPrices ? priceTable : <Typography variant={"largeText"}>No Prices available</Typography>}
<div>
</div>
<p>Selected: {totalSelected()}</p>
</CardContent>
</Card>
); );
} }
export default RoomBooking; export default RoomBooking
+46 -82
View File
@@ -1,15 +1,12 @@
import { Separator } from "../ui/separator"; import { Separator } from "../ui/separator"
import { Card, CardContent } from "../ui/card"; import { Card, CardContent, CardHeader } from "../ui/card"
import { Typography } from "../ui/typography"; import { Typography } from "../ui/typography"
import { BedDoubleIcon, BedSingleIcon, UserIcon } from "lucide-react"; import { BedDoubleIcon, BedSingleIcon, UserIcon } from "lucide-react"
import { RoomCategory, RoomCategoryPhoto } from "@/model/RoomCategory"; import { RoomCategory, RoomCategoryPhoto } from "@/model/RoomCategory"
import { IconWithTooltip } from "../ui/icon-number-tooltip"; import { IconWithTooltipNumber } from "../ui/icon-number-tooltip"
import roomImg from "@/res/SomniaRoomImage.svg";
import { cn } from "@/lib/utils";
interface RoomItemCardProps { interface RoomItemCardProps {
room: RoomCategory; room: RoomCategory
className?: string;
} }
const defaultRoom: RoomCategory = { const defaultRoom: RoomCategory = {
@@ -19,83 +16,50 @@ const defaultRoom: RoomCategory = {
bedType: "0,1", bedType: "0,1",
maxGuestNum: 2, maxGuestNum: 2,
roomCategoryDetails: [], roomCategoryDetails: [],
roomCategoryPhotos: [], roomCategoryPhotos: []
}; }
export function RoomItemCard({ export function RoomItemCard({ room = defaultRoom }: RoomItemCardProps) {
room = defaultRoom,
className, const mainPhoto: RoomCategoryPhoto | undefined = room.roomCategoryPhotos.find((element) => {
}: RoomItemCardProps) { return element.kind = "main"
const mainPhoto: RoomCategoryPhoto | undefined = room.roomCategoryPhotos.find( });
(element) => { const bedTypeList: number[] = room.bedType.split(",").map((e) => Number.parseInt(e));
return (element.kind = "main"); const hasSingleBed: boolean = (bedTypeList.at(0) !== undefined && bedTypeList[0] > 0);
}, const hasDoubleBed: boolean = (bedTypeList.at(1) !== undefined && bedTypeList[1] > 0);
);
const bedTypeList: number[] = room.bedType
.split(",")
.map((e) => Number.parseInt(e));
const hasSingleBed: boolean =
bedTypeList.at(0) !== undefined && bedTypeList[0] > 0;
const hasDoubleBed: boolean =
bedTypeList.at(1) !== undefined && bedTypeList[1] > 0;
return ( return (
<Card id={room.id.toString()} className={cn(className, "relative")}> <Card id={room.id.toString()}>
{/* <CardHeader className="p-0 m-0 mb-5"> <CardHeader className="p-0 m-0 mb-5">
</CardHeader> */} <img src={mainPhoto?.path ?? "https://images.unsplash.com/photo-1618773928121-c32242e63f39"} className="rounded-md"></img>
<CardContent className="flex h-full w-full flex-col p-0"> <Typography variant={"h2"} as="h1" className="mx-5 py-2">{room.name}</Typography>
<div className=""> </CardHeader>
<img <CardContent>
src={mainPhoto?.path ?? roomImg} <Typography variant={"p"} as="p">
className="aspect-[4/3] w-full rounded-t-md object-cover" {room.description}
></img> </Typography>
<Separator className="my-0 border-2" /> <Separator className="my-4" />
</div> <div className="flex justify-around">
<div> <div className="flex flex-row gap-2">
<Typography variant={"h2"} as="h2" className="border-none px-4 pt-4"> {hasSingleBed && (
{room.name} <IconWithTooltipNumber altText="Single bed" amount={bedTypeList[0]}>
</Typography> <BedSingleIcon />
</div> </IconWithTooltipNumber>
<div> )}
<Typography variant={"p"} as="h2" className="px-5"> {hasDoubleBed && (
{room.description} <>
</Typography> <IconWithTooltipNumber altText="Double bed" amount={bedTypeList[1]}>
</div> <BedDoubleIcon />
<div className="mt-auto pb-4"> </IconWithTooltipNumber>
<Separator className="my-4" /> </>
<div className="flex justify-around"> )}
<div className="flex flex-row gap-2"> </div>
{hasSingleBed && ( <div className="flex flex-row">
<IconWithTooltip <UserIcon />
tooltipText="Single bed" <Typography variant={"p_inline"} className="ml-3">{room.maxGuestNum}</Typography>
label={bedTypeList[0]?.toString()}
>
<BedSingleIcon />
</IconWithTooltip>
)}
{hasDoubleBed && (
<>
<IconWithTooltip
tooltipText="Double bed"
label={bedTypeList[1]?.toString()}
>
<BedDoubleIcon />
</IconWithTooltip>
</>
)}
</div>
<div className="flex flex-row">
<IconWithTooltip
tooltipText="Max. gests"
label={room.maxGuestNum?.toString()}
labelPosition={"right"}
>
<UserIcon />
</IconWithTooltip>
</div>
</div> </div>
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
); )
} }
+41 -47
View File
@@ -1,37 +1,35 @@
import { Separator } from "../ui/separator"; import { Separator } from "../ui/separator"
import { Card, CardContent, CardHeader } from "../ui/card"; import { Card, CardContent, CardHeader } from "../ui/card"
import { Typography } from "../ui/typography"; import { Typography } from "../ui/typography"
import "react-day-picker/dist/style.css"; import 'react-day-picker/dist/style.css';
import { DatePickerWithRange } from "../ui/dateRange-picker"; import { DatePickerWithRange } from "../ui/dateRange-picker";
import { Button } from "../ui/button"; import { Button } from "../ui/button";
import { SearchIcon } from "lucide-react"; import { SearchIcon } from "lucide-react";
import { useState } from "react"; import { useEffect, useState } from "react";
import { SearchFilter } from "@/model/SearchFilter"; import { SearchFilter } from "@/model/SearchFilter";
import { DateRange } from "react-day-picker"; import { DateRange } from "react-day-picker";
import { useToast } from "../ui/use-toast"; import { useToast } from "../ui/use-toast";
import { useAppStore } from "@/store"; import { useAppStore } from "@/store";
import { useLocation } from "react-router-dom";
type funOnSearchClick = (newFilter: SearchFilter) => void; type funOnSearchClick = (newFilter: SearchFilter) => void;
export function SearchFilterCard({ export function SearchFilterCard({ onSearchClick }: { onSearchClick?: funOnSearchClick }) {
onSearchClick,
}: {
onSearchClick?: funOnSearchClick;
}) {
//App filter. Updated on btSearchClick. //App filter. Updated on btSearchClick.
const appSearchFilter = useAppStore((state) => state.searchFilter); const appSearchFilter = useAppStore((state) => (state.searchFilter));
const setAppSearchFilter = useAppStore((state) => state.setSearchFilter); const setAppSearchFilter = useAppStore((state) => (state.setSearchFilter));
//Local Filter state. //Local Filter state.
const [searchFilter, setSearchFilter] = const [searchFilter, setSearchFilter] = useState<SearchFilter>(appSearchFilter)
useState<SearchFilter>(appSearchFilter);
//On location change, try to load searchFilter from state. //On location change, try to load searchFilter from state.
//FIXME: Si llegamos sin state, hay que borrar el state global... //FIXME: Si llegamos sin state, hay que borrar el state global...
// const location = useLocation(); const location = useLocation();
// useEffect(() => { useEffect(() => {
// setSearchFilter(location.state); setSearchFilter(location.state);
// }, [location]); }, [location]);
const { toast } = useToast(); const { toast } = useToast();
@@ -50,17 +48,16 @@ export function SearchFilterCard({
toast({ toast({
variant: "destructive", variant: "destructive",
title: "Uh oh! Invalid Search.", title: "Uh oh! Invalid Search.",
description: "You should select a 'from' and 'to' dates", description: "You should select a 'from' and 'to' dates"
}); })
return; return;
} }
setAppSearchFilter(searchFilter);
if (onSearchClick) { if (onSearchClick) {
setAppSearchFilter(searchFilter);
onSearchClick(searchFilter); onSearchClick(searchFilter);
} }
}; }
// Handle Element updates. // Handle Element updates.
const updateDateRange = (newRange: DateRange) => { const updateDateRange = (newRange: DateRange) => {
@@ -68,40 +65,37 @@ export function SearchFilterCard({
...searchFilter, ...searchFilter,
dateRange: newRange, dateRange: newRange,
}); });
};
const datePickerElement = console.log("SearchFilterCard filter UPDATED");
searchFilter == null ? ( }
<DatePickerWithRange
updateDateRange={updateDateRange} const datePickerElement = searchFilter == null ? (
allowPast={false} <DatePickerWithRange
></DatePickerWithRange> updateDateRange={updateDateRange}
) : ( allowPast={false}>
<DatePickerWithRange </DatePickerWithRange>
updateDateRange={updateDateRange} ) : (
allowPast={false} <DatePickerWithRange
startDate={searchFilter.dateRange.from} updateDateRange={updateDateRange}
endDate={searchFilter.dateRange.to} allowPast={false}
></DatePickerWithRange> startDate={searchFilter.dateRange.from}
); endDate={searchFilter.dateRange.to}>
</DatePickerWithRange>
);
return ( return (
<Card> <Card>
<CardHeader className="m-0 mb-5 p-0"> <CardHeader className="p-0 m-0 mb-5">
<Typography variant={"h2"} as="h1" className="mx-5 py-2"> <Typography variant={"h2"} as="h1" className="mx-5 py-2">Reserva ahora</Typography>
Reserva ahora
</Typography>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
{datePickerElement} {datePickerElement}
<Separator className="my-4" /> <Separator className="my-4" />
<Button size={"lg"} onClick={btSearchClick}> <Button size={"lg"} onClick={btSearchClick}>
<SearchIcon className="me-2 text-primary-foreground" /> <SearchIcon className="text-primary-foreground me-2" />
<Typography variant={"h3"} className="text-primary-foreground"> <Typography variant={"h3"} className="text-primary-foreground">Buscar</Typography>
Buscar
</Typography>
</Button> </Button>
</CardContent> </CardContent>
</Card> </Card>
); )
} }
+16 -12
View File
@@ -1,17 +1,21 @@
function AppFooter() { function AppFooter() {
return ( return (
<div className="hidden flex-col bg-secondary"> <div className="bg-secondary flex-col hidden">
<div className="">Created with Love by me :)</div> <div className="">
<div className=""> Created with Love by me :)
<p>Más información</p> </div>
<ul className="list-outside"> <div className="">
<li>Info</li> <p>Más información</p>
<li>Info2</li> <ul className="list-outside">
<li>Info3</li> <li>Info</li>
</ul> <li>Info2</li>
</div> <li>Info3</li>
</ul>
</div>
</div> </div>
); )
} }
export default AppFooter; export default AppFooter
+15 -23
View File
@@ -1,40 +1,32 @@
import { ModeToggle } from "./mode-toggle"; import { ModeToggle } from "./mode-toggle"
import { Button } from "./ui/button"; import { Button } from "./ui/button"
import { Card, CardContent } from "./ui/card"; import { Card, CardContent } from "./ui/card"
import { Typography } from "./ui/typography"; import { Typography } from "./ui/typography"
import { Link } from "react-router-dom"; import { Link } from "react-router-dom"
import { BookAIcon, HomeIcon } from "lucide-react"; import { BookAIcon, HomeIcon } from "lucide-react"
function AppHeader() { function AppHeader() {
return ( return (
<Card className="mx-10 my-4 flex items-center"> <Card className="flex items-center mx-10 my-4">
<CardContent className="w-full py-2"> <CardContent className="w-full py-2">
<div className="flex items-center justify-around"> <div className="flex justify-around items-center">
<div className="relative flex flex-row items-center gap-2"> <div className="flex flex-row items-center gap-2 relative">
<img src="public/SR2.svg" className="w-[64px]"></img> <img src="public/SR2.svg" className="w-[64px]"></img>
<Typography variant={"largeText"}>Somnia Rooms</Typography> <Typography variant={"largeText"}>Somnia Rooms</Typography>
<a <a href="https://duck.com" className="absolute w-[100%] h-[100%]"></a>
href="https://duck.com"
className="absolute h-[100%] w-[100%]"
></a>
</div> </div>
<Button variant="ghost" className="h-15"> <Button variant="ghost" className="h-15">
<Link to={`home`}> <Link to={`home`}><HomeIcon className="mx-auto" />Home</Link>
<HomeIcon className="mx-auto" />
Home
</Link>
</Button> </Button>
<Button variant="ghost" className="h-15"> <Button variant="ghost" className="h-15">
<Link to={`search`}> <Link to={`search`}><BookAIcon className="mx-auto" />Reservar</Link>
<BookAIcon className="mx-auto" />
Reservar
</Link>
</Button> </Button>
<ModeToggle /> <ModeToggle />
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
); )
} }
export default AppHeader; export default AppHeader
+6 -10
View File
@@ -1,10 +1,6 @@
function BackendConnectionStatus({
isLoading, function BackendConnectionStatus({ isLoading, isError }: { isLoading?: boolean, isError?: boolean }) {
isError,
}: {
isLoading?: boolean;
isError?: boolean;
}) {
const BACKEND_HOST = import.meta.env.VITE_BACKEND_HOST; const BACKEND_HOST = import.meta.env.VITE_BACKEND_HOST;
const BACKEND_PORT = import.meta.env.VITE_BACKEND_PORT; const BACKEND_PORT = import.meta.env.VITE_BACKEND_PORT;
@@ -14,10 +10,10 @@ function BackendConnectionStatus({
Conected to Back-End at: {BACKEND_HOST} - {BACKEND_PORT} Conected to Back-End at: {BACKEND_HOST} - {BACKEND_PORT}
</p> </p>
<p> <p>
Conection Status: {isError ? "ERROR" : isLoading ? "LOADING" : "LOADED"} Conection Status: {isError ? "ERROR" : (isLoading ? "LOADING" : "LOADED")}
</p> </p>
</div> </div>
); )
} }
export default BackendConnectionStatus; export default BackendConnectionStatus
+46 -79
View File
@@ -1,39 +1,29 @@
import { useAppStore } from "@/store"; import { useAppStore } from "@/store"
import { Card, CardContent, CardHeader } from "../ui/card"; import { Card, CardContent, CardHeader } from "../ui/card"
import { Typography } from "../ui/typography"; import { Typography } from "../ui/typography"
import { differenceInDays } from "date-fns"; import { differenceInDays } from "date-fns";
import { Separator } from "../ui/separator"; import { Separator } from "../ui/separator";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../ui/table";
import { Button } from "../ui/button"; import { Button } from "../ui/button";
import { useAPIRoomCategories } from "@/api/api-roomCategories";
import { IconWithTooltip } from "../ui/icon-number-tooltip";
import { UserIcon } from "lucide-react";
type OnBookingClickFunction = () => void; type OnBookingClickFunction = () => void;
type BookingDetailsModes = "Book" | "View"; type BookingDetailsModes = "Book" | "View"
export function BookingDetails({ onBookingConfirm, mode }: { onBookingConfirm?: OnBookingClickFunction, mode: BookingDetailsModes }) {
export function BookingDetails({
onBookingConfirm,
mode,
}: {
onBookingConfirm?: OnBookingClickFunction;
mode: BookingDetailsModes;
}) {
const bookingData = useAppStore((state) => state.newBookingData); const bookingData = useAppStore((state) => state.newBookingData);
const roomCategoryList = useAPIRoomCategories();
const onBtBookingClick = () => { const onBtBookingClick = () => {
if (onBookingConfirm) { if (onBookingConfirm) {
onBookingConfirm(); onBookingConfirm();
} }
}; }
if (!bookingData || bookingData.rooms.length <= 0) { if (!bookingData || bookingData.rooms.length <= 0) {
return ( return (
<Card> <Card>
<CardHeader> <CardHeader>
<Typography variant={"h2"} as="h2"> <Typography variant={"h2"} as="h2">Your Booking</Typography>
Your Booking
</Typography>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<Typography variant={"h3"}>No rooms added yet</Typography> <Typography variant={"h3"}>No rooms added yet</Typography>
@@ -43,86 +33,63 @@ export function BookingDetails({
} }
const roomList = bookingData.rooms.map((room) => { const roomList = bookingData.rooms.map((room) => {
const category = roomCategoryList.roomCategoryList
?.filter((c) => c.id == room.roomCategory)
.at(0);
const photo = category?.roomCategoryPhotos.at(0);
return ( return (
<Card <TableRow key={room.roomCategory + "_" + room.guestNumber}>
key={room.roomCategory.toString() + room.guestNumber.toString()} <TableCell>{room.roomCategory}</TableCell>
className="my-3 flex flex-row bg-accent" <TableCell>{room.guestNumber}</TableCell>
> <TableCell>{room.amount}</TableCell>
{photo && ( <TableCell>{room.price / 100} €</TableCell>
<img <TableCell>{(room.price * room.amount) / 100} €</TableCell>
src={photo.path} </TableRow>
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, const roomTable = (
0, <Table>
<TableHeader>
<TableRow>
<TableHead>Room</TableHead>
<TableHead>Guests</TableHead>
<TableHead>Quantity</TableHead>
<TableHead>Unit price</TableHead>
<TableHead>Total price</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{roomList}
</TableBody>
</Table>
); );
const totalPrice = bookingData.rooms.reduce((acc, room) => (acc + (room.price * room.amount)), 0);
return ( return (
<Card> <Card>
<CardHeader> <CardHeader>
<Typography variant={"h2"} as="h2"> <Typography variant={"h2"} as="h2">Your Booking</Typography>
Your Booking
</Typography>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<Typography variant={"h3"}>Your Dates</Typography> <Typography variant={"h3"}>Your Dates</Typography>
<Typography variant={"largeText"}> <Typography variant={"largeText"}>
Arrival: {bookingData.arrivalDate.toLocaleDateString()} - Departure:{" "} Arrival: {bookingData.arrivalDate.toLocaleDateString()} -
{bookingData.departureDate.toLocaleDateString()} <br></br> Departure: {bookingData.departureDate.toLocaleDateString()} <br></br>
Number of nights:{" "} Number of nights: {differenceInDays(bookingData.departureDate, bookingData.arrivalDate)}
{differenceInDays(
bookingData.departureDate,
bookingData.arrivalDate,
) + 1}
</Typography> </Typography>
<Separator className="my-2"></Separator> <Separator className="my-2"></Separator>
<Typography variant={"h3"}>Your Rooms</Typography> <Typography variant={"h3"}>Your Rooms</Typography>
<div className="">{roomList}</div> {roomTable}
<Separator className="my-2"></Separator> <Separator className="my-2"></Separator>
<Typography variant={"h3"}>Total Price</Typography> <Typography variant={"h3"}>Total Price</Typography>
<Typography variant={"h3"}>{totalPrice / 100} €</Typography> <Typography variant={"h3"}>{totalPrice / 100} €</Typography>
{mode == "Book" && ( {
mode == "Book" &&
<Button className="my-2" onClick={onBtBookingClick}> <Button className="my-2" onClick={onBtBookingClick}>
<Typography <Typography variant={"largeText"} className="text-primary-foreground">Book it!</Typography>
variant={"largeText"}
className="text-primary-foreground"
>
Book it!
</Typography>
</Button> </Button>
)} }
</CardContent> </CardContent>
</Card> </Card>
); )
} }
+6 -6
View File
@@ -1,16 +1,16 @@
import { MoonIcon, SunIcon } from "@radix-ui/react-icons"; import { MoonIcon, SunIcon } from "@radix-ui/react-icons"
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button"
import { import {
DropdownMenu, DropdownMenu,
DropdownMenuContent, DropdownMenuContent,
DropdownMenuItem, DropdownMenuItem,
DropdownMenuTrigger, DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"; } from "@/components/ui/dropdown-menu"
import { useTheme } from "@/components/theme-provider"; import { useTheme } from "@/components/theme-provider"
export function ModeToggle() { export function ModeToggle() {
const { setTheme } = useTheme(); const { setTheme } = useTheme()
return ( return (
<DropdownMenu> <DropdownMenu>
@@ -33,5 +33,5 @@ export function ModeToggle() {
</DropdownMenuItem> </DropdownMenuItem>
</DropdownMenuContent> </DropdownMenuContent>
</DropdownMenu> </DropdownMenu>
); )
} }
+51 -51
View File
@@ -1,74 +1,74 @@
import { createContext, useContext, useEffect, useState } from "react"; import { createContext, useContext, useEffect, useState } from "react"
type Theme = "dark" | "light" | "system"; type Theme = "dark" | "light" | "system"
type ThemeProviderProps = { type ThemeProviderProps = {
children: React.ReactNode; children: React.ReactNode
defaultTheme?: Theme; defaultTheme?: Theme
storageKey?: string; storageKey?: string
}; }
type ThemeProviderState = { type ThemeProviderState = {
theme: Theme; theme: Theme
setTheme: (theme: Theme) => void; setTheme: (theme: Theme) => void
}; }
const initialState: ThemeProviderState = { const initialState: ThemeProviderState = {
theme: "system", theme: "system",
setTheme: () => null, setTheme: () => null,
}; }
const ThemeProviderContext = createContext<ThemeProviderState>(initialState); const ThemeProviderContext = createContext<ThemeProviderState>(initialState)
export function ThemeProvider({ export function ThemeProvider({
children, children,
defaultTheme = "system", defaultTheme = "system",
storageKey = "vite-ui-theme", storageKey = "vite-ui-theme",
...props ...props
}: ThemeProviderProps) { }: ThemeProviderProps) {
const [theme, setTheme] = useState<Theme>( const [theme, setTheme] = useState<Theme>(
() => (localStorage.getItem(storageKey) as Theme) || defaultTheme, () => (localStorage.getItem(storageKey) as Theme) || defaultTheme
); )
useEffect(() => { useEffect(() => {
const root = window.document.documentElement; const root = window.document.documentElement
root.classList.remove("light", "dark"); root.classList.remove("light", "dark")
if (theme === "system") { if (theme === "system") {
const systemTheme = window.matchMedia("(prefers-color-scheme: dark)") const systemTheme = window.matchMedia("(prefers-color-scheme: dark)")
.matches .matches
? "dark" ? "dark"
: "light"; : "light"
root.classList.add(systemTheme); root.classList.add(systemTheme)
return; return
}
root.classList.add(theme)
}, [theme])
const value = {
theme,
setTheme: (theme: Theme) => {
localStorage.setItem(storageKey, theme)
setTheme(theme)
},
} }
root.classList.add(theme); return (
}, [theme]); <ThemeProviderContext.Provider {...props} value={value}>
{children}
const value = { </ThemeProviderContext.Provider>
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 // eslint-disable-next-line react-refresh/only-export-components
export const useTheme = () => { export const useTheme = () => {
const context = useContext(ThemeProviderContext); const context = useContext(ThemeProviderContext)
if (context === undefined) if (context === undefined)
throw new Error("useTheme must be used within a ThemeProvider"); throw new Error("useTheme must be used within a ThemeProvider")
return context; return context
}; }
+7 -7
View File
@@ -1,7 +1,7 @@
import * as React from "react"; import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"; import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils"
const badgeVariants = cva( const badgeVariants = cva(
"inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2", "inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
@@ -20,8 +20,8 @@ const badgeVariants = cva(
defaultVariants: { defaultVariants: {
variant: "default", variant: "default",
}, },
}, }
); )
export interface BadgeProps export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>, extends React.HTMLAttributes<HTMLDivElement>,
@@ -30,7 +30,7 @@ export interface BadgeProps
function Badge({ className, variant, ...props }: BadgeProps) { function Badge({ className, variant, ...props }: BadgeProps) {
return ( return (
<div className={cn(badgeVariants({ variant }), className)} {...props} /> <div className={cn(badgeVariants({ variant }), className)} {...props} />
); )
} }
export { Badge }; export { Badge, badgeVariants }
+13 -14
View File
@@ -1,8 +1,8 @@
import * as React from "react"; import * as React from "react"
import { Slot } from "@radix-ui/react-slot"; import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"; import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils"
const buttonVariants = cva( const buttonVariants = cva(
"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50", "inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",
@@ -31,28 +31,27 @@ const buttonVariants = cva(
variant: "default", variant: "default",
size: "default", size: "default",
}, },
}, }
); )
export interface ButtonProps export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>, extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> { VariantProps<typeof buttonVariants> {
asChild?: boolean; asChild?: boolean
} }
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>( const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => { ({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"; const Comp = asChild ? Slot : "button"
return ( return (
<Comp <Comp
className={cn(buttonVariants({ variant, size, className }))} className={cn(buttonVariants({ variant, size, className }))}
ref={ref} ref={ref}
{...props} {...props}
/> />
); )
}, }
); )
Button.displayName = "Button"; Button.displayName = "Button"
// eslint-disable-next-line react-refresh/only-export-components export { Button, buttonVariants }
export { Button, buttonVariants };
+12 -12
View File
@@ -1,11 +1,11 @@
import * as React from "react"; import * as React from "react"
import { ChevronLeftIcon, ChevronRightIcon } from "@radix-ui/react-icons"; import { ChevronLeftIcon, ChevronRightIcon } from "@radix-ui/react-icons"
import { DayPicker } from "react-day-picker"; import { DayPicker } from "react-day-picker"
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button"; import { buttonVariants } from "@/components/ui/button"
export type CalendarProps = React.ComponentProps<typeof DayPicker>; export type CalendarProps = React.ComponentProps<typeof DayPicker>
function Calendar({ function Calendar({
className, className,
@@ -25,7 +25,7 @@ function Calendar({
nav: "space-x-1 flex items-center", nav: "space-x-1 flex items-center",
nav_button: cn( nav_button: cn(
buttonVariants({ variant: "outline" }), buttonVariants({ variant: "outline" }),
"h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100", "h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"
), ),
nav_button_previous: "absolute left-1", nav_button_previous: "absolute left-1",
nav_button_next: "absolute right-1", nav_button_next: "absolute right-1",
@@ -38,11 +38,11 @@ function Calendar({
"relative p-0 text-center text-sm focus-within:relative focus-within:z-20 [&:has([aria-selected])]:bg-accent [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected].day-range-end)]:rounded-r-md", "relative p-0 text-center text-sm focus-within:relative focus-within:z-20 [&:has([aria-selected])]:bg-accent [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected].day-range-end)]:rounded-r-md",
props.mode === "range" props.mode === "range"
? "[&:has(>.day-range-end)]:rounded-r-md [&:has(>.day-range-start)]:rounded-l-md first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md" ? "[&:has(>.day-range-end)]:rounded-r-md [&:has(>.day-range-start)]:rounded-l-md first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md"
: "[&:has([aria-selected])]:rounded-md", : "[&:has([aria-selected])]:rounded-md"
), ),
day: cn( day: cn(
buttonVariants({ variant: "ghost" }), buttonVariants({ variant: "ghost" }),
"h-8 w-8 p-0 font-normal aria-selected:opacity-100", "h-8 w-8 p-0 font-normal aria-selected:opacity-100"
), ),
day_range_start: "day-range-start", day_range_start: "day-range-start",
day_range_end: "day-range-end", day_range_end: "day-range-end",
@@ -63,8 +63,8 @@ function Calendar({
}} }}
{...props} {...props}
/> />
); )
} }
Calendar.displayName = "Calendar"; Calendar.displayName = "Calendar"
export { Calendar }; export { Calendar }
+16 -23
View File
@@ -1,6 +1,6 @@
import * as React from "react"; import * as React from "react"
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils"
const Card = React.forwardRef< const Card = React.forwardRef<
HTMLDivElement, HTMLDivElement,
@@ -10,12 +10,12 @@ const Card = React.forwardRef<
ref={ref} ref={ref}
className={cn( className={cn(
"rounded-xl border bg-card text-card-foreground shadow", "rounded-xl border bg-card text-card-foreground shadow",
className, className
)} )}
{...props} {...props}
/> />
)); ))
Card.displayName = "Card"; Card.displayName = "Card"
const CardHeader = React.forwardRef< const CardHeader = React.forwardRef<
HTMLDivElement, HTMLDivElement,
@@ -26,8 +26,8 @@ const CardHeader = React.forwardRef<
className={cn("flex flex-col space-y-1.5 p-6", className)} className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props} {...props}
/> />
)); ))
CardHeader.displayName = "CardHeader"; CardHeader.displayName = "CardHeader"
const CardTitle = React.forwardRef< const CardTitle = React.forwardRef<
HTMLParagraphElement, HTMLParagraphElement,
@@ -38,8 +38,8 @@ const CardTitle = React.forwardRef<
className={cn("font-semibold leading-none tracking-tight", className)} className={cn("font-semibold leading-none tracking-tight", className)}
{...props} {...props}
/> />
)); ))
CardTitle.displayName = "CardTitle"; CardTitle.displayName = "CardTitle"
const CardDescription = React.forwardRef< const CardDescription = React.forwardRef<
HTMLParagraphElement, HTMLParagraphElement,
@@ -50,16 +50,16 @@ const CardDescription = React.forwardRef<
className={cn("text-sm text-muted-foreground", className)} className={cn("text-sm text-muted-foreground", className)}
{...props} {...props}
/> />
)); ))
CardDescription.displayName = "CardDescription"; CardDescription.displayName = "CardDescription"
const CardContent = React.forwardRef< const CardContent = React.forwardRef<
HTMLDivElement, HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => ( >(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} /> <div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
)); ))
CardContent.displayName = "CardContent"; CardContent.displayName = "CardContent"
const CardFooter = React.forwardRef< const CardFooter = React.forwardRef<
HTMLDivElement, HTMLDivElement,
@@ -70,14 +70,7 @@ const CardFooter = React.forwardRef<
className={cn("flex items-center p-6 pt-0", className)} className={cn("flex items-center p-6 pt-0", className)}
{...props} {...props}
/> />
)); ))
CardFooter.displayName = "CardFooter"; CardFooter.displayName = "CardFooter"
export { export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
Card,
CardHeader,
CardFooter,
CardTitle,
CardDescription,
CardContent,
};
+80 -80
View File
@@ -1,43 +1,43 @@
import * as React from "react"; import * as React from "react"
import { ArrowLeftIcon, ArrowRightIcon } from "@radix-ui/react-icons"; import { ArrowLeftIcon, ArrowRightIcon } from "@radix-ui/react-icons"
import useEmblaCarousel, { import useEmblaCarousel, {
type UseEmblaCarouselType, type UseEmblaCarouselType,
} from "embla-carousel-react"; } from "embla-carousel-react"
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button"
type CarouselApi = UseEmblaCarouselType[1]; type CarouselApi = UseEmblaCarouselType[1]
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>; type UseCarouselParameters = Parameters<typeof useEmblaCarousel>
type CarouselOptions = UseCarouselParameters[0]; type CarouselOptions = UseCarouselParameters[0]
type CarouselPlugin = UseCarouselParameters[1]; type CarouselPlugin = UseCarouselParameters[1]
type CarouselProps = { type CarouselProps = {
opts?: CarouselOptions; opts?: CarouselOptions
plugins?: CarouselPlugin; plugins?: CarouselPlugin
orientation?: "horizontal" | "vertical"; orientation?: "horizontal" | "vertical"
setApi?: (api: CarouselApi) => void; setApi?: (api: CarouselApi) => void
}; }
type CarouselContextProps = { type CarouselContextProps = {
carouselRef: ReturnType<typeof useEmblaCarousel>[0]; carouselRef: ReturnType<typeof useEmblaCarousel>[0]
api: ReturnType<typeof useEmblaCarousel>[1]; api: ReturnType<typeof useEmblaCarousel>[1]
scrollPrev: () => void; scrollPrev: () => void
scrollNext: () => void; scrollNext: () => void
canScrollPrev: boolean; canScrollPrev: boolean
canScrollNext: boolean; canScrollNext: boolean
} & CarouselProps; } & CarouselProps
const CarouselContext = React.createContext<CarouselContextProps | null>(null); const CarouselContext = React.createContext<CarouselContextProps | null>(null)
function useCarousel() { function useCarousel() {
const context = React.useContext(CarouselContext); const context = React.useContext(CarouselContext)
if (!context) { if (!context) {
throw new Error("useCarousel must be used within a <Carousel />"); throw new Error("useCarousel must be used within a <Carousel />")
} }
return context; return context
} }
const Carousel = React.forwardRef< const Carousel = React.forwardRef<
@@ -54,69 +54,69 @@ const Carousel = React.forwardRef<
children, children,
...props ...props
}, },
ref, ref
) => { ) => {
const [carouselRef, api] = useEmblaCarousel( const [carouselRef, api] = useEmblaCarousel(
{ {
...opts, ...opts,
axis: orientation === "horizontal" ? "x" : "y", axis: orientation === "horizontal" ? "x" : "y",
}, },
plugins, plugins
); )
const [canScrollPrev, setCanScrollPrev] = React.useState(false); const [canScrollPrev, setCanScrollPrev] = React.useState(false)
const [canScrollNext, setCanScrollNext] = React.useState(false); const [canScrollNext, setCanScrollNext] = React.useState(false)
const onSelect = React.useCallback((api: CarouselApi) => { const onSelect = React.useCallback((api: CarouselApi) => {
if (!api) { if (!api) {
return; return
} }
setCanScrollPrev(api.canScrollPrev()); setCanScrollPrev(api.canScrollPrev())
setCanScrollNext(api.canScrollNext()); setCanScrollNext(api.canScrollNext())
}, []); }, [])
const scrollPrev = React.useCallback(() => { const scrollPrev = React.useCallback(() => {
api?.scrollPrev(); api?.scrollPrev()
}, [api]); }, [api])
const scrollNext = React.useCallback(() => { const scrollNext = React.useCallback(() => {
api?.scrollNext(); api?.scrollNext()
}, [api]); }, [api])
const handleKeyDown = React.useCallback( const handleKeyDown = React.useCallback(
(event: React.KeyboardEvent<HTMLDivElement>) => { (event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.key === "ArrowLeft") { if (event.key === "ArrowLeft") {
event.preventDefault(); event.preventDefault()
scrollPrev(); scrollPrev()
} else if (event.key === "ArrowRight") { } else if (event.key === "ArrowRight") {
event.preventDefault(); event.preventDefault()
scrollNext(); scrollNext()
} }
}, },
[scrollPrev, scrollNext], [scrollPrev, scrollNext]
); )
React.useEffect(() => { React.useEffect(() => {
if (!api || !setApi) { if (!api || !setApi) {
return; return
} }
setApi(api); setApi(api)
}, [api, setApi]); }, [api, setApi])
React.useEffect(() => { React.useEffect(() => {
if (!api) { if (!api) {
return; return
} }
onSelect(api); onSelect(api)
api.on("reInit", onSelect); api.on("reInit", onSelect)
api.on("select", onSelect); api.on("select", onSelect)
return () => { return () => {
api?.off("select", onSelect); api?.off("select", onSelect)
}; }
}, [api, onSelect]); }, [api, onSelect])
return ( return (
<CarouselContext.Provider <CarouselContext.Provider
@@ -143,16 +143,16 @@ const Carousel = React.forwardRef<
{children} {children}
</div> </div>
</CarouselContext.Provider> </CarouselContext.Provider>
); )
}, }
); )
Carousel.displayName = "Carousel"; Carousel.displayName = "Carousel"
const CarouselContent = React.forwardRef< const CarouselContent = React.forwardRef<
HTMLDivElement, HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => { >(({ className, ...props }, ref) => {
const { carouselRef, orientation } = useCarousel(); const { carouselRef, orientation } = useCarousel()
return ( return (
<div ref={carouselRef} className="overflow-hidden"> <div ref={carouselRef} className="overflow-hidden">
@@ -161,20 +161,20 @@ const CarouselContent = React.forwardRef<
className={cn( className={cn(
"flex", "flex",
orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col", orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
className, className
)} )}
{...props} {...props}
/> />
</div> </div>
); )
}); })
CarouselContent.displayName = "CarouselContent"; CarouselContent.displayName = "CarouselContent"
const CarouselItem = React.forwardRef< const CarouselItem = React.forwardRef<
HTMLDivElement, HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => { >(({ className, ...props }, ref) => {
const { orientation } = useCarousel(); const { orientation } = useCarousel()
return ( return (
<div <div
@@ -184,19 +184,19 @@ const CarouselItem = React.forwardRef<
className={cn( className={cn(
"min-w-0 shrink-0 grow-0 basis-full", "min-w-0 shrink-0 grow-0 basis-full",
orientation === "horizontal" ? "pl-4" : "pt-4", orientation === "horizontal" ? "pl-4" : "pt-4",
className, className
)} )}
{...props} {...props}
/> />
); )
}); })
CarouselItem.displayName = "CarouselItem"; CarouselItem.displayName = "CarouselItem"
const CarouselPrevious = React.forwardRef< const CarouselPrevious = React.forwardRef<
HTMLButtonElement, HTMLButtonElement,
React.ComponentProps<typeof Button> React.ComponentProps<typeof Button>
>(({ className, variant = "outline", size = "icon", ...props }, ref) => { >(({ className, variant = "outline", size = "icon", ...props }, ref) => {
const { orientation, scrollPrev, canScrollPrev } = useCarousel(); const { orientation, scrollPrev, canScrollPrev } = useCarousel()
return ( return (
<Button <Button
@@ -204,11 +204,11 @@ const CarouselPrevious = React.forwardRef<
variant={variant} variant={variant}
size={size} size={size}
className={cn( className={cn(
"absolute h-8 w-8 rounded-full", "absolute h-8 w-8 rounded-full",
orientation === "horizontal" orientation === "horizontal"
? "-left-12 top-1/2 -translate-y-1/2" ? "-left-12 top-1/2 -translate-y-1/2"
: "-top-12 left-1/2 -translate-x-1/2 rotate-90", : "-top-12 left-1/2 -translate-x-1/2 rotate-90",
className, className
)} )}
disabled={!canScrollPrev} disabled={!canScrollPrev}
onClick={scrollPrev} onClick={scrollPrev}
@@ -217,15 +217,15 @@ const CarouselPrevious = React.forwardRef<
<ArrowLeftIcon className="h-4 w-4" /> <ArrowLeftIcon className="h-4 w-4" />
<span className="sr-only">Previous slide</span> <span className="sr-only">Previous slide</span>
</Button> </Button>
); )
}); })
CarouselPrevious.displayName = "CarouselPrevious"; CarouselPrevious.displayName = "CarouselPrevious"
const CarouselNext = React.forwardRef< const CarouselNext = React.forwardRef<
HTMLButtonElement, HTMLButtonElement,
React.ComponentProps<typeof Button> React.ComponentProps<typeof Button>
>(({ className, variant = "outline", size = "icon", ...props }, ref) => { >(({ className, variant = "outline", size = "icon", ...props }, ref) => {
const { orientation, scrollNext, canScrollNext } = useCarousel(); const { orientation, scrollNext, canScrollNext } = useCarousel()
return ( return (
<Button <Button
@@ -237,7 +237,7 @@ const CarouselNext = React.forwardRef<
orientation === "horizontal" orientation === "horizontal"
? "-right-12 top-1/2 -translate-y-1/2" ? "-right-12 top-1/2 -translate-y-1/2"
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90", : "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
className, className
)} )}
disabled={!canScrollNext} disabled={!canScrollNext}
onClick={scrollNext} onClick={scrollNext}
@@ -246,9 +246,9 @@ const CarouselNext = React.forwardRef<
<ArrowRightIcon className="h-4 w-4" /> <ArrowRightIcon className="h-4 w-4" />
<span className="sr-only">Next slide</span> <span className="sr-only">Next slide</span>
</Button> </Button>
); )
}); })
CarouselNext.displayName = "CarouselNext"; CarouselNext.displayName = "CarouselNext"
export { export {
type CarouselApi, type CarouselApi,
@@ -257,4 +257,4 @@ export {
CarouselItem, CarouselItem,
CarouselPrevious, CarouselPrevious,
CarouselNext, CarouselNext,
}; }
+8 -8
View File
@@ -1,8 +1,8 @@
import * as React from "react"; import * as React from "react"
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"; import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
import { CheckIcon } from "@radix-ui/react-icons"; import { CheckIcon } from "@radix-ui/react-icons"
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils"
const Checkbox = React.forwardRef< const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>, React.ElementRef<typeof CheckboxPrimitive.Root>,
@@ -12,7 +12,7 @@ const Checkbox = React.forwardRef<
ref={ref} ref={ref}
className={cn( className={cn(
"peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground", "peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
className, className
)} )}
{...props} {...props}
> >
@@ -22,7 +22,7 @@ const Checkbox = React.forwardRef<
<CheckIcon className="h-4 w-4" /> <CheckIcon className="h-4 w-4" />
</CheckboxPrimitive.Indicator> </CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root> </CheckboxPrimitive.Root>
)); ))
Checkbox.displayName = CheckboxPrimitive.Root.displayName; Checkbox.displayName = CheckboxPrimitive.Root.displayName
export { Checkbox }; export { Checkbox }
+37 -53
View File
@@ -1,39 +1,27 @@
"use client"; "use client"
import * as React from "react"; import * as React from "react"
import { CalendarIcon } from "@radix-ui/react-icons"; import { CalendarIcon } from "@radix-ui/react-icons"
import { format } from "date-fns"; import { format } from "date-fns"
import { import { ActiveModifiers, DateBefore, DateRange, Matcher } from "react-day-picker"
ActiveModifiers,
DateBefore,
DateRange,
Matcher,
} from "react-day-picker";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button"
import { Calendar } from "@/components/ui/calendar"; import { Calendar } from "@/components/ui/calendar"
import { import {
Popover, Popover,
PopoverContent, PopoverContent,
PopoverTrigger, PopoverTrigger,
} from "@/components/ui/popover"; } from "@/components/ui/popover"
import { Typography } from "./typography"; import { Typography } from "./typography"
export type UpdateRangeFunction = (newRange: DateRange) => void; export type UpdateRangeFunction = (newRange: DateRange) => void;
export function DatePickerWithRange({ export function DatePickerWithRange({
className, className, updateDateRange, startDate, endDate, allowPast = true
updateDateRange,
startDate,
endDate,
allowPast = true,
}: { }: {
className?: React.HTMLAttributes<HTMLDivElement> | undefined; className?: React.HTMLAttributes<HTMLDivElement> | undefined, updateDateRange: UpdateRangeFunction | undefined,
updateDateRange: UpdateRangeFunction | undefined; startDate?: Date, endDate?: Date, allowPast?: boolean
startDate?: Date;
endDate?: Date;
allowPast?: boolean;
}) { }) {
// Date Range State. // Date Range State.
const [dateRange, setDateRange] = React.useState<DateRange | undefined>({ const [dateRange, setDateRange] = React.useState<DateRange | undefined>({
@@ -46,27 +34,27 @@ export function DatePickerWithRange({
const handleDayClickFrom = (day: Date, mods: ActiveModifiers) => { const handleDayClickFrom = (day: Date, mods: ActiveModifiers) => {
const newDateRange: DateRange = { const newDateRange: DateRange = {
from: mods.selected ? undefined : day, from: mods.selected ? undefined : day,
to: undefined, to: dateRange?.to
}; }
fnUpdateRange(newDateRange); setDateRange(newDateRange)
}; if (updateDateRange !== undefined) {
updateDateRange(newDateRange)
}
}
const handleDayClickTo = (day: Date, mods: ActiveModifiers) => { const handleDayClickTo = (day: Date, mods: ActiveModifiers) => {
const newDateRange: DateRange = { const newDateRange: DateRange = {
from: dateRange?.from, from: dateRange?.from,
to: mods.selected ? undefined : day, to: mods.selected ? undefined : day
};
fnUpdateRange(newDateRange);
};
const fnUpdateRange = (range: DateRange) => {
setDateRange(range);
if (updateDateRange !== undefined) {
updateDateRange(range);
} }
};
setDateRange(newDateRange)
if (updateDateRange !== undefined) {
updateDateRange(newDateRange)
}
}
// Disable days from "To" before "From" // Disable days from "To" before "From"
let beforeAndSelected: Matcher[] = []; let beforeAndSelected: Matcher[] = [];
@@ -82,13 +70,9 @@ export function DatePickerWithRange({
} }
return ( return (
<div className={cn("grid grid-cols-2 grid-rows-2 gap-x-2", className)}> <div className={cn("grid gap-x-2 grid-cols-2 grid-rows-2", className)}>
<Typography variant={"largeText"} as="p"> <Typography variant={"largeText"} as="p">Desde</Typography>
Desde <Typography variant={"largeText"} as="p">Hasta</Typography>
</Typography>
<Typography variant={"largeText"} as="p">
Hasta
</Typography>
<Popover> <Popover>
<PopoverTrigger asChild> <PopoverTrigger asChild>
<Button <Button
@@ -96,7 +80,7 @@ export function DatePickerWithRange({
variant={"outline"} variant={"outline"}
className={cn( className={cn(
"justify-start text-left font-normal", "justify-start text-left font-normal",
!dateRange && "text-muted-foreground", !dateRange && "text-muted-foreground"
)} )}
> >
<CalendarIcon className="mr-2 h-4 w-4" /> <CalendarIcon className="mr-2 h-4 w-4" />
@@ -107,7 +91,7 @@ export function DatePickerWithRange({
)} )}
</Button> </Button>
</PopoverTrigger> </PopoverTrigger>
<PopoverContent className="w-auto p-0" align="center"> <PopoverContent className="w-auto p-0" align="start">
<Calendar <Calendar
initialFocus initialFocus
mode="single" mode="single"
@@ -126,7 +110,7 @@ export function DatePickerWithRange({
variant={"outline"} variant={"outline"}
className={cn( className={cn(
"justify-start text-left font-normal", "justify-start text-left font-normal",
!dateRange && "text-muted-foreground", !dateRange && "text-muted-foreground"
)} )}
> >
<CalendarIcon className="mr-2 h-4 w-4" /> <CalendarIcon className="mr-2 h-4 w-4" />
@@ -137,11 +121,11 @@ export function DatePickerWithRange({
)} )}
</Button> </Button>
</PopoverTrigger> </PopoverTrigger>
<PopoverContent className="w-auto p-0" align="center"> <PopoverContent className="w-auto p-0" align="start">
<Calendar <Calendar
initialFocus initialFocus
mode="single" mode="single"
defaultMonth={dateRange?.to ?? dateRange?.from} defaultMonth={dateRange?.to}
selected={dateRange?.to} selected={dateRange?.to}
onDayClick={handleDayClickTo} onDayClick={handleDayClickTo}
numberOfMonths={1} numberOfMonths={1}
@@ -150,5 +134,5 @@ export function DatePickerWithRange({
</PopoverContent> </PopoverContent>
</Popover> </Popover>
</div> </div>
); )
} }
+40 -40
View File
@@ -1,29 +1,29 @@
import * as React from "react"; import * as React from "react"
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"; import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
import { import {
CheckIcon, CheckIcon,
ChevronRightIcon, ChevronRightIcon,
DotFilledIcon, DotFilledIcon,
} from "@radix-ui/react-icons"; } from "@radix-ui/react-icons"
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils"
const DropdownMenu = DropdownMenuPrimitive.Root; const DropdownMenu = DropdownMenuPrimitive.Root
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger; const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger
const DropdownMenuGroup = DropdownMenuPrimitive.Group; const DropdownMenuGroup = DropdownMenuPrimitive.Group
const DropdownMenuPortal = DropdownMenuPrimitive.Portal; const DropdownMenuPortal = DropdownMenuPrimitive.Portal
const DropdownMenuSub = DropdownMenuPrimitive.Sub; const DropdownMenuSub = DropdownMenuPrimitive.Sub
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup; const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup
const DropdownMenuSubTrigger = React.forwardRef< const DropdownMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>, React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & { React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean; inset?: boolean
} }
>(({ className, inset, children, ...props }, ref) => ( >(({ className, inset, children, ...props }, ref) => (
<DropdownMenuPrimitive.SubTrigger <DropdownMenuPrimitive.SubTrigger
@@ -31,16 +31,16 @@ const DropdownMenuSubTrigger = React.forwardRef<
className={cn( className={cn(
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent", "flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",
inset && "pl-8", inset && "pl-8",
className, className
)} )}
{...props} {...props}
> >
{children} {children}
<ChevronRightIcon className="ml-auto h-4 w-4" /> <ChevronRightIcon className="ml-auto h-4 w-4" />
</DropdownMenuPrimitive.SubTrigger> </DropdownMenuPrimitive.SubTrigger>
)); ))
DropdownMenuSubTrigger.displayName = DropdownMenuSubTrigger.displayName =
DropdownMenuPrimitive.SubTrigger.displayName; DropdownMenuPrimitive.SubTrigger.displayName
const DropdownMenuSubContent = React.forwardRef< const DropdownMenuSubContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>, React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
@@ -50,13 +50,13 @@ const DropdownMenuSubContent = React.forwardRef<
ref={ref} ref={ref}
className={cn( className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className, className
)} )}
{...props} {...props}
/> />
)); ))
DropdownMenuSubContent.displayName = DropdownMenuSubContent.displayName =
DropdownMenuPrimitive.SubContent.displayName; DropdownMenuPrimitive.SubContent.displayName
const DropdownMenuContent = React.forwardRef< const DropdownMenuContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Content>, React.ElementRef<typeof DropdownMenuPrimitive.Content>,
@@ -69,18 +69,18 @@ const DropdownMenuContent = React.forwardRef<
className={cn( className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md", "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md",
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className, className
)} )}
{...props} {...props}
/> />
</DropdownMenuPrimitive.Portal> </DropdownMenuPrimitive.Portal>
)); ))
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName; DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName
const DropdownMenuItem = React.forwardRef< const DropdownMenuItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Item>, React.ElementRef<typeof DropdownMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & { React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean; inset?: boolean
} }
>(({ className, inset, ...props }, ref) => ( >(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Item <DropdownMenuPrimitive.Item
@@ -88,12 +88,12 @@ const DropdownMenuItem = React.forwardRef<
className={cn( className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", "relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
inset && "pl-8", inset && "pl-8",
className, className
)} )}
{...props} {...props}
/> />
)); ))
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName; DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName
const DropdownMenuCheckboxItem = React.forwardRef< const DropdownMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>, React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
@@ -103,7 +103,7 @@ const DropdownMenuCheckboxItem = React.forwardRef<
ref={ref} ref={ref}
className={cn( className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className, className
)} )}
checked={checked} checked={checked}
{...props} {...props}
@@ -115,9 +115,9 @@ const DropdownMenuCheckboxItem = React.forwardRef<
</span> </span>
{children} {children}
</DropdownMenuPrimitive.CheckboxItem> </DropdownMenuPrimitive.CheckboxItem>
)); ))
DropdownMenuCheckboxItem.displayName = DropdownMenuCheckboxItem.displayName =
DropdownMenuPrimitive.CheckboxItem.displayName; DropdownMenuPrimitive.CheckboxItem.displayName
const DropdownMenuRadioItem = React.forwardRef< const DropdownMenuRadioItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>, React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
@@ -127,7 +127,7 @@ const DropdownMenuRadioItem = React.forwardRef<
ref={ref} ref={ref}
className={cn( className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50", "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className, className
)} )}
{...props} {...props}
> >
@@ -138,13 +138,13 @@ const DropdownMenuRadioItem = React.forwardRef<
</span> </span>
{children} {children}
</DropdownMenuPrimitive.RadioItem> </DropdownMenuPrimitive.RadioItem>
)); ))
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName; DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName
const DropdownMenuLabel = React.forwardRef< const DropdownMenuLabel = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Label>, React.ElementRef<typeof DropdownMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & { React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean; inset?: boolean
} }
>(({ className, inset, ...props }, ref) => ( >(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Label <DropdownMenuPrimitive.Label
@@ -152,12 +152,12 @@ const DropdownMenuLabel = React.forwardRef<
className={cn( className={cn(
"px-2 py-1.5 text-sm font-semibold", "px-2 py-1.5 text-sm font-semibold",
inset && "pl-8", inset && "pl-8",
className, className
)} )}
{...props} {...props}
/> />
)); ))
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName; DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName
const DropdownMenuSeparator = React.forwardRef< const DropdownMenuSeparator = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Separator>, React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
@@ -168,8 +168,8 @@ const DropdownMenuSeparator = React.forwardRef<
className={cn("-mx-1 my-1 h-px bg-muted", className)} className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props} {...props}
/> />
)); ))
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName; DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName
const DropdownMenuShortcut = ({ const DropdownMenuShortcut = ({
className, className,
@@ -180,9 +180,9 @@ const DropdownMenuShortcut = ({
className={cn("ml-auto text-xs tracking-widest opacity-60", className)} className={cn("ml-auto text-xs tracking-widest opacity-60", className)}
{...props} {...props}
/> />
); )
}; }
DropdownMenuShortcut.displayName = "DropdownMenuShortcut"; DropdownMenuShortcut.displayName = "DropdownMenuShortcut"
export { export {
DropdownMenu, DropdownMenu,
@@ -200,4 +200,4 @@ export {
DropdownMenuSubContent, DropdownMenuSubContent,
DropdownMenuSubTrigger, DropdownMenuSubTrigger,
DropdownMenuRadioGroup, DropdownMenuRadioGroup,
}; }
+17 -29
View File
@@ -1,47 +1,35 @@
import { Typography } from "./typography"; import { Typography } from "./typography";
import { import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "./tooltip";
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "./tooltip";
import { PropsWithChildren } from "react"; import { PropsWithChildren } from "react";
interface IconWithTooltipNumberProps { interface IconWithTooltipNumberProps {
label?: string | null | undefined; amount?: number | null |undefined,
labelPosition?: "left" | "right" | null | undefined; altText?: string | null | undefined
tooltipText?: string | null | undefined;
} }
export function IconWithTooltip({ export function IconWithTooltipNumber({ amount = undefined, altText = undefined, children }: PropsWithChildren<IconWithTooltipNumberProps>) {
label = undefined,
labelPosition = "left", const iconElement = altText ? (
tooltipText = undefined,
children,
}: PropsWithChildren<IconWithTooltipNumberProps>) {
const iconElement = tooltipText ? (
<TooltipProvider> <TooltipProvider>
<Tooltip> <Tooltip>
<TooltipTrigger asChild>{children}</TooltipTrigger> <TooltipTrigger asChild>
{children}
</TooltipTrigger>
<TooltipContent> <TooltipContent>
<p className="inline">{tooltipText}</p> <p>{altText}</p>
</TooltipContent> </TooltipContent>
</Tooltip> </Tooltip>
</TooltipProvider> </TooltipProvider>
) : ( ) : (
<>{children}</> <>
{children}
</>
); );
const labelElement = (
<Typography variant={"p_inline"} className="px-1">
{label}
</Typography>
);
return ( return (
<div className="flex flex-row items-center gap-1"> <>
{label && labelPosition == "left" && labelElement} {amount && <Typography variant={"p_inline"}>{amount}</Typography>}
{iconElement} {iconElement}
{label && labelPosition == "right" && labelElement} </>
</div> )
);
} }
+8 -8
View File
@@ -1,6 +1,6 @@
import * as React from "react"; import * as React from "react"
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils"
export interface InputProps export interface InputProps
extends React.InputHTMLAttributes<HTMLInputElement> {} extends React.InputHTMLAttributes<HTMLInputElement> {}
@@ -12,14 +12,14 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(
type={type} type={type}
className={cn( className={cn(
"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50", "flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
className, className
)} )}
ref={ref} ref={ref}
{...props} {...props}
/> />
); )
}, }
); )
Input.displayName = "Input"; Input.displayName = "Input"
export { Input }; export { Input }
+9 -9
View File
@@ -1,12 +1,12 @@
import * as React from "react"; import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"; import * as LabelPrimitive from "@radix-ui/react-label"
import { cva, type VariantProps } from "class-variance-authority"; import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils"
const labelVariants = cva( const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70", "text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
); )
const Label = React.forwardRef< const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>, React.ElementRef<typeof LabelPrimitive.Root>,
@@ -18,7 +18,7 @@ const Label = React.forwardRef<
className={cn(labelVariants(), className)} className={cn(labelVariants(), className)}
{...props} {...props}
/> />
)); ))
Label.displayName = LabelPrimitive.Root.displayName; Label.displayName = LabelPrimitive.Root.displayName
export { Label }; export { Label }
+14 -25
View File
@@ -1,18 +1,14 @@
import { useState } from "react"; import { useState } from "react"
import { Button } from "./button"; import { Button } from "./button";
import { Typography } from "./typography"; import { Typography } from "./typography";
export type UpdateSelectedNumberFunction = (newCount: number) => void; export type UpdateSelectedNumberFunction = (newCount: number) => void;
export function NumberSelector({ export function NumberSelector(
updateCount, { updateCount, addEnabled = true, allowNegative = false }:
addEnabled = true, { updateCount: UpdateSelectedNumberFunction, addEnabled?: boolean, allowNegative?: boolean }) {
allowNegative = false,
}: {
updateCount: UpdateSelectedNumberFunction;
addEnabled?: boolean;
allowNegative?: boolean;
}) {
const [count, setCount] = useState<number>(0); const [count, setCount] = useState<number>(0);
const counterUpdated = (newAmount: number) => { const counterUpdated = (newAmount: number) => {
@@ -21,24 +17,17 @@ export function NumberSelector({
if (updateCount != undefined) { if (updateCount != undefined) {
updateCount(newAmount); updateCount(newAmount);
} }
}; }
const minusDisabled = !allowNegative && count <= 0; const minusDisabled = (!allowNegative && count <= 0)
return ( return (
<div className="flex flex-row items-center gap-2"> <div className="flex flex-row items-center gap-2">
<Button <Button disabled={minusDisabled}
disabled={minusDisabled} onClick={() => counterUpdated(count - 1)}>-</Button>
onClick={() => counterUpdated(count - 1)} <Typography variant={"largeText"} className="mx-2">{count}</Typography>
> <Button disabled={!addEnabled}
- onClick={() => counterUpdated(count + 1)}>+</Button>
</Button>
<Typography variant={"largeText"} className="mx-2">
{count}
</Typography>
<Button disabled={!addEnabled} onClick={() => counterUpdated(count + 1)}>
+
</Button>
</div> </div>
); )
} }
+10 -10
View File
@@ -1,13 +1,13 @@
import * as React from "react"; import * as React from "react"
import * as PopoverPrimitive from "@radix-ui/react-popover"; import * as PopoverPrimitive from "@radix-ui/react-popover"
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils"
const Popover = PopoverPrimitive.Root; const Popover = PopoverPrimitive.Root
const PopoverTrigger = PopoverPrimitive.Trigger; const PopoverTrigger = PopoverPrimitive.Trigger
const PopoverAnchor = PopoverPrimitive.Anchor; const PopoverAnchor = PopoverPrimitive.Anchor
const PopoverContent = React.forwardRef< const PopoverContent = React.forwardRef<
React.ElementRef<typeof PopoverPrimitive.Content>, React.ElementRef<typeof PopoverPrimitive.Content>,
@@ -20,12 +20,12 @@ const PopoverContent = React.forwardRef<
sideOffset={sideOffset} sideOffset={sideOffset}
className={cn( className={cn(
"z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", "z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className, className
)} )}
{...props} {...props}
/> />
</PopoverPrimitive.Portal> </PopoverPrimitive.Portal>
)); ))
PopoverContent.displayName = PopoverPrimitive.Content.displayName; PopoverContent.displayName = PopoverPrimitive.Content.displayName
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }; export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }
+9 -9
View File
@@ -1,7 +1,7 @@
import * as React from "react"; import * as React from "react"
import * as SeparatorPrimitive from "@radix-ui/react-separator"; import * as SeparatorPrimitive from "@radix-ui/react-separator"
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils"
const Separator = React.forwardRef< const Separator = React.forwardRef<
React.ElementRef<typeof SeparatorPrimitive.Root>, React.ElementRef<typeof SeparatorPrimitive.Root>,
@@ -9,7 +9,7 @@ const Separator = React.forwardRef<
>( >(
( (
{ className, orientation = "horizontal", decorative = true, ...props }, { className, orientation = "horizontal", decorative = true, ...props },
ref, ref
) => ( ) => (
<SeparatorPrimitive.Root <SeparatorPrimitive.Root
ref={ref} ref={ref}
@@ -18,12 +18,12 @@ const Separator = React.forwardRef<
className={cn( className={cn(
"shrink-0 bg-border", "shrink-0 bg-border",
orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]", orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
className, className
)} )}
{...props} {...props}
/> />
), )
); )
Separator.displayName = SeparatorPrimitive.Root.displayName; Separator.displayName = SeparatorPrimitive.Root.displayName
export { Separator }; export { Separator }
+3 -3
View File
@@ -1,4 +1,4 @@
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils"
function Skeleton({ function Skeleton({
className, className,
@@ -9,7 +9,7 @@ function Skeleton({
className={cn("animate-pulse rounded-md bg-primary/10", className)} className={cn("animate-pulse rounded-md bg-primary/10", className)}
{...props} {...props}
/> />
); )
} }
export { Skeleton }; export { Skeleton }
+23 -23
View File
@@ -1,6 +1,6 @@
import * as React from "react"; import * as React from "react"
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils"
const Table = React.forwardRef< const Table = React.forwardRef<
HTMLTableElement, HTMLTableElement,
@@ -13,16 +13,16 @@ const Table = React.forwardRef<
{...props} {...props}
/> />
</div> </div>
)); ))
Table.displayName = "Table"; Table.displayName = "Table"
const TableHeader = React.forwardRef< const TableHeader = React.forwardRef<
HTMLTableSectionElement, HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement> React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => ( >(({ className, ...props }, ref) => (
<thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} /> <thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
)); ))
TableHeader.displayName = "TableHeader"; TableHeader.displayName = "TableHeader"
const TableBody = React.forwardRef< const TableBody = React.forwardRef<
HTMLTableSectionElement, HTMLTableSectionElement,
@@ -33,8 +33,8 @@ const TableBody = React.forwardRef<
className={cn("[&_tr:last-child]:border-0", className)} className={cn("[&_tr:last-child]:border-0", className)}
{...props} {...props}
/> />
)); ))
TableBody.displayName = "TableBody"; TableBody.displayName = "TableBody"
const TableFooter = React.forwardRef< const TableFooter = React.forwardRef<
HTMLTableSectionElement, HTMLTableSectionElement,
@@ -44,12 +44,12 @@ const TableFooter = React.forwardRef<
ref={ref} ref={ref}
className={cn( className={cn(
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0", "border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
className, className
)} )}
{...props} {...props}
/> />
)); ))
TableFooter.displayName = "TableFooter"; TableFooter.displayName = "TableFooter"
const TableRow = React.forwardRef< const TableRow = React.forwardRef<
HTMLTableRowElement, HTMLTableRowElement,
@@ -59,12 +59,12 @@ const TableRow = React.forwardRef<
ref={ref} ref={ref}
className={cn( className={cn(
"border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted", "border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
className, className
)} )}
{...props} {...props}
/> />
)); ))
TableRow.displayName = "TableRow"; TableRow.displayName = "TableRow"
const TableHead = React.forwardRef< const TableHead = React.forwardRef<
HTMLTableCellElement, HTMLTableCellElement,
@@ -74,12 +74,12 @@ const TableHead = React.forwardRef<
ref={ref} ref={ref}
className={cn( className={cn(
"h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]", "h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className, className
)} )}
{...props} {...props}
/> />
)); ))
TableHead.displayName = "TableHead"; TableHead.displayName = "TableHead"
const TableCell = React.forwardRef< const TableCell = React.forwardRef<
HTMLTableCellElement, HTMLTableCellElement,
@@ -89,12 +89,12 @@ const TableCell = React.forwardRef<
ref={ref} ref={ref}
className={cn( className={cn(
"p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]", "p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className, className
)} )}
{...props} {...props}
/> />
)); ))
TableCell.displayName = "TableCell"; TableCell.displayName = "TableCell"
const TableCaption = React.forwardRef< const TableCaption = React.forwardRef<
HTMLTableCaptionElement, HTMLTableCaptionElement,
@@ -105,8 +105,8 @@ const TableCaption = React.forwardRef<
className={cn("mt-4 text-sm text-muted-foreground", className)} className={cn("mt-4 text-sm text-muted-foreground", className)}
{...props} {...props}
/> />
)); ))
TableCaption.displayName = "TableCaption"; TableCaption.displayName = "TableCaption"
export { export {
Table, Table,
@@ -117,4 +117,4 @@ export {
TableRow, TableRow,
TableCell, TableCell,
TableCaption, TableCaption,
}; }
+27 -27
View File
@@ -1,11 +1,11 @@
import * as React from "react"; import * as React from "react"
import { Cross2Icon } from "@radix-ui/react-icons"; import { Cross2Icon } from "@radix-ui/react-icons"
import * as ToastPrimitives from "@radix-ui/react-toast"; import * as ToastPrimitives from "@radix-ui/react-toast"
import { cva, type VariantProps } from "class-variance-authority"; import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils"
const ToastProvider = ToastPrimitives.Provider; const ToastProvider = ToastPrimitives.Provider
const ToastViewport = React.forwardRef< const ToastViewport = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Viewport>, React.ElementRef<typeof ToastPrimitives.Viewport>,
@@ -15,12 +15,12 @@ const ToastViewport = React.forwardRef<
ref={ref} ref={ref}
className={cn( className={cn(
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]", "fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
className, className
)} )}
{...props} {...props}
/> />
)); ))
ToastViewport.displayName = ToastPrimitives.Viewport.displayName; ToastViewport.displayName = ToastPrimitives.Viewport.displayName
const toastVariants = cva( const toastVariants = cva(
"group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full", "group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",
@@ -35,8 +35,8 @@ const toastVariants = cva(
defaultVariants: { defaultVariants: {
variant: "default", variant: "default",
}, },
}, }
); )
const Toast = React.forwardRef< const Toast = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Root>, React.ElementRef<typeof ToastPrimitives.Root>,
@@ -49,9 +49,9 @@ const Toast = React.forwardRef<
className={cn(toastVariants({ variant }), className)} className={cn(toastVariants({ variant }), className)}
{...props} {...props}
/> />
); )
}); })
Toast.displayName = ToastPrimitives.Root.displayName; Toast.displayName = ToastPrimitives.Root.displayName
const ToastAction = React.forwardRef< const ToastAction = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Action>, React.ElementRef<typeof ToastPrimitives.Action>,
@@ -61,12 +61,12 @@ const ToastAction = React.forwardRef<
ref={ref} ref={ref}
className={cn( className={cn(
"inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive", "inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",
className, className
)} )}
{...props} {...props}
/> />
)); ))
ToastAction.displayName = ToastPrimitives.Action.displayName; ToastAction.displayName = ToastPrimitives.Action.displayName
const ToastClose = React.forwardRef< const ToastClose = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Close>, React.ElementRef<typeof ToastPrimitives.Close>,
@@ -76,15 +76,15 @@ const ToastClose = React.forwardRef<
ref={ref} ref={ref}
className={cn( className={cn(
"absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600", "absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
className, className
)} )}
toast-close="" toast-close=""
{...props} {...props}
> >
<Cross2Icon className="h-4 w-4" /> <Cross2Icon className="h-4 w-4" />
</ToastPrimitives.Close> </ToastPrimitives.Close>
)); ))
ToastClose.displayName = ToastPrimitives.Close.displayName; ToastClose.displayName = ToastPrimitives.Close.displayName
const ToastTitle = React.forwardRef< const ToastTitle = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Title>, React.ElementRef<typeof ToastPrimitives.Title>,
@@ -95,8 +95,8 @@ const ToastTitle = React.forwardRef<
className={cn("text-sm font-semibold [&+div]:text-xs", className)} className={cn("text-sm font-semibold [&+div]:text-xs", className)}
{...props} {...props}
/> />
)); ))
ToastTitle.displayName = ToastPrimitives.Title.displayName; ToastTitle.displayName = ToastPrimitives.Title.displayName
const ToastDescription = React.forwardRef< const ToastDescription = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Description>, React.ElementRef<typeof ToastPrimitives.Description>,
@@ -107,12 +107,12 @@ const ToastDescription = React.forwardRef<
className={cn("text-sm opacity-90", className)} className={cn("text-sm opacity-90", className)}
{...props} {...props}
/> />
)); ))
ToastDescription.displayName = ToastPrimitives.Description.displayName; ToastDescription.displayName = ToastPrimitives.Description.displayName
type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>; type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>
type ToastActionElement = React.ReactElement<typeof ToastAction>; type ToastActionElement = React.ReactElement<typeof ToastAction>
export { export {
type ToastProps, type ToastProps,
@@ -124,4 +124,4 @@ export {
ToastDescription, ToastDescription,
ToastClose, ToastClose,
ToastAction, ToastAction,
}; }
+5 -5
View File
@@ -5,11 +5,11 @@ import {
ToastProvider, ToastProvider,
ToastTitle, ToastTitle,
ToastViewport, ToastViewport,
} from "@/components/ui/toast"; } from "@/components/ui/toast"
import { useToast } from "@/components/ui/use-toast"; import { useToast } from "@/components/ui/use-toast"
export function Toaster() { export function Toaster() {
const { toasts } = useToast(); const { toasts } = useToast()
return ( return (
<ToastProvider> <ToastProvider>
@@ -25,9 +25,9 @@ export function Toaster() {
{action} {action}
<ToastClose /> <ToastClose />
</Toast> </Toast>
); )
})} })}
<ToastViewport /> <ToastViewport />
</ToastProvider> </ToastProvider>
); )
} }
+10 -10
View File
@@ -1,13 +1,13 @@
import * as React from "react"; import * as React from "react"
import * as TooltipPrimitive from "@radix-ui/react-tooltip"; import * as TooltipPrimitive from "@radix-ui/react-tooltip"
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils"
const TooltipProvider = TooltipPrimitive.Provider; const TooltipProvider = TooltipPrimitive.Provider
const Tooltip = TooltipPrimitive.Root; const Tooltip = TooltipPrimitive.Root
const TooltipTrigger = TooltipPrimitive.Trigger; const TooltipTrigger = TooltipPrimitive.Trigger
const TooltipContent = React.forwardRef< const TooltipContent = React.forwardRef<
React.ElementRef<typeof TooltipPrimitive.Content>, React.ElementRef<typeof TooltipPrimitive.Content>,
@@ -18,11 +18,11 @@ const TooltipContent = React.forwardRef<
sideOffset={sideOffset} sideOffset={sideOffset}
className={cn( className={cn(
"z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2", "z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className, className
)} )}
{...props} {...props}
/> />
)); ))
TooltipContent.displayName = TooltipPrimitive.Content.displayName; TooltipContent.displayName = TooltipPrimitive.Content.displayName
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }; export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
+63 -63
View File
@@ -1,82 +1,82 @@
"use client"; 'use client';
import * as React from "react"; import * as React from 'react';
import { VariantProps, cva } from "class-variance-authority"; import { VariantProps, cva } from 'class-variance-authority';
import { cn } from "@/lib/utils"; import { cn } from '@/lib/utils';
import { Slot } from "@radix-ui/react-slot"; import { Slot } from '@radix-ui/react-slot';
const typographyVariants = cva("text-foreground", { const typographyVariants = cva('text-foreground', {
variants: { variants: {
variant: { variant: {
h1: "scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl", h1: 'scroll-m-20 text-4xl font-extrabold tracking-tight lg:text-5xl',
h2: "scroll-m-20 border-b pb-2 text-3xl font-semibold tracking-tight first:mt-0", 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", h3: 'scroll-m-20 text-2xl font-semibold tracking-tight',
h4: "scroll-m-20 text-xl font-semibold tracking-tight", h4: 'scroll-m-20 text-xl font-semibold tracking-tight',
h5: "scroll-m-20 text-lg font-semibold tracking-tight", h5: 'scroll-m-20 text-lg font-semibold tracking-tight',
h6: "scroll-m-20 text-base font-semibold tracking-tight", h6: 'scroll-m-20 text-base font-semibold tracking-tight',
p: "leading-7 [&:not(:first-child)]:mt-6", p: 'leading-7 [&:not(:first-child)]:mt-6',
p_inline: "leading-7", p_inline: 'leading-7',
blockquote: "mt-6 border-l-2 pl-6 italic", blockquote: 'mt-6 border-l-2 pl-6 italic',
ul: "my-6 ml-6 list-disc [&>li]:mt-2", ul: 'my-6 ml-6 list-disc [&>li]:mt-2',
inlineCode: inlineCode:
"relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold", 'relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold',
lead: "text-xl text-muted-foreground", lead: 'text-xl text-muted-foreground',
largeText: "text-lg font-semibold", largeText: 'text-lg font-semibold',
smallText: "text-sm font-medium leading-none", smallText: 'text-sm font-medium leading-none',
mutedText: "text-sm text-muted-foreground", mutedText: 'text-sm text-muted-foreground',
},
},
defaultVariants: {
variant: "p",
}, },
},
defaultVariants: {
variant: "p",
},
}); });
type VariantPropType = VariantProps<typeof typographyVariants>; type VariantPropType = VariantProps<typeof typographyVariants>;
const variantElementMap: Record< const variantElementMap: Record<
NonNullable<VariantPropType["variant"]>, NonNullable<VariantPropType['variant']>,
string string
> = { > = {
h1: "h1", h1: 'h1',
h2: "h2", h2: 'h2',
h3: "h3", h3: 'h3',
h4: "h4", h4: 'h4',
h5: "h5", h5: 'h5',
h6: "h6", h6: 'h6',
p: "p", p: 'p',
p_inline: "p", p_inline: 'p',
blockquote: "blockquote", blockquote: 'blockquote',
inlineCode: "code", inlineCode: 'code',
largeText: "div", largeText: 'div',
smallText: "small", smallText: 'small',
lead: "p", lead: 'p',
mutedText: "p", mutedText: 'p',
ul: "ul", ul: 'ul',
}; };
export interface TypographyProps export interface TypographyProps
extends React.HTMLAttributes<HTMLElement>, extends React.HTMLAttributes<HTMLElement>,
VariantProps<typeof typographyVariants> { VariantProps<typeof typographyVariants> {
asChild?: boolean; asChild?: boolean;
as?: string; as?: string;
} }
const Typography = React.forwardRef<HTMLElement, TypographyProps>( const Typography = React.forwardRef<HTMLElement, TypographyProps>(
({ className, variant, as, asChild, ...props }, ref) => { ({ className, variant, as, asChild, ...props }, ref) => {
const Comp = asChild const Comp = asChild
? Slot ? Slot
: (as ?? (variant ? variantElementMap[variant] : undefined) ?? "div"); : as ?? (variant ? variantElementMap[variant] : undefined) ?? 'div';
return ( return (
<Comp <Comp
className={cn(typographyVariants({ variant, className }))} className={cn(typographyVariants({ variant, className }))}
ref={ref} ref={ref}
{...props} {...props}
/> />
); );
}, }
); );
Typography.displayName = "Typography"; Typography.displayName = 'Typography';
// eslint-disable-next-line react-refresh/only-export-components // eslint-disable-next-line react-refresh/only-export-components
export { Typography, typographyVariants }; export { Typography, typographyVariants };
+71 -68
View File
@@ -1,73 +1,76 @@
// Inspired by react-hot-toast library // Inspired by react-hot-toast library
import * as React from "react"; import * as React from "react"
import type { ToastActionElement, ToastProps } from "src/components/ui/toast"; import type {
ToastActionElement,
ToastProps,
} from "src/components/ui/toast"
const TOAST_LIMIT = 1; const TOAST_LIMIT = 1
const TOAST_REMOVE_DELAY = 1000000; const TOAST_REMOVE_DELAY = 1000000
type ToasterToast = ToastProps & { type ToasterToast = ToastProps & {
id: string; id: string
title?: React.ReactNode; title?: React.ReactNode
description?: React.ReactNode; description?: React.ReactNode
action?: ToastActionElement; action?: ToastActionElement
}; }
const actionTypes = { const actionTypes = {
ADD_TOAST: "ADD_TOAST", ADD_TOAST: "ADD_TOAST",
UPDATE_TOAST: "UPDATE_TOAST", UPDATE_TOAST: "UPDATE_TOAST",
DISMISS_TOAST: "DISMISS_TOAST", DISMISS_TOAST: "DISMISS_TOAST",
REMOVE_TOAST: "REMOVE_TOAST", REMOVE_TOAST: "REMOVE_TOAST",
} as const; } as const
let count = 0; let count = 0
function genId() { function genId() {
count = (count + 1) % Number.MAX_SAFE_INTEGER; count = (count + 1) % Number.MAX_SAFE_INTEGER
return count.toString(); return count.toString()
} }
type ActionType = typeof actionTypes; type ActionType = typeof actionTypes
type Action = type Action =
| { | {
type: ActionType["ADD_TOAST"]; type: ActionType["ADD_TOAST"]
toast: ToasterToast; toast: ToasterToast
} }
| { | {
type: ActionType["UPDATE_TOAST"]; type: ActionType["UPDATE_TOAST"]
toast: Partial<ToasterToast>; toast: Partial<ToasterToast>
} }
| { | {
type: ActionType["DISMISS_TOAST"]; type: ActionType["DISMISS_TOAST"]
toastId?: ToasterToast["id"]; toastId?: ToasterToast["id"]
} }
| { | {
type: ActionType["REMOVE_TOAST"]; type: ActionType["REMOVE_TOAST"]
toastId?: ToasterToast["id"]; toastId?: ToasterToast["id"]
}; }
interface State { interface State {
toasts: ToasterToast[]; toasts: ToasterToast[]
} }
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>(); const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()
const addToRemoveQueue = (toastId: string) => { const addToRemoveQueue = (toastId: string) => {
if (toastTimeouts.has(toastId)) { if (toastTimeouts.has(toastId)) {
return; return
} }
const timeout = setTimeout(() => { const timeout = setTimeout(() => {
toastTimeouts.delete(toastId); toastTimeouts.delete(toastId)
dispatch({ dispatch({
type: "REMOVE_TOAST", type: "REMOVE_TOAST",
toastId: toastId, toastId: toastId,
}); })
}, TOAST_REMOVE_DELAY); }, TOAST_REMOVE_DELAY)
toastTimeouts.set(toastId, timeout); toastTimeouts.set(toastId, timeout)
}; }
export const reducer = (state: State, action: Action): State => { export const reducer = (state: State, action: Action): State => {
switch (action.type) { switch (action.type) {
@@ -75,27 +78,27 @@ export const reducer = (state: State, action: Action): State => {
return { return {
...state, ...state,
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT), toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
}; }
case "UPDATE_TOAST": case "UPDATE_TOAST":
return { return {
...state, ...state,
toasts: state.toasts.map((t) => toasts: state.toasts.map((t) =>
t.id === action.toast.id ? { ...t, ...action.toast } : t, t.id === action.toast.id ? { ...t, ...action.toast } : t
), ),
}; }
case "DISMISS_TOAST": { case "DISMISS_TOAST": {
const { toastId } = action; const { toastId } = action
// ! Side effects ! - This could be extracted into a dismissToast() action, // ! Side effects ! - This could be extracted into a dismissToast() action,
// but I'll keep it here for simplicity // but I'll keep it here for simplicity
if (toastId) { if (toastId) {
addToRemoveQueue(toastId); addToRemoveQueue(toastId)
} else { } else {
state.toasts.forEach((toast) => { state.toasts.forEach((toast) => {
addToRemoveQueue(toast.id); addToRemoveQueue(toast.id)
}); })
} }
return { return {
@@ -106,46 +109,46 @@ export const reducer = (state: State, action: Action): State => {
...t, ...t,
open: false, open: false,
} }
: t, : t
), ),
}; }
} }
case "REMOVE_TOAST": case "REMOVE_TOAST":
if (action.toastId === undefined) { if (action.toastId === undefined) {
return { return {
...state, ...state,
toasts: [], toasts: [],
}; }
} }
return { return {
...state, ...state,
toasts: state.toasts.filter((t) => t.id !== action.toastId), toasts: state.toasts.filter((t) => t.id !== action.toastId),
}; }
} }
};
const listeners: Array<(state: State) => void> = [];
let memoryState: State = { toasts: [] };
function dispatch(action: Action) {
memoryState = reducer(memoryState, action);
listeners.forEach((listener) => {
listener(memoryState);
});
} }
type Toast = Omit<ToasterToast, "id">; const listeners: Array<(state: State) => void> = []
let memoryState: State = { toasts: [] }
function dispatch(action: Action) {
memoryState = reducer(memoryState, action)
listeners.forEach((listener) => {
listener(memoryState)
})
}
type Toast = Omit<ToasterToast, "id">
function toast({ ...props }: Toast) { function toast({ ...props }: Toast) {
const id = genId(); const id = genId()
const update = (props: ToasterToast) => const update = (props: ToasterToast) =>
dispatch({ dispatch({
type: "UPDATE_TOAST", type: "UPDATE_TOAST",
toast: { ...props, id }, toast: { ...props, id },
}); })
const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id }); const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id })
dispatch({ dispatch({
type: "ADD_TOAST", type: "ADD_TOAST",
@@ -154,36 +157,36 @@ function toast({ ...props }: Toast) {
id, id,
open: true, open: true,
onOpenChange: (open) => { onOpenChange: (open) => {
if (!open) dismiss(); if (!open) dismiss()
}, },
}, },
}); })
return { return {
id: id, id: id,
dismiss, dismiss,
update, update,
}; }
} }
function useToast() { function useToast() {
const [state, setState] = React.useState<State>(memoryState); const [state, setState] = React.useState<State>(memoryState)
React.useEffect(() => { React.useEffect(() => {
listeners.push(setState); listeners.push(setState)
return () => { return () => {
const index = listeners.indexOf(setState); const index = listeners.indexOf(setState)
if (index > -1) { if (index > -1) {
listeners.splice(index, 1); listeners.splice(index, 1)
} }
}; }
}, [state]); }, [state])
return { return {
...state, ...state,
toast, toast,
dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }), dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
}; }
} }
export { useToast, toast }; export { useToast, toast }
+3 -2
View File
@@ -1,8 +1,9 @@
import { useRouteError } from "react-router-dom"; import { useRouteError } from "react-router-dom";
export default function ErrorPage() { export default function ErrorPage() {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
const error: any = useRouteError(); const error : any = useRouteError();
console.error(error); console.error(error);
return ( return (
@@ -14,4 +15,4 @@ export default function ErrorPage() {
</p> </p>
</div> </div>
); );
} }
+2 -1
View File
@@ -2,6 +2,7 @@
@tailwind components; @tailwind components;
@tailwind utilities; @tailwind utilities;
@layer base { @layer base {
:root { :root {
--background: 0 0% 100%; --background: 0 0% 100%;
@@ -57,4 +58,4 @@
body { body {
@apply bg-background text-foreground; @apply bg-background text-foreground;
} }
} }
+3 -3
View File
@@ -1,6 +1,6 @@
import { type ClassValue, clsx } from "clsx"; import { type ClassValue, clsx } from "clsx"
import { twMerge } from "tailwind-merge"; import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) { export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs)); return twMerge(clsx(inputs))
} }
+21 -19
View File
@@ -1,13 +1,13 @@
import React from "react"; import React from 'react'
import ReactDOM from "react-dom/client"; import ReactDOM from 'react-dom/client'
import "./index.css"; import './index.css'
import { RouterProvider, createBrowserRouter } from "react-router-dom"; import { RouterProvider, createBrowserRouter } from 'react-router-dom';
import Root from "./routes/Root"; import Root from './routes/Root';
import ErrorPage from "./error-page"; import ErrorPage from './error-page';
import Homepage from "./routes/home-page"; import Homepage from './routes/home-page';
import SearchPage from "./routes/search-page"; import SearchPage from './routes/search-page';
import BookPage from "./routes/book-page"; import BookPage from './routes/book-page';
import SuccessPage from "./routes/success-page"; import SuccessPage from './routes/success-page';
const router = createBrowserRouter([ const router = createBrowserRouter([
{ {
@@ -17,30 +17,32 @@ const router = createBrowserRouter([
children: [ children: [
{ {
path: "/", path: "/",
element: <Homepage />, element: <Homepage />
}, },
{ {
path: "/home", path: "/home",
element: <Homepage />, element: <Homepage />
}, },
{ {
path: "/search", path: "/search",
element: <SearchPage />, element: <SearchPage />
}, },
{ {
path: "/book", path: "/book",
element: <BookPage />, element: <BookPage />
}, },
{ {
path: "/success", path: "/success",
element: <SuccessPage />, element: <SuccessPage />
}, }
], ]
}, },
]); ]);
ReactDOM.createRoot(document.getElementById("root")!).render(
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode> <React.StrictMode>
<RouterProvider router={router} /> <RouterProvider router={router} />
</React.StrictMode>, </React.StrictMode>,
); )
+15 -14
View File
@@ -1,24 +1,25 @@
export type NewBooking = { export type NewBooking = {
arrivalDate: Date; arrivalDate: Date,
departureDate: Date; departureDate: Date,
customerDetails: NewBookingCustomerDetails; customerDetails: NewBookingCustomerDetails,
rooms: NewBookingRoom[]; rooms: NewBookingRoom[]
}; };
export type NewBookingCustomerDetails = { export type NewBookingCustomerDetails = {
name: string | null; name: string | null,
surname: string | null; surname: string | null,
email: string | null; email: string | null,
phoneNumber: string | null; phoneNumber: string | null
}; };
export type NewBookingRoom = { export type NewBookingRoom = {
roomCategory: number; roomCategory: number,
guestNumber: number; guestNumber: number,
amount: number; amount: number,
price: number; price: number
}; };
export type NewBookingResponse = { export type NewBookingResponse = {
refNumber: number; refNumber: number,
}; }
+19 -17
View File
@@ -1,22 +1,24 @@
export type RoomCategory = { export type RoomCategory = {
id: number; id: number,
name: string; name: string,
description: string; description: string,
bedType: string; bedType: string,
maxGuestNum: number; maxGuestNum: number,
roomCategoryPhotos: RoomCategoryPhoto[]; roomCategoryPhotos: RoomCategoryPhoto[],
roomCategoryDetails: RoomCategoryDetails[]; roomCategoryDetails: RoomCategoryDetails[],
}; }
export type RoomCategoryDetails = { export type RoomCategoryDetails = {
id: number; id: number,
detailsSection: string; detailsSection: string,
detailValue: string; detailValue: string,
}; }
export type RoomCategoryPhoto = { export type RoomCategoryPhoto = {
id: number; id: number,
path: string; path: string,
altText: string | undefined; altText: string | undefined,
kind: string; kind: string,
}; }
+19 -17
View File
@@ -1,28 +1,30 @@
export type RoomAvailabity = { export type RoomAvailabity = {
roomCategory: number; roomCategory: number,
availability: number; availability: number
}; }
export type RoomPrice = { export type RoomPrice = {
guestNumber: number; guestNumber: number,
price: number; price: number
}; }
export type AvailabilityRequest = { export type AvailabilityRequest = {
filter: AvailabilityFilter; filter: AvailabilityFilter
}; }
export type AvailabilityFilter = { export type AvailabilityFilter = {
startDate: string; startDate: string,
endDate: string; endDate: string
}; }
export type FareRequest = { export type FareRequest = {
filter: FareFilter; filter: FareFilter
}; }
export type FareFilter = { export type FareFilter = {
roomCategory: number; roomCategory: number,
startDate: string; startDate: string,
endDate: string; endDate: string
}; }
+3 -3
View File
@@ -1,5 +1,5 @@
import { DateRange } from "react-day-picker"; import { DateRange } from "react-day-picker"
export type SearchFilter = { export type SearchFilter = {
dateRange: DateRange; dateRange: DateRange
}; }
File diff suppressed because it is too large Load Diff

Before

Width:  |  Height:  |  Size: 133 KiB

File diff suppressed because it is too large Load Diff

Before

Width:  |  Height:  |  Size: 96 KiB

+2 -1
View File
@@ -8,9 +8,10 @@ html {
box-sizing: inherit; box-sizing: inherit;
} }
.appPage { .appPage {
width: 80%; width: 80%;
margin: 0 auto; margin: 0 auto;
padding: 2rem; padding: 2rem;
text-align: center; text-align: center;
} }
+10 -9
View File
@@ -1,23 +1,24 @@
import { Outlet } from "react-router-dom"; import { Outlet } from 'react-router-dom'
import "./Root.css"; import './Root.css'
import AppHeader from "../components/app-header"; import AppHeader from '../components/app-header'
import AppFooter from "../components/app-footer"; import AppFooter from '../components/app-footer'
import { ThemeProvider } from "@/components/theme-provider"; import { ThemeProvider } from '@/components/theme-provider'
import { Toaster } from "@/components/ui/toaster"; import { Toaster } from '@/components/ui/toaster'
function Root() { function Root() {
return ( return (
<> <>
<ThemeProvider defaultTheme="dark" storageKey="vite-ui-theme"> <ThemeProvider defaultTheme="dark" storageKey="vite-ui-theme">
<AppHeader /> <AppHeader />
<div className="mx-auto w-full bg-background p-8 text-center text-foreground sm:w-[90%] md:w-[80%]"> <div className='appPage bg-background text-foreground'>
<Outlet /> <Outlet />
</div> </div>
<Toaster /> <Toaster />
<AppFooter /> <AppFooter />
</ThemeProvider> </ThemeProvider>
</> </>
); )
} }
export default Root; export default Root
+32 -68
View File
@@ -1,26 +1,23 @@
import { APISendCreateBooking } from "@/api/api-booking"; import { APISendCreateBooking } from "@/api/api-booking"
import { BookingDetails } from "@/components/booking/booking-details"; import { BookingDetails } from "@/components/booking/booking-details"
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label"
import { Separator } from "@/components/ui/separator"; import { Separator } from "@/components/ui/separator"
import { Typography } from "@/components/ui/typography"; import { Typography } from "@/components/ui/typography"
import { useToast } from "@/components/ui/use-toast"; import { useToast } from "@/components/ui/use-toast"
import { useAppStore } from "@/store"; import { useAppStore } from "@/store"
import { ChangeEvent, useState } from "react"; import { ChangeEvent, useState } from "react"
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom"
enum PageState { enum PageState {
noData, noData, showForm, sending, created, error
showForm,
sending,
created,
error,
} }
function BookPage() { function BookPage() {
const [pageState, setPageState] = useState<PageState>(PageState.showForm); const [pageState, setPageState] = useState<PageState>(PageState.showForm);
const bookingData = useAppStore((state) => state.newBookingData); const bookingData = useAppStore((state) => state.newBookingData)
const setCustomerData = useAppStore((state) => state.setBookingCustomer); const setCustomerData = useAppStore((state) => state.setBookingCustomer);
const { toast } = useToast(); const { toast } = useToast();
const navigate = useNavigate(); const navigate = useNavigate();
@@ -28,7 +25,7 @@ function BookPage() {
if (!bookingData || !bookingData.customerDetails) { if (!bookingData || !bookingData.customerDetails) {
return ( return (
<Typography variant={"h2"}>You must select some rooms...</Typography> <Typography variant={"h2"}>You must select some rooms...</Typography>
); )
} }
function handleOnChange(e: ChangeEvent<HTMLInputElement>) { function handleOnChange(e: ChangeEvent<HTMLInputElement>) {
@@ -61,13 +58,8 @@ function BookPage() {
function handleOnBookingSubmit() { function handleOnBookingSubmit() {
const customerDetails = bookingData?.customerDetails; const customerDetails = bookingData?.customerDetails;
if ( if (!customerDetails ||
!customerDetails || customerDetails.name == "" || customerDetails.surname == "" || customerDetails.phoneNumber == "" || customerDetails.email == "") {
customerDetails.name == "" ||
customerDetails.surname == "" ||
customerDetails.phoneNumber == "" ||
customerDetails.email == ""
) {
toast({ toast({
variant: "destructive", variant: "destructive",
title: "Uh oh! You must fill all fields.", title: "Uh oh! You must fill all fields.",
@@ -86,9 +78,10 @@ function BookPage() {
if (rs.isError) { if (rs.isError) {
setPageState(PageState.error); setPageState(PageState.error);
} else { } else {
navigate("/success", { state: rs.bookingResponse }); navigate("/success", { state: rs.bookingResponse })
} }
}; }
return ( return (
<> <>
@@ -99,63 +92,34 @@ function BookPage() {
<div> <div>
<div> <div>
<Label htmlFor="name">Name</Label> <Label htmlFor="name">Name</Label>
<Input <Input type="text" name="name" id="name" placeholder="Name" value={bookingData.customerDetails.name ?? ""}
type="text" onChange={handleOnChange} />
name="name"
id="name"
placeholder="Name"
value={bookingData.customerDetails.name ?? ""}
onChange={handleOnChange}
/>
</div> </div>
<div> <div>
<Label htmlFor="surname">Surname</Label> <Label htmlFor="surname">Surname</Label>
<Input <Input type="text" name="surname" id="surname" placeholder="Surname" value={bookingData.customerDetails.surname ?? ""}
type="text" onChange={handleOnChange} />
name="surname"
id="surname"
placeholder="Surname"
value={bookingData.customerDetails.surname ?? ""}
onChange={handleOnChange}
/>
</div> </div>
<div> <div>
<Label htmlFor="email">Email</Label> <Label htmlFor="email">Email</Label>
<Input <Input type="email" name="email" id="email" placeholder="Email" value={bookingData.customerDetails.email ?? ""}
type="email" onChange={handleOnChange} />
name="email"
id="email"
placeholder="Email"
value={bookingData.customerDetails.email ?? ""}
onChange={handleOnChange}
/>
</div> </div>
<div> <div>
<Label htmlFor="phone">Phone Number</Label> <Label htmlFor="phone">Phone Number</Label>
<Input <Input type="tel" name="phoneNumber" id="phone" placeholder="Number" value={bookingData.customerDetails.phoneNumber ?? ""}
type="tel" onChange={handleOnChange} />
name="phoneNumber"
id="phone"
placeholder="Number"
value={bookingData.customerDetails.phoneNumber ?? ""}
onChange={handleOnChange}
/>
</div> </div>
</div> </div>
</div> </div>
<Separator className="my-10" /> <Separator className="my-10" />
<BookingDetails mode="View"></BookingDetails> <BookingDetails mode="View"></BookingDetails>
<Separator className="my-10" /> <Separator className="my-10" />
<Button <Button onClick={handleOnBookingSubmit} disabled={pageState == PageState.sending}>
onClick={handleOnBookingSubmit} <Typography variant={"h3"} className="text-primary-foreground">Book it now!</Typography>
disabled={pageState == PageState.sending}
>
<Typography variant={"h3"} className="text-primary-foreground">
Book it now!
</Typography>
</Button> </Button>
</> </>
); )
} }
export default BookPage; export default BookPage
-3
View File
@@ -1,3 +0,0 @@
.homePageRoomGrid {
grid-template-columns: repeat(auto-fit, minmax(300px, 3fr));
}
+24 -25
View File
@@ -1,49 +1,48 @@
import { useAPIRoomCategories } from "@/api/api-roomCategories"; import { useAPIRoomCategories } from "@/api/api-roomCategories"
import { RoomItemCard } from "@/components/Rooms/room-item-card"; import { RoomItemCard } from "@/components/Rooms/room-item-card"
import { SearchFilterCard } from "@/components/Search/SearchFilterCard"; import { SearchFilterCard } from "@/components/Search/SearchFilterCard"
import BackendConnectionStatus from "@/components/backend-conection-status"; import BackendConnectionStatus from "@/components/backend-conection-status"
import { Separator } from "@/components/ui/separator"; import { Separator } from "@/components/ui/separator"
import { Skeleton } from "@/components/ui/skeleton"; import { Skeleton } from "@/components/ui/skeleton"
import { Typography } from "@/components/ui/typography"; import { Typography } from "@/components/ui/typography"
import { RoomCategory } from "@/model/RoomCategory"; import { RoomCategory } from "@/model/RoomCategory"
import { SearchFilter } from "@/model/SearchFilter"; import { SearchFilter } from "@/model/SearchFilter"
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom"
import { LoaderIcon } from "lucide-react";
import "./home-page.css";
function Homepage() { function Homepage() {
const { roomCategoryList, isLoading, isError } = useAPIRoomCategories(); const { roomCategoryList, isLoading, isError } = useAPIRoomCategories();
const navigate = useNavigate(); const navigate = useNavigate();
const onBtSearchClick = (filter: SearchFilter) => { const onBtSearchClick = (filter: SearchFilter) => {
navigate("/search", { state: filter }); navigate("/search", {state: filter})
}; }
const roomList = roomCategoryList?.map((element: RoomCategory) => { const roomList = roomCategoryList?.map((element: RoomCategory) => {
return <RoomItemCard key={element.id} room={element} />; return (
<RoomItemCard key={element.id} room={element} />
);
}); });
return ( return (
<> <>
<Typography variant={"h1"}>Somnia Rooms</Typography> <Typography variant={"h1"}>Somnia Rooms</Typography>
<Separator className="my-10" /> <Separator className="my-10" />
<SearchFilterCard onSearchClick={onBtSearchClick} /> <SearchFilterCard onSearchClick={onBtSearchClick}/>
<Separator className="my-10" /> <Separator className="my-10" />
<div className="homePageRoomGrid grid gap-4">{roomList}</div> <div className="grid grid-cols-2 gap-4">
{roomList}
</div>
{isLoading && ( {isLoading && (
<> <>
<Skeleton className="mx-auto flex h-[200px] w-full flex-col items-center justify-center"> <Typography variant={"h3"} as="h2">Loading...</Typography>
<LoaderIcon /> <Skeleton className="w-[400px] h-[200px] mx-auto" />
<Typography variant={"h3"} as="h2">
Loading...
</Typography>
</Skeleton>
</> </>
)} )}
<Separator className="my-10" /> <Separator className="my-10" />
<BackendConnectionStatus isLoading={isLoading} isError={isError} /> <BackendConnectionStatus isLoading={isLoading} isError={isError} />
</> </>
); )
} }
export default Homepage; export default Homepage
+55 -87
View File
@@ -1,127 +1,95 @@
import { useAPIRoomAvailability } from "@/api/api-roomSearch"; import { useAPIRoomAvailability } from "@/api/api-roomSearch"
import RoomBooking from "@/components/Rooms/room-booking"; import RoomBooking from "@/components/Rooms/room-booking"
import { SearchFilterCard } from "@/components/Search/SearchFilterCard"; import { SearchFilterCard } from "@/components/Search/SearchFilterCard"
import BackendConnectionStatus from "@/components/backend-conection-status"; import BackendConnectionStatus from "@/components/backend-conection-status"
import { BookingDetails } from "@/components/booking/booking-details"; import { BookingDetails } from "@/components/booking/booking-details"
import { Separator } from "@/components/ui/separator"; import { Separator } from "@/components/ui/separator"
import { Skeleton } from "@/components/ui/skeleton"; import { Skeleton } from "@/components/ui/skeleton"
import { Typography } from "@/components/ui/typography"; import { Typography } from "@/components/ui/typography"
import { AvailabilityFilter } from "@/model/RoomSearch"; import { AvailabilityFilter } from "@/model/RoomSearch"
import { SearchFilter } from "@/model/SearchFilter"; import { SearchFilter } from "@/model/SearchFilter"
import { useAppStore } from "@/store"; import { useAppStore } from "@/store"
import { useMemo, useState } from "react"; import { useMemo, useState } from "react"
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom"
//TODOME: Igual podemos crear un StateMachine conjunta para los siguiente estados de la página: Sin Buscar, Sin disponibilidad, error, cargando. //TODOME: Igual podemos crear un StateMachine conjunta para los siguiente estados de la página: Sin Buscar, Sin disponibilidad, error, cargando.
function SearchPage() { function SearchPage() {
//const [availabilityFilter, setAvailabilityFilter] = useState<AvailabilityFilter>(); //const [availabilityFilter, setAvailabilityFilter] = useState<AvailabilityFilter>();
const searchFilter = useAppStore((state) => state.searchFilter); const searchFilter = useAppStore((state) => (state.searchFilter));
const resetBooking = useAppStore((state) => state.resetBookingState); const resetBooking = useAppStore((state) => (state.resetBookingState));
const navigate = useNavigate(); const navigate = useNavigate();
const [isSearched, setIsSearched] = useState<boolean>(false); const [isSearched, setIsSearched] = useState<boolean>(false);
//This seems a little bit overkill, but IDK.
const availabilityFilter: AvailabilityFilter | null = useMemo(() => {
if (
searchFilter &&
searchFilter.dateRange &&
searchFilter.dateRange.from &&
searchFilter.dateRange.to
) {
const newAvailabilityFilter: AvailabilityFilter = {
startDate: searchFilter.dateRange.from.toDateString(),
endDate: searchFilter.dateRange.to.toDateString(),
};
return newAvailabilityFilter;
}
return null;
}, [searchFilter]);
const {
roomAvailabilityList,
isLoading: isLoadingAvailability,
isError: isErrorAvailability,
} = useAPIRoomAvailability(availabilityFilter ?? null);
const isLoading = isLoadingAvailability;
const isError = isErrorAvailability;
const onBtSearchClick = (newFilter: SearchFilter) => { const onBtSearchClick = (newFilter: SearchFilter) => {
console.log("onBtSearchClick: "); console.log("onBtSearchClick: ");
console.log(newFilter); console.log(newFilter);
if ( if (newFilter.dateRange && newFilter.dateRange.from && newFilter.dateRange.to) {
newFilter.dateRange &&
newFilter.dateRange.from &&
newFilter.dateRange.to
) {
setIsSearched(true); setIsSearched(true);
resetBooking(newFilter.dateRange.from, newFilter.dateRange.to); resetBooking(newFilter.dateRange.from, newFilter.dateRange.to);
} }
}; }
const onBookingContinue = () => { const onBookingContinue = () => {
navigate("/book"); navigate("/book");
}; }
//This seems a little bit overkill, but IDK.
const availabilityFilter: AvailabilityFilter | null = useMemo(
() => {
if (searchFilter && searchFilter.dateRange && searchFilter.dateRange.from && searchFilter.dateRange.to) {
const newAvailabilityFilter: AvailabilityFilter = {
startDate: searchFilter.dateRange.from.toDateString(),
endDate: searchFilter.dateRange.to.toDateString()
};
return newAvailabilityFilter;
}
return null;
},
[searchFilter]
);
const { roomAvailabilityList, isLoading: isLoadingAvailability, isError: isErrorAvailability } = useAPIRoomAvailability(availabilityFilter ?? null);
const isLoading = isLoadingAvailability;
const isError = isErrorAvailability;
const roomList = roomAvailabilityList?.map((element) => { const roomList = roomAvailabilityList?.map((element) => {
return ( return (
<RoomBooking <RoomBooking key={element.roomCategory} availableAmount={element.availability} roomCategoryId={element.roomCategory} />
key={element.roomCategory}
availableAmount={element.availability}
roomCategoryId={element.roomCategory}
/>
); );
}); });
const noRoomsAvailable = ( const noRoomsAvailable = (
<> <>
<Typography variant={"h3"} as="h3"> <Typography variant={"h3"} as="h3">Sorry 😔, there aren't rooms available for selected period.
Sorry 😔, there aren't rooms available for selected period. You can You can contact us for more info.</Typography>
contact us for more info.
</Typography>
</> </>
); );
const hasRooms = const hasRooms = (roomAvailabilityList?.length && roomAvailabilityList?.length > 0);
roomAvailabilityList?.length && roomAvailabilityList?.length > 0;
console.log(hasRooms); console.log(hasRooms);
const pageContent = isLoading ? (
<>
<Typography variant={"h3"} as="h2">
Loading...
</Typography>
<Skeleton className="mx-auto h-[200px] w-full" />
</>
) : (
<div className="2xl:grid 2xl:grid-cols-60/40 2xl:gap-6">
<div className="flex flex-col gap-5">
{hasRooms ? roomList : isSearched && noRoomsAvailable}
</div>
<Separator className="my-10 2xl:hidden" />
<BookingDetails
onBookingConfirm={onBookingContinue}
mode={"Book"}
></BookingDetails>
</div>
);
return ( return (
<div className="bg-background text-foreground"> <div className="bg-background text-foreground">
<SearchFilterCard onSearchClick={onBtSearchClick} /> <SearchFilterCard onSearchClick={onBtSearchClick} />
<Separator className="my-10" /> <Separator className="my-10" />
{hasRooms ? ( {isLoading && (
pageContent <>
) : ( <Typography variant={"h3"} as="h2">Loading...</Typography>
<Typography> <Skeleton className="w-[400px] h-[200px] mx-auto" />
Realiza una búsqueda para ver la disponibilidad y los precios. </>
</Typography>
)} )}
<div className="flex flex-col gap-5">
{hasRooms ? roomList : (isSearched && noRoomsAvailable)}
</div>
<Separator className="my-10" />
<BookingDetails onBookingConfirm={onBookingContinue} mode={"Book"}></BookingDetails>
<Separator className="my-10" /> <Separator className="my-10" />
<BackendConnectionStatus isLoading={isLoading} isError={isError} /> <BackendConnectionStatus isLoading={isLoading} isError={isError} />
</div> </div>
); )
} }
export default SearchPage; export default SearchPage
+35 -36
View File
@@ -1,48 +1,47 @@
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader } from "@/components/ui/card"; import { Card, CardContent, CardHeader } from "@/components/ui/card"
import { Typography } from "@/components/ui/typography"; import { Typography } from "@/components/ui/typography"
import { NewBookingResponse } from "@/model/Bookings"; import { NewBookingResponse } from "@/model/Bookings"
import { useAppStore } from "@/store"; import { useAppStore } from "@/store"
import { addDays } from "date-fns"; import { addDays } from "date-fns"
import { useEffect, useState } from "react"; import { useEffect, useState } from "react"
import { useLocation, useNavigate } from "react-router-dom"; import { useLocation, useNavigate } from "react-router-dom"
function SuccessPage() { function SuccessPage() {
const [pageState, setPageState] = useState<NewBookingResponse | null>(null);
const resetBookingState = useAppStore((state) => state.resetBookingState);
const location = useLocation(); const [pageState, setPageState] = useState<NewBookingResponse|null>(null)
const navigate = useNavigate(); const resetBookingState = useAppStore((state) => state.resetBookingState);
useEffect(() => { const location = useLocation();
if (location.state == null) { const navigate = useNavigate();
navigate("/home");
useEffect(() => {
if(location.state == null) {
navigate("/home");
}
setPageState(location.state);
}, [location, navigate])
const handleBtBackClick = () => {
resetBookingState(new Date(), addDays(new Date(), 2));
navigate("/home");
} }
setPageState(location.state);
}, [location, navigate]);
const handleBtBackClick = () => {
resetBookingState(new Date(), addDays(new Date(), 2));
navigate("/home");
};
return ( return (
<Card> <Card>
<CardHeader> <CardHeader>
<Typography variant={"h2"}>Booking Completed</Typography> <Typography variant={"h2"}>Booking Completed</Typography>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<Typography variant={"largeText"}> <Typography variant={"largeText"}>Booking ref: {pageState?.refNumber}</Typography>
Booking ref: {pageState?.refNumber} <Button className="my-4" onClick={handleBtBackClick}>
</Typography> <Typography variant={"largeText"} className="text-primary-foreground">Go Back</Typography>
<Button className="my-4" onClick={handleBtBackClick}> </Button>
<Typography variant={"largeText"} className="text-primary-foreground"> </CardContent>
Go Back
</Typography>
</Button>
</CardContent>
</Card> </Card>
); )
} }
export default SuccessPage; export default SuccessPage
+79 -94
View File
@@ -1,110 +1,95 @@
import { create } from "zustand"; import { create } from 'zustand'
import { SearchFilter } from "./model/SearchFilter"; import { SearchFilter } from './model/SearchFilter'
import { import { NewBooking, NewBookingCustomerDetails, NewBookingRoom } from './model/Bookings'
NewBooking,
NewBookingCustomerDetails,
NewBookingRoom,
} from "./model/Bookings";
interface AppState { interface AppState {
searchFilter: SearchFilter; searchFilter: SearchFilter
setSearchFilter: (newFilter: SearchFilter) => void; setSearchFilter: (newFilter: SearchFilter) => void
newBookingData: NewBooking | null; newBookingData: NewBooking | null
setNewBooking: (newBooking: NewBooking) => void; setNewBooking: (newBooking: NewBooking) => void
resetBookingState: (arrival: Date, departure: Date) => void; resetBookingState: (arrival: Date, departure: Date) => void
addNewBookingRoom: (newRoom: NewBookingRoom) => void; addNewBookingRoom: (newRoom: NewBookingRoom) => void
setBookingCustomer: (newCustomer: NewBookingCustomerDetails) => void; setBookingCustomer: (newCustomer: NewBookingCustomerDetails) => void
} }
const defaultSearchFilter: SearchFilter = { const defaultSearchFilter: SearchFilter = {
dateRange: { from: new Date() }, dateRange: { from: new Date() }
}; }
const defaultNewBooking: NewBooking = { const defaultNewBooking: NewBooking = {
arrivalDate: new Date(), arrivalDate: new Date(),
departureDate: new Date(), departureDate: new Date(),
customerDetails: { customerDetails: {
name: null, name: null,
surname: null, surname: null,
email: null, email: null,
phoneNumber: null, phoneNumber: null
}, },
rooms: [], rooms: []
}; }
function getDefaultBookingData(arrivalDate: Date, departureDate: Date) { function getDefaultBookingData(arrivalDate: Date, departureDate: Date) {
return { return {
...defaultNewBooking, ...defaultNewBooking,
arrivalDate: arrivalDate, arrivalDate: arrivalDate,
departureDate: departureDate, departureDate: departureDate
};
}
function addNewBookingRoomToCurrentState(
newRoom: NewBookingRoom,
currentState: NewBooking | null,
): NewBooking | null {
if (currentState == null) {
return currentState;
}
//Remove rooms with "same key".
const filteredRooms = currentState.rooms.filter((room) => {
const diffRoom = room.roomCategory != newRoom.roomCategory;
const diffAmount = room.guestNumber != newRoom.guestNumber;
if (diffRoom || (!diffRoom && diffAmount)) {
return true;
} }
return false;
});
console.log(filteredRooms);
if (newRoom.amount > 0) {
filteredRooms.push(newRoom);
}
const newState: NewBooking = {
...currentState,
rooms: filteredRooms ?? [],
};
console.log("AddRoomNewState:");
console.log(newState);
return newState;
} }
function setBookingCustomer( function addNewBookingRoomToCurrentState(newRoom: NewBookingRoom, currentState: NewBooking | null): NewBooking | null {
newCustomer: NewBookingCustomerDetails,
currentState: NewBooking | null,
) {
if (currentState == null) {
return currentState;
}
const newState: NewBooking = { if (currentState == null) {
...currentState, return currentState;
customerDetails: newCustomer, }
};
return newState; //Remove rooms with "same key".
const filteredRooms = currentState.rooms.filter((room) => {
const diffRoom = room.roomCategory != newRoom.roomCategory;
const diffAmount = room.guestNumber != newRoom.guestNumber;
if(diffRoom || (!diffRoom && diffAmount)) {
return true;
}
return false;
})
console.log(filteredRooms);
if (newRoom.amount > 0) {
filteredRooms.push(newRoom);
}
const newState: NewBooking = {
...currentState,
rooms: filteredRooms ?? []
}
console.log("AddRoomNewState:");
console.log(newState);
return newState;
}
function setBookingCustomer(newCustomer: NewBookingCustomerDetails, currentState: NewBooking | null) {
if(currentState == null) {
return currentState;
}
const newState: NewBooking = {
...currentState,
customerDetails: newCustomer
};
return newState;
} }
export const useAppStore = create<AppState>()((set) => ({ export const useAppStore = create<AppState>()((set) => ({
searchFilter: defaultSearchFilter, searchFilter: defaultSearchFilter,
setSearchFilter: (newFilter) => set(() => ({ searchFilter: newFilter })), setSearchFilter: (newFilter) => set(() => ({ searchFilter: newFilter })),
newBookingData: null, newBookingData: null,
setNewBooking: (newBooking) => set(() => ({ newBookingData: newBooking })), setNewBooking: (newBooking) => set(() => ({ newBookingData: newBooking })),
resetBookingState: (arrival, departure) => resetBookingState: (arrival, departure) =>
set(() => ({ newBookingData: getDefaultBookingData(arrival, departure) })), set(() => ({ newBookingData: getDefaultBookingData(arrival, departure) })),
addNewBookingRoom: (newRoom: NewBookingRoom) => addNewBookingRoom: (newRoom: NewBookingRoom) =>
set((state) => ({ set((state) => ({ newBookingData: addNewBookingRoomToCurrentState(newRoom, state.newBookingData) })),
newBookingData: addNewBookingRoomToCurrentState( setBookingCustomer: (newCustomer: NewBookingCustomerDetails) =>
newRoom, set((state) => ({newBookingData: setBookingCustomer(newCustomer, state.newBookingData)}))
state.newBookingData, }))
),
})),
setBookingCustomer: (newCustomer: NewBookingCustomerDetails) =>
set((state) => ({
newBookingData: setBookingCustomer(newCustomer, state.newBookingData),
})),
}));
+6 -12
View File
@@ -1,13 +1,13 @@
import plugin from "tailwindcss-animate"; import plugin from 'tailwindcss-animate';
/** @type {import('tailwindcss').Config} */ /** @type {import('tailwindcss').Config} */
export default { export default {
darkMode: ["class"], darkMode: ["class"],
content: [ content: [
"./pages/**/*.{ts,tsx}", './pages/**/*.{ts,tsx}',
"./components/**/*.{ts,tsx}", './components/**/*.{ts,tsx}',
"./app/**/*.{ts,tsx}", './app/**/*.{ts,tsx}',
"./src/**/*.{ts,tsx}", './src/**/*.{ts,tsx}',
], ],
prefix: "", prefix: "",
theme: { theme: {
@@ -73,13 +73,7 @@ export default {
"accordion-down": "accordion-down 0.2s ease-out", "accordion-down": "accordion-down 0.2s ease-out",
"accordion-up": "accordion-up 0.2s ease-out", "accordion-up": "accordion-up 0.2s ease-out",
}, },
//SomniaRooms Extends
gridTemplateColumns: {
"60/40": "60% 40%",
"40/60": "40% 60%",
},
}, },
}, },
plugins: [plugin], plugins: [plugin],
}; }
+3 -1
View File
@@ -2,7 +2,9 @@
"compilerOptions": { "compilerOptions": {
"baseUrl": ".", "baseUrl": ".",
"paths": { "paths": {
"@/*": ["./src/*"] "@/*": [
"./src/*"
]
}, },
"target": "ES2020", "target": "ES2020",
"useDefineForClassFields": true, "useDefineForClassFields": true,
+4 -4
View File
@@ -1,6 +1,6 @@
import { defineConfig } from "vite"; import { defineConfig } from 'vite'
import react from "@vitejs/plugin-react-swc"; import react from '@vitejs/plugin-react-swc'
import path from "path"; import path from "path"
// https://vitejs.dev/config/ // https://vitejs.dev/config/
export default defineConfig({ export default defineConfig({
@@ -14,4 +14,4 @@ export default defineConfig({
"@": path.resolve(__dirname, "./src"), "@": path.resolve(__dirname, "./src"),
}, },
}, },
}); })