Compare commits

..
204 Commits
Author SHA1 Message Date
changwng e88cf0c6d0 Initial commit 2025-03-26 09:59:55 +09:00
changwng 882ed8d9eb 최초 커밋 2025-03-22 13:01:39 +09:00
chanii8 deeb670150 Merge pull request 'iipbs_cs' (#11) from iipbs_cs into main
Reviewed-on: #11
2025-03-21 11:32:11 +09:00
chanii8 b1f3de08a7 refactor: query provider 구조 변경 2025-03-21 11:31:33 +09:00
chanii8 699eadb399 feat: 사이트 테마 SSR 적용 2025-03-21 09:56:25 +09:00
chanii8 580d449f3e chore: 사이트 등록 페이지 폼 기본값 수정 2025-03-20 18:59:06 +09:00
chanii8 b8e0a8a878 feat: 다크 모드 적용 2025-03-20 18:50:31 +09:00
chanii8 55ac57d73c chore: 사이트 폼 컨펌 다이얼로그 로직 수정 2025-03-20 17:38:13 +09:00
chanii8 fadb57242d feat: 도메인 관리 및 IP 관리 작업 2025-03-20 17:36:16 +09:00
chanii8 dc01c897a9 chore: 사이트 수정 폼 수정 2025-03-20 10:48:54 +09:00
chanii8 b2141d9708 refactor: ip 관리 폼 수정 2025-03-20 10:43:19 +09:00
chanii8 e49e3d3b36 feat: useAlertStore 적용 2025-03-19 18:43:58 +09:00
chanii8 915543628d feat: ip 관리 서비스 작업 2025-03-19 16:23:33 +09:00
chanii8 6f0e1a6e40 feat: 컨펌 & 얼럿 다이얼로그 스토어 생성 2025-03-19 15:54:20 +09:00
chanii8 4e0e05ea78 Merge pull request 'iipbs_cs' (#10) from iipbs_cs into main
Reviewed-on: #10
2025-03-19 13:00:01 +09:00
chanii8 25a2ac5716 refactor: 인증 및 로그인 로직 수정 2025-03-19 09:38:49 +09:00
yschoi c31a6ea8bf 테스트 2025-03-19 09:24:36 +09:00
chanii8 a13ea5d6e9 design: 사이트 관리 페이지 스타일 수정 2025-03-18 17:42:12 +09:00
chanii8 8f484e8425 feat: sidebar 작업 2025-03-18 14:29:40 +09:00
chanii8 e7f2b3e3ee Update README.md 2025-03-17 19:14:32 +09:00
chanii8 4933fc164a Merge pull request 'iipbs_cs' (#9) from iipbs_cs into main
Reviewed-on: #9
2025-03-17 18:51:47 +09:00
chanii8 8aa713e285 chore: Remove .next directory from git tracking 2025-03-17 18:47:53 +09:00
chanii8 daacb2cb25 Merge branch 'main' of https://www.onasys.co.kr:3000/ONAANDALL/frontend into iipbs_cs 2025-03-17 18:42:35 +09:00
chanii8 d88afe7034 build: packages & cs 폴더 빌드 성공 2025-03-17 18:39:13 +09:00
chanii8 4a88315a99 chore: gitignore 수정 2025-03-17 18:28:17 +09:00
chanii8 f767d0a688 feat: sidebar 컴포넌트 생성 2025-03-17 18:28:17 +09:00
chanii8 57e9daf772 feat: user store 생성(zustand) 2025-03-17 18:28:17 +09:00
chanii8 4ed2a45486 refactor: provider 레이어 변경 & 누락된 public api 수정 2025-03-17 18:28:17 +09:00
chanii8 08e9cb98e9 Merge pull request 'iipbs_cs' (#8) from iipbs_cs into main
Reviewed-on: #8
2025-03-17 18:10:31 +09:00
truthwing 0b9b5bd22c Merge commit 'e5265a10d0b9d2f7df9aa53e1d482deb821ba4e7' into iipbs/wr/main_merge 2025-03-17 17:54:40 +09:00
truthwing e5265a10d0 Merge commit '50ffc2d763ae5797dd41c068777c5546f1d971ce' into iipbs/common/main 2025-03-17 17:54:29 +09:00
YangJinSoo94 4e869b2c70 TABLE에서 아이템 선택 이벤트 추가가 2025-03-17 17:45:57 +09:00
chanii8 d404de4afb chore: gitignore 수정 2025-03-17 17:37:47 +09:00
truthwing c7039294c9 Merge commit 'e16ff92e72f6346ee36d0f1b7dd9d6039fa1a2d2' into iipbs/wr/main_merge 2025-03-17 17:19:24 +09:00
chanii8 574286139c feat: sidebar 컴포넌트 생성 2025-03-17 15:24:58 +09:00
chanii8 c81735b8b8 feat: user store 생성(zustand) 2025-03-17 14:50:18 +09:00
leedj312 e2c80a9530 form.md 생성 및 작성 2025-03-17 14:01:39 +09:00
chanii8 39bf03c4f5 refactor: provider 레이어 변경 & 누락된 public api 수정 2025-03-17 13:27:19 +09:00
truthwing e16ff92e72 Merge commit 'cd03d6f42ebb9e3e9ceda9d9681d298cea9ca8ff' into iipbs/common/main 2025-03-17 11:20:28 +09:00
chanii8 cd03d6f42e Merge pull request 'iipbs_cs' (#7) from iipbs_cs into main
Reviewed-on: #7
2025-03-17 11:13:10 +09:00
YangJinSoo94 4a8383da73 라인차트 라인데이터가 여러개일 경우에 여러개의 라인그래프가 그려지도록 수정 2025-03-17 11:11:30 +09:00
chanii8 babf7055b4 chore: env 파일 git에 포함 2025-03-17 11:11:21 +09:00
chanii8 05f3e48ed6 feat: view only layout 생성 2025-03-17 11:11:21 +09:00
chanii8 6e3b9aaa37 refactor: rewrites 로직 미들웨어로 이동 2025-03-17 11:11:21 +09:00
chanii8 594dbd9fc7 feat: base layout 그룹 분리 2025-03-17 11:11:21 +09:00
chanii8 daf9a52aec feat: 사이트 삭제 기능 작업 2025-03-17 11:11:21 +09:00
truthwing b8cf245cac Merge commit 'e178fe370cc71bd2a8adead7a0278b78471b08ed' into iipbs/common/main 2025-03-17 10:56:51 +09:00
chanii8 e178fe370c Merge pull request 'iipbs_cs' (#6) from iipbs_cs into main
Reviewed-on: #6
2025-03-14 18:43:19 +09:00
chanii8 ec5acf9291 feat: 사이트 등록/수정 작업 2025-03-14 18:42:32 +09:00
chanii8 5505838bc5 design: 컴포넌트 스타일 수정 2025-03-14 18:13:25 +09:00
chanii8 9277ffbde9 feat: 사이트 수정 작업 2025-03-14 16:57:19 +09:00
chanii8 d4a2b5641d refactor: provider 및 client component 정리 2025-03-14 16:02:49 +09:00
jcchoi 50ffc2d763 Update README.md 2025-03-14 15:57:12 +09:00
jcchoi d5c376ca54 Update README.md
CMS API 서버 및 Swagger  주소 추가
2025-03-14 15:56:57 +09:00
chanii8 6542635391 design: 공통 컴포넌트 스타일 수정 2025-03-14 15:56:56 +09:00
jcchoi 2618fc7fbe Update README.md
network 항목에 대한 참조 추가
2025-03-14 15:54:14 +09:00
truthwing 8bd0bf3346 Merge commit 'd80f64901805f34678e05db046ac25cd66407763' into iipbs/wr/dev 2025-03-14 14:05:50 +09:00
truthwing d80f649018 Merge remote-tracking branch 'origin/main' into iipbs/common/main 2025-03-14 14:05:19 +09:00
chanii8 4c441a9c28 feat: 인증 처리 로직 수정 2025-03-14 11:27:10 +09:00
chanii8 f541687c00 feat: 사이트 등록/수정 페이지 form 작업 2025-03-13 17:42:22 +09:00
chanii8 64a615258d feat: 사이트 등록/수정 페이지 컴포넌트 작업 2025-03-13 13:28:33 +09:00
chanii8 b64ff7c081 design: 공통 컴포넌트 다크 테마 스타일 적용 2025-03-13 13:25:51 +09:00
leedj312 00ba7de206 Merge commit 'ffb15a7e3a64f6b798e58fbcbc6bd10e4b6481bf' into iipbs/wr/dev 2025-03-13 11:32:36 +09:00
leedj312 ffb15a7e3a date picker 수정_ 1. selectClass 2.아이콘 간격 css수정 3.color white고정 2025-03-13 11:32:11 +09:00
leedj312 59f35775b1 공공하수처리시설 css 수정 2025-03-13 11:29:35 +09:00
YangJinSoo94 71e70c842b LineBar 범례 및 ui 수정정 2025-03-13 10:57:27 +09:00
leedj312 f026268aa8 하수재이용 등록 폼수정 2025-03-12 20:07:18 +09:00
leedj312 ca78815ab5 수요신청 폼 ui 완료 2025-03-12 17:40:24 +09:00
chanii8 0588bf0d7f feat: 사이트 상세(수정) 페이지 데이터 바인딩 작업 2025-03-12 16:56:47 +09:00
YangJinSoo94 396992fe1b 도넛차트 레이아웃 수정정 2025-03-12 16:36:25 +09:00
YangJinSoo94 25566be2c6 차트 레이아웃 수정(크기 및 여백) 2025-03-12 14:46:56 +09:00
leedj312 3507bb63c3 toast 패키지 추가 2025-03-12 13:36:17 +09:00
leedj312 6528151aea 수요처 등록 폼 작업중 2025-03-12 13:35:40 +09:00
chanii8 49bcf4037f Merge pull request 'iipbs_cs' (#5) from iipbs_cs into main
Reviewed-on: #5
2025-03-12 13:30:35 +09:00
chanii8 108e2a8746 feat: refresh 로직 수정 2025-03-12 13:29:34 +09:00
YangJinSoo94 42647d6ce3 차트 제목 누락 추가가 2025-03-12 13:07:41 +09:00
YangJinSoo94 afd8925792 차트 chartTitle properties 추가(빈칸이 아니면 차트제목 영역나오도록 추가) 2025-03-12 11:36:49 +09:00
YangJinSoo94 104a7b0079 차트 수정정중, 라인바 차트 개발 2025-03-12 11:02:10 +09:00
chanii8 6e41c09157 rename: 폴더 이동 및 파일명 수정 2025-03-12 10:40:23 +09:00
leedj312 4cb3e10686 Merge commit 'b79629704a4f2bd688fe92dbbfd8843fd93d2c91' into iipbs/wr/dmdForm 2025-03-11 18:03:17 +09:00
leedj312 b79629704a Merge commit 'bc0dee30300e33b7a2ef93871c128bd7ab252571' into iipbs/common/main 2025-03-11 18:02:44 +09:00
leedj312 0d57bde4fd 데이트 피커 설치dependency 추가 2025-03-11 18:00:26 +09:00
leedj312 66fe8b3ef6 수요처등록 폼 데이트 피커 수정 2025-03-11 17:59:36 +09:00
chanii8 53bad41e53 Merge pull request 'Update README.md' (#4) from chanii8-patch-1 into main
Reviewed-on: #4
2025-03-11 17:56:27 +09:00
chanii8 43cbae0a7e Update README.md 2025-03-11 17:56:07 +09:00
chanii8 6fc30dd4c6 Update README.md 2025-03-11 17:55:00 +09:00
chanii8 23ccb53e8c Update README.md 2025-03-11 17:53:14 +09:00
leedj312 b7e204f744 Merge commit '0900c469e2ff81b0d48eb618783e694ff9ee7f9d' into iipbs/wr/dmdForm 2025-03-11 17:45:26 +09:00
leedj312 4126a6c3a8 수요처 등록 기본구조 작업중 2025-03-11 17:40:04 +09:00
chanii8 0042f0b8c9 feat: 사이트 목록 api 조회 작업 2025-03-11 17:34:11 +09:00
truthwing 0900c469e2 Merge branch 'iipbs/wr/dmdForm' into iipbs/wr/dev 2025-03-11 17:28:51 +09:00
truthwing 6f3115f523 Merge branch 'iipbs/wr/form' into iipbs/wr/dev 2025-03-11 17:27:52 +09:00
leedj312 e2ae39c73c formStore 작업완료 2025-03-11 17:21:23 +09:00
leedj312 7807da99c6 dmdForm작업중 2025-03-11 16:58:12 +09:00
chanii8 c13ce271ff Merge pull request 'feat: client request 인증 로직 추가' (#3) from iipbs_cs into main
Reviewed-on: #3
2025-03-11 16:34:29 +09:00
chanii8 2f8f1b5ddc feat: client request 인증 로직 추가 2025-03-11 16:33:31 +09:00
chanii8 cddb5e0187 Merge pull request 'iipbs_cs' (#2) from iipbs_cs into main
Reviewed-on: #2
2025-03-11 16:21:48 +09:00
chanii8 89eaefeb84 feat: vite 환경 변수 타입 적용 2025-03-11 15:49:14 +09:00
chanii8 7262a03ec7 feat: common 폴더 최신화 2025-03-11 15:48:32 +09:00
chanii8 58a0c5f1de chore: cs 프로젝트 최신화 2025-03-11 15:36:23 +09:00
YangJinSoo94 bc0dee3030 Merge branch 'iipbs/common/main' of https://www.onasys.co.kr:3000/ONAANDALL/frontend into iipbs/common/main 2025-03-11 14:44:53 +09:00
YangJinSoo94 5c81e35bc4 input initvalue 추가, console.log제거 2025-03-11 14:44:35 +09:00
truthwing a338afb36c Merge branch 'iipbs/common/main' into iipbs/wr/form 2025-03-11 14:36:14 +09:00
truthwing d145eee662 form import 오류로 수정. 2025-03-11 14:02:46 +09:00
truthwing 2d341c1314 Merge commit '5785e57b40d4f4f7e467e934f19b0a874b6f1915' into iipbs/wr/form 2025-03-11 14:01:22 +09:00
truthwing 5785e57b40 데이트 피커 추가
디자인 관련 원앤올에 문의 해야함
2025-03-11 14:00:58 +09:00
truthwing 8104ba825f datepicker 동작되는 구조로 수정. 2025-03-11 13:55:55 +09:00
YangJinSoo94 8dfa052ea6 search 영역 label 크기 lg > 2xl 2025-03-11 13:55:14 +09:00
leedj312 1b41ec5873 Merge commit '0ad1fdd2532e65d6e1bfcf727af388e5a2c1aa7d' into iipbs/wr/dev 2025-03-11 13:54:12 +09:00
leedj312 2f4745a65a 빗물재이용 폼 수정 2025-03-11 13:52:34 +09:00
leedj312 1158b77ecb 빗물재이용 폼수정중 2025-03-11 13:52:08 +09:00
YangJinSoo94 e0ef37e9d7 label class 변경경 2025-03-11 13:27:05 +09:00
truthwing 0ad1fdd253 재이용 시설 폼 작성. 2025-03-11 13:21:16 +09:00
leedj312 718187a25d Merge commit '19d765266fc571f25e7f66c20ff77a2999354f35' into iipbs/wr/dev 2025-03-11 11:24:34 +09:00
truthwing a2b0e9dfb3 Merge commit '19d765266fc571f25e7f66c20ff77a2999354f35' into iipbs/wr/form 2025-03-11 11:20:37 +09:00
truthwing 19d765266f form_ui 추가. 2025-03-11 11:20:09 +09:00
leedj312 ad7c01eb4d Merge remote-tracking branch 'origin/iipbs/wr/dev' into iipbs/wr/dev 2025-03-10 22:25:42 +09:00
leedj312 2756b075d0 form 수정 2025-03-10 22:17:16 +09:00
truthwing 56ae9ec3c7 Merge commit '971c4a56151a43cb7599da3dd1301792076a731a' into iipbs/wr/dev 2025-03-10 18:33:11 +09:00
truthwing 971c4a5615 Merge commit 'e4d5e21b2944169449844be2842ca3f606d8dc35' into iipbs/wr/searchStore 2025-03-10 18:25:21 +09:00
truthwing e4d5e21b29 입포트 구조 수정
서치폼 기본 크기 적용
글자크기 2xl로 수정.
2025-03-10 18:25:06 +09:00
truthwing 842461eb53 물재이용 서치바 수정중. 2025-03-10 18:21:26 +09:00
leedj312 818fec3f75 Merge branch 'iipbs/common/main' into iipbs/wr/dev 2025-03-10 18:01:16 +09:00
leedj312 fa0d220aab tabledata로 변수 명 변경, 페이지 네이션 unvisible 추가 2025-03-10 18:01:01 +09:00
leedj312 622b8bcf94 테이블 데이터 변수명 및 스토어명, 필요없는 코드 삭제 2025-03-10 17:59:07 +09:00
truthwing 68ed0f6436 스토어 물재이용 타입이랑 초기값 추가. 2025-03-10 16:58:04 +09:00
truthwing 4775da6725 store 정리
search
2025-03-10 16:55:54 +09:00
leedj312 411a47a0b8 페이지 삭제 2025-03-10 16:11:57 +09:00
leedj312 16b296e2fb 스크롤 오류 수정 2025-03-10 15:27:22 +09:00
leedj312 6d4004fd86 Merge remote-tracking branch 'origin/iipbs/common/main' into iipbs/wr/dev 2025-03-10 15:16:07 +09:00
leedj312 d04a79d1cc 스크롤바 작업 중 / business 컴포넌트 적용전 2025-03-10 15:15:56 +09:00
leedj312 1d8426224e scroll 추가 2025-03-10 15:12:33 +09:00
truthwing fcf45107b1 onSelectValue 함수 부분 추가. 2025-03-10 13:50:38 +09:00
truthwing 021a282655 search bar에 값 입력하는 형태로 component 구현. 2025-03-10 13:26:39 +09:00
leedj312 03abe7ae90 Merge commit '87031def3c7d77e5867290ceffd1b228edcdba31' into iipbs/wr/dev 2025-03-10 09:30:12 +09:00
chanii8 e7bff1579e chore: 환경 변수 설정 작업 2025-03-07 23:36:43 +09:00
chanii8 d209213f02 chore: tree 디자인 수정 2025-03-07 18:54:39 +09:00
chanii8 811c6e62db feat: tree 공통 컴포넌트 생성 2025-03-07 18:37:25 +09:00
truthwing 87031def3c searchbar 구조 수정. 2025-03-07 18:11:26 +09:00
chanii8 c0abd6d53f chore: type 패키지 설치 2025-03-07 16:18:55 +09:00
leedj312 d9c77bcc5b 폴더구조(url구조) 변경, 물재이용 공통 컴포넌트 이동, 빗물이용시설 등록 페이지 추가 2025-03-07 14:16:19 +09:00
leedj312 24d7ed06fe Merge commit '7c03f04078e289e9c252ce7edd4df8ea3892800c' into iipbs/wr/dev 2025-03-07 13:28:34 +09:00
leedj312 7c03f04078 type 수정 2025-03-07 13:24:09 +09:00
leedj312 efa63f9c6a Merge commit '12f6f42b0e63a70efa19fa6abcd2e6758745669d' into iipbs/common/main 2025-03-07 13:17:18 +09:00
leedj312 37c2901976 테이블 타이틀 노드 추가 및 headlist 인터페이스 수정 2025-03-07 13:03:09 +09:00
leedj312 ff83a6c7dd css변경 2025-03-07 12:58:00 +09:00
leedj312 584484bbd0 각 노드 위치 수정 2025-03-07 11:41:03 +09:00
YangJinSoo94 12f6f42b0e selectbox 크기 조절 컴포넌트 받을수있도록 수정정 2025-03-07 11:24:22 +09:00
leedj312 2a25f9b113 Merge commit '90c36533f400828e254fc165b51f75d1892f36cf' into iipbs/wr/dev 2025-03-07 09:52:24 +09:00
leedj312 ab95b278cd 하수재이용시서 폼 작업중 2025-03-07 09:34:00 +09:00
leedj312 48d55b0578 Merge commit 'e50799c726ae286efc42878cba0cce9ce1f0cf9e' into iipbs/wr/dev 2025-03-06 18:12:34 +09:00
leedj312 ff7bd16a6e input 작업중 2025-03-06 18:03:37 +09:00
truthwing e50799c726 Merge branch 'iipbs/common/main' into iipbs/wr/fileupload 2025-03-06 18:01:30 +09:00
truthwing dae9374b28 FileUpload 타입 오류로 수정. 2025-03-06 18:01:12 +09:00
truthwing 34a133b35c Merge commit '432579de83b9cb3611acee49764739e5badd480c' into iipbs/wr/fileupload 2025-03-06 17:51:41 +09:00
truthwing 432579de83 파일 업로드 conponent 추가 2025-03-06 17:51:26 +09:00
truthwing ff3b2f18b5 file upload 컴퍼넌트 사용하는 예제 소스 작성. 2025-03-06 17:38:05 +09:00
leedj312 c96b2600dd 공공재이용시설 등록 폼 작업중 2025-03-06 14:16:48 +09:00
truthwing 90c36533f4 레이아웃이 전체적으로 추가 되도록 수정. 2025-03-06 11:35:36 +09:00
YangJinSoo94 6fe828d77f placeHolder, label undefined시 조건추가가 2025-03-05 18:17:36 +09:00
leedj312 b4403ab687 package.js 수정 zustand 설치 2025-03-05 17:07:54 +09:00
leedj312 2815110cb9 Merge remote-tracking branch 'origin/iipbs/wr/store' into iipbs/wr/dev 2025-03-05 16:55:10 +09:00
leedj312 a244917de7 공공재사용 시설 등록 작업중 (css) 2025-03-05 16:33:38 +09:00
truthwing 58d5175ee5 store 사용 방법 md 작성. 2025-03-05 16:31:36 +09:00
truthwing 54e6ae3443 타입에 오류가 없게끔 수정 완료. 2025-03-05 15:53:10 +09:00
truthwing 9f71e5527c 페이지에서 타이틀 구조 오류로 수정. 2025-03-05 15:48:05 +09:00
truthwing bf8dbffd15 첫페이지 관련 store 처리 2025-03-05 15:44:17 +09:00
YangJinSoo94 9b44458a12 search_form 및 selectbox 영역 수정정 2025-03-05 14:51:39 +09:00
leedj312 77b779be6a Merge branch 'iipbs/common/main' into iipbs/wr/dev 2025-03-05 13:14:03 +09:00
leedj312 0f1ff0ff68 Merge branch 'iipbs/common/form' into iipbs/common/main 2025-03-05 13:11:07 +09:00
leedj312 4598bbb0ca Merge commit '62d29d51f0ac51aacbd1a009df8f9f4db8395300' into iipbs/common/main 2025-03-05 13:10:47 +09:00
leedj312 3ef2795844 form component 초기 작업 완료 2025-03-05 13:08:33 +09:00
YangJinSoo94 62d29d51f0 selectbox 구성변경 (lib에 원본넣고 index.tsx에 array를 key/value로 구성) 2025-03-05 10:18:30 +09:00
leedj312 d31a2776a4 test 2025-03-05 09:25:45 +09:00
leedj312 c6dea2e397 Merge remote-tracking branch 'origin/iipbs/common/main' into iipbs/wr/dev 2025-03-04 18:05:33 +09:00
leedj312 41c8c11ec0 table colspan 기능 추가 2025-03-04 18:05:17 +09:00
truthwing fa5ef73261 Merge commit '7078f932ef6393c64d7967f1ea2cf5bf5aab04e6' into iipbs/common/main 2025-03-04 18:02:08 +09:00
leedj312 7078f932ef 테이블 헤더 colspan 추가 2025-03-04 17:58:30 +09:00
YangJinSoo94 7aa6f3449d index.ts에 select export 구문추가가 2025-03-04 17:19:48 +09:00
YangJinSoo94 c320a75cdd selectbox lib 설치치 2025-03-04 17:14:46 +09:00
YangJinSoo94 3704927378 childnode 형식으로 변경경 2025-03-04 16:57:59 +09:00
YangJinSoo94 e6f097355c search_form 추가가 2025-03-04 16:51:36 +09:00
truthwing 624d5434db Merge branch 'iipbs/common' into iipbs/wr/dev 2025-03-04 15:49:19 +09:00
truthwing 1ed87ab8fb components 경로가 잘못된 부분으로 수정. 2025-03-04 13:32:17 +09:00
leedj312 c995f6a112 Merge branch 'iipbs_common' into iipbs_common-table 2025-03-04 11:18:13 +09:00
truthwing cea633c7b1 라이브러리 경로 확인후 수정. 2025-03-04 10:59:52 +09:00
truthwing c51f2d977d Merge commit 'b1ae5126f21ed4b43693da4c7948c9182e958d16' into iipbs_wr-dev 2025-02-28 17:56:00 +09:00
truthwing b1ae5126f2 패키지 경로 수정 완료. 2025-02-28 17:52:58 +09:00
leedj312 910eee4100 chart import 변경 2025-02-28 17:16:46 +09:00
leedj312 54ba841d6d Merge branch 'iipbs_common' into iipbs_wr-dev 2025-02-28 17:04:04 +09:00
leedj312 86c29bc790 form 및table 수정사항 반영 2025-02-28 17:03:39 +09:00
leedj312 d51358a59a package wr 실행 추가 2025-02-28 16:59:50 +09:00
leedj312 1ea71aa2ad base layout 및 하수재이용등록 테이블 추가 2025-02-28 16:59:08 +09:00
YangJinSoo94 8be4a7c086 README.md 및 chart.md 생성성 2025-02-28 16:58:50 +09:00
YangJinSoo94 c4e021f8b5 chart.md 파일 업로드드 2025-02-28 16:47:19 +09:00
truthwing 5a3e849e81 Merge commit 'ce1d5f90156913e27652261c998fe32bc8e0545b' into iipbs_common 2025-02-28 16:37:32 +09:00
leedj312 249f3fa883 Merge remote-tracking branch 'origin/iipbs_common' into iipbs_wr-dev 2025-02-28 13:54:07 +09:00
truthwing 73f1431087 Merge commit '1cb54d220ec560042ac17fc7c0a23f7f986565d2' into iipbs_common 2025-02-28 13:52:20 +09:00
leedj312 ecb138a619 Merge branch 'iipbs_common-table' into iipbs_wr-dev 2025-02-27 10:44:39 +09:00
leedj312 bbfc08e9de table 초기작업 2025-02-26 18:12:56 +09:00
YangJinSoo94 41a9deb098 package.json에 clx 및 tailwind 추가가 2025-02-26 18:09:06 +09:00
leedj312 0a4334dba2 business component dependency추가 2025-02-26 16:45:32 +09:00
YangJinSoo94 e783084086 공통모듈-차트 추가 2025-02-26 16:40:52 +09:00
leedj312 c45bccf9ce init 2025-02-24 13:39:54 +09:00
182 changed files with 10393 additions and 846 deletions
+15 -3
View File
@@ -1,8 +1,20 @@
# turbo
.turbo
.turbo/
# dependencies
node_modules
node_modules/
# build
.next/
dist/
# build
.next
dist
# misc
.DS_Store
.DS_Store
# env
.env*
.qodo
+75 -5
View File
@@ -33,7 +33,7 @@
## 새로운 프로젝트 설치 및 실행
### 1. 프로젝트 생성(Next.js)
### 1. 프로젝트 생성(Next.js 기준)
```bash
npx create-next-app@latest ./apps/as --typescript --eslint --tailwind --app
@@ -44,6 +44,12 @@ npx create-next-app@latest ./apps/as --typescript --eslint --tailwind --app
```json
{
// 기타 설정 ...
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@common/components": "workspace:*", // 추가
"react": "^19.0.0", // 제거
@@ -62,7 +68,10 @@ npx create-next-app@latest ./apps/as --typescript --eslint --tailwind --app
{
// 기타 설정 ...
"paths": {
"@common/components": ["../../packages/common/components/src"], // 추가
"@common/components/*": ["../../../packages/common/components/src/*"],
"@common/components": ["../../../packages/common/components/src"],
"@common/network/*": ["../../../packages/common/network/*"],
"@common/network": ["../../../packages/common/network/"]
}
}
```
@@ -83,7 +92,61 @@ export default {
} satisfies Config;
```
### 5. globals.css(또는 전역 css) 수정
### 5. next.config.ts 수정
```json
import type { NextConfig } from "next";
import webpack from "webpack";
const serverApiUrl =
process.env.NEXT_PUBLIC_SERVER_API_URL || "http://localhost:3000";
const nextConfig: NextConfig = {
webpack: (config) => {
config.plugins.push(
// common/components의 vite 환경 변수를 next 환경 변수로 정의
new webpack.DefinePlugin({
"import.meta.env.VITE_PORT": JSON.stringify(
process.env.NEXT_PUBLIC_PORT,
),
"import.meta.env.VITE_PROXY_HOST": JSON.stringify(
process.env.NEXT_PUBLIC_PROXY_HOST,
),
"import.meta.env.VITE_SERVER_API_URL": JSON.stringify(
process.env.NEXT_PUBLIC_SERVER_API_URL,
),
"import.meta.env.VITE_SITE_ID": JSON.stringify(process.env.SITE_ID),
"import.meta.env.VITE_CLAIM_NAME": JSON.stringify(
process.env.NEXT_PUBLIC_CLAIM_NAME,
),
"import.meta.env.VITE_ACCESS_TOKEN": JSON.stringify(
process.env.NEXT_PUBLIC_ACCESS_TOKEN,
),
"import.meta.env.VITE_REFRESH_TOKEN": JSON.stringify(
process.env.NEXT_PUBLIC_REFRESH_TOKEN,
),
"import.meta.env.VITE_AUTH_USER_ID": JSON.stringify(
process.env.NEXT_PUBLIC_AUTH_USER_ID,
),
"process.env.SITE_ID": JSON.stringify(process.env.NEXT_PUBLIC_SITE_ID),
}),
);
return config;
},
async rewrites() {
return [
{
source: "/server/:path*",
destination: `${serverApiUrl}/:path*`,
},
];
},
};
export default nextConfig;
```
### 6. globals.css(또는 전역 css) 수정
```css
@import "@common/assets/index.css";
@@ -95,7 +158,7 @@ export default {
/* 기타 스타일 */
```
### 6. 패키지 의존성 재설치
### 7. 패키지 의존성 재설치
```bash
rm -rf node_modules pnpm-lock.yaml
@@ -109,7 +172,7 @@ pnpm install
- Next.js(^15)
- Tailwind CSS(^3)
- react-dnd-treeview(^3)
- ~~TUI Grid(^4)~~ -> TanStack Table (v8)
- TanStack Table (v8)
- Chart.js(^4)
- Storybook(^8)
- tus-js-client(^4)
@@ -120,3 +183,10 @@ pnpm install
## 링크
- 컴포넌트 가이드(스토리북): http://www.onasys.co.kr/design/template
## API 서버
http://dev.onasys.co.kr:8000
## Swagger
http://dev.onasys.co.kr:8000/webjars/swagger-ui/index.html?urls.primaryName=attach-service
+2
View File
@@ -0,0 +1,2 @@
NEXT_PUBLIC_PORT=3000
NEXT_PUBLIC_SERVER_API_URL=http://192.168.0.102:8000
-3
View File
@@ -30,9 +30,6 @@ yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
+11
View File
@@ -0,0 +1,11 @@
"use client";
import { BaseLayout } from "@common/components/ui";
export default function WithBaseLayout({
children,
}: {
children: React.ReactNode;
}) {
return <BaseLayout>{children}</BaseLayout>;
}
@@ -0,0 +1,10 @@
import { ModifyPage as VModifyPage } from "@/pages/site";
export default async function ModifyPage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
return <VModifyPage siteId={id} />;
}
@@ -0,0 +1,2 @@
import { CreatePage } from "@/pages/site";
export default CreatePage;
+100
View File
@@ -0,0 +1,100 @@
import {
ACCESS_TOKEN,
AUTH_USER_ID,
CLAIM_NAME,
REFRESH_TOKEN,
SERVER_API_URL,
SITE_ID,
} from "@/shared/config";
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
async function handler(
request: Request,
params: { url: string[] },
method: "GET" | "POST" | "PUT" | "DELETE",
) {
const cookieStore = await cookies();
const headers: Record<string, string> = {
"Content-Type": "application/json",
"X-Site-Id": SITE_ID,
};
let body = {};
const isRefreshHandler = params.url.includes("refresh");
// silent refresh
if (isRefreshHandler) {
const refreshToken = cookieStore.get(REFRESH_TOKEN);
headers[CLAIM_NAME] = refreshToken?.value ?? "";
if (!headers[CLAIM_NAME]) {
return NextResponse.json({ message: "Can't refresh" }, { status: 401 });
}
}
try {
if (!isRefreshHandler) {
body = await request.json();
}
const result = await fetch(`${SERVER_API_URL}/${params.url.join("/")}`, {
method,
headers,
body: JSON.stringify(body),
});
if (!result.ok) {
return NextResponse.json(
{ message: "Invalid Credentials" },
{ status: 401 },
);
}
const accessToken = result.headers.get(ACCESS_TOKEN);
const refreshToken = result.headers.get(REFRESH_TOKEN);
const userId = result.headers.get(AUTH_USER_ID);
if (accessToken && userId) {
const response = NextResponse.json({
[ACCESS_TOKEN]: accessToken,
[AUTH_USER_ID]: userId,
});
if (refreshToken) {
cookieStore.set(REFRESH_TOKEN, refreshToken, {
httpOnly: true,
sameSite: "lax",
path: "/",
});
}
return response;
}
return NextResponse.json(
{ message: "Invalid Credentials" },
{ status: 401 },
);
} catch (error) {
return NextResponse.json(
{ message: "Server Error", error },
{ status: 500 },
);
}
}
export async function POST(
request: Request,
props: { params: Promise<{ url: string[] }> },
) {
const params = await props.params;
return handler(request, params, "POST");
}
export async function PUT(
request: Request,
props: { params: Promise<{ url: string[] }> },
) {
const params = await props.params;
return handler(request, params, "PUT");
}
-2
View File
@@ -1,2 +0,0 @@
import { RegisterPage } from "@/pages/site";
export default RegisterPage;
+1
View File
@@ -0,0 +1 @@
NODE_OPTIONS='--inspect' npx next dev
+16
View File
@@ -0,0 +1,16 @@
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_PORT: string;
readonly VITE_PROXY_HOST: string;
readonly VITE_SERVER_API_URL: string;
readonly VITE_SITE_ID: string;
readonly VITE_CLAIM_NAME: string;
readonly VITE_ACCESS_TOKEN: string;
readonly VITE_REFRESH_TOKEN: string;
readonly VITE_AUTH_USER_ID: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
+24
View File
@@ -0,0 +1,24 @@
import { NextRequest, NextResponse } from "next/server";
const serverApiUrl =
process.env.NEXT_PUBLIC_SERVER_API_URL ?? "http://localhost:3000";
export function middleware(req: NextRequest) {
const pathname = req.nextUrl.pathname;
const searchParams = req.nextUrl.searchParams;
if (pathname.startsWith("/server")) {
const queryParams = searchParams.toString();
const newUrl = `${serverApiUrl}${pathname.replace("/server", "")}${
queryParams ? `?${queryParams}` : ""
}`;
console.log("Rewriting to: ", newUrl);
return NextResponse.rewrite(new URL(newUrl));
}
return NextResponse.next();
}
export const config = {
matcher: "/server/:path*",
};
+13 -9
View File
@@ -5,23 +5,27 @@ const nextConfig: NextConfig = {
webpack: (config) => {
config.plugins.push(
new webpack.DefinePlugin({
"import.meta.env.VITE_PORT": JSON.stringify(
process.env.NEXT_PUBLIC_PORT,
),
"import.meta.env.VITE_PROXY_HOST": JSON.stringify(
process.env.NEXT_PUBLIC_PROXY_HOST,
),
"import.meta.env.VITE_SERVER_API_URL": JSON.stringify(
process.env.VITE_SERVER_API_URL,
),
"import.meta.env.VITE_SITE_ID": JSON.stringify(
process.env.VITE_SITE_ID,
process.env.NEXT_PUBLIC_SERVER_API_URL,
),
"import.meta.env.VITE_SITE_ID": JSON.stringify(process.env.SITE_ID),
"import.meta.env.VITE_CLAIM_NAME": JSON.stringify(
process.env.VITE_CLAIM_NAME,
process.env.NEXT_PUBLIC_CLAIM_NAME,
),
"import.meta.env.VITE_ACCESS_TOKEN": JSON.stringify(
process.env.VITE_ACCESS_TOKEN,
process.env.NEXT_PUBLIC_ACCESS_TOKEN,
),
"import.meta.env.VITE_REFRESH_TOKEN": JSON.stringify(
process.env.VITE_REFRESH_TOKEN,
process.env.NEXT_PUBLIC_REFRESH_TOKEN,
),
"import.meta.env.VITE_TOKEN_ID": JSON.stringify(
process.env.VITE_TOKEN_ID,
"import.meta.env.VITE_AUTH_USER_ID": JSON.stringify(
process.env.NEXT_PUBLIC_AUTH_USER_ID,
),
}),
);
+10 -1
View File
@@ -11,13 +11,22 @@
"dependencies": {
"@common/assets": "workspace:*",
"@common/components": "workspace:*",
"@frontend-opensource/use-react-hooks": "^1.1.4",
"@hookform/resolvers": "^4.1.3",
"@radix-ui/react-label": "^2.1.2",
"@radix-ui/react-slot": "^1.1.2",
"@tanstack/react-query": "^5.67.1",
"@tanstack/react-table": "^8.21.2",
"axios": "^1.8.1",
"chart.js": "^4.4.8",
"dayjs": "^1.11.13",
"js-cookie": "^3.0.5",
"next": "15.1.7",
"react-chartjs-2": "^5.3.0",
"tailwindcss-animate": "^1.0.7"
"react-hook-form": "^7.54.2",
"tailwindcss-animate": "^1.0.7",
"zod": "^3.24.2",
"zustand": "^5.0.3"
},
"devDependencies": {
"@eslint/eslintrc": "^3",
+9 -3
View File
@@ -1,10 +1,16 @@
import "./styles/base.css";
import "./styles/components.css";
import { AppProvider } from "./providers";
import { cookies } from "next/headers";
const App = async ({ children }: Readonly<{ children: React.ReactNode }>) => {
const theme = (await cookies()).get("site-theme-key");
const App = ({ children }: Readonly<{ children: React.ReactNode }>) => {
return (
<html lang="ko">
<body>{children}</body>
<html lang="ko" data-theme={theme?.value}>
<body>
<AppProvider>{children}</AppProvider>
</body>
</html>
);
};
@@ -0,0 +1,21 @@
"use client";
import { ConfirmProvider } from "@frontend-opensource/use-react-hooks";
import { AuthWrapper } from "@/entities/auth";
import { StoreProvider } from "@/shared/providers";
import { AlertDialog } from "@/shared/ui/alert-dialog";
const AppProvider = ({ children }: Readonly<{ children: React.ReactNode }>) => {
return (
<StoreProvider>
<ConfirmProvider>
<AuthWrapper>
{children}
<AlertDialog />
</AuthWrapper>
</ConfirmProvider>
</StoreProvider>
);
};
export { AppProvider };
+1
View File
@@ -0,0 +1 @@
export { AppProvider } from "./app-provider";
+10 -1
View File
@@ -5,7 +5,7 @@
@apply relative m-[0.6rem] box-border min-h-[2rem] rounded-[0.5rem] p-[0.6rem] text-[1.3rem] text-[#666];
}
.card-border {
@apply shadow-blur border border-[#dbe2e6] bg-[rgba(255,255,255,0.6)];
@apply border border-[#dbe2e6] bg-[rgba(255,255,255,0.6)] shadow-blur;
}
.card-header {
@apply -mx-[0.6rem] flex items-center justify-between border-b border-b-[#e1e7eb] p-4;
@@ -13,4 +13,13 @@
.card-footer {
@apply -mx-[0.6rem] mt-2 flex items-center justify-center border-t border-t-[#e1e7eb] py-4;
}
[data-theme="black"] {
.card-border {
@apply border-[#3f4042] bg-[rgba(255,255,255,0.065)];
}
.card-header {
@apply border-b-[#3f4042];
}
}
}
@@ -0,0 +1,85 @@
import { AxiosError } from "axios";
import {
ENDPOINT,
JWT_EXPIRATION_TIME,
ACCESS_TOKEN,
AUTH_USER_ID,
CLAIM_NAME,
} from "@/shared/config";
import type { LoginService, ILogin } from "../model/login-interface";
import { tokenManager } from "../lib/token-manager";
export class LoginApiService implements LoginService {
private static instance: LoginApiService;
private constructor() {}
public static getInstance(): LoginApiService {
if (!LoginApiService.instance) {
LoginApiService.instance = new LoginApiService();
}
return LoginApiService.instance;
}
public async login(payload: ILogin): Promise<void> {
try {
const response = await fetch(`/api/proxy${ENDPOINT.USER_SERVICE.LOGIN}`, {
method: "POST",
body: JSON.stringify({
userId: payload.userId,
password: payload.password,
}),
});
const data = await response.json();
const accessToken = data[ACCESS_TOKEN];
const tokenId = data[AUTH_USER_ID];
if (!accessToken || !tokenId) {
throw new Error("Missing required authentication tokens");
}
tokenManager.setToken(CLAIM_NAME, accessToken);
tokenManager.setToken(AUTH_USER_ID, tokenId);
tokenManager.setupRefreshTimer(
() => this.silentRefresh(),
JWT_EXPIRATION_TIME,
);
} catch (error) {
if (error instanceof AxiosError) {
throw new Error(`Login failed: ${error.response?.data?.message}`);
}
throw new Error(`Login failed: ${error}`);
}
}
public async silentRefresh(): Promise<void> {
try {
const response = await fetch(
`/api/proxy${ENDPOINT.USER_SERVICE.SILENT_REFRESH}`,
{ method: "PUT" },
);
const data = await response.json();
const accessToken = data[ACCESS_TOKEN];
const tokenId = data[AUTH_USER_ID];
if (!accessToken || !tokenId) {
throw new Error("Missing required authentication tokens");
}
tokenManager.setToken(CLAIM_NAME, accessToken);
tokenManager.setToken(AUTH_USER_ID, tokenId);
} catch (error) {
tokenManager.clearAuthToken();
if (error instanceof AxiosError) {
throw new Error(
`Silent refresh failed: ${error.response?.data?.message}`,
);
}
throw new Error(`Silent refresh failed: ${error}`);
}
}
}
export const LoginApi = LoginApiService.getInstance();
+2
View File
@@ -0,0 +1,2 @@
export { LoginApi } from "./api/login-service";
export { AuthWrapper } from "./ui/auth-wrapper";
@@ -1,6 +1,5 @@
import axios from "axios";
import Cookies from "js-cookie";
import { CLAIM_NAME, REFRESH_TOKEN, TOKEN_ID } from "@/shared/config";
import { AUTH_USER_ID, CLAIM_NAME } from "@/shared/config";
import { getCookie, setCookie, removeCookie } from "@/shared/lib";
export class TokenManager {
private static instance: TokenManager;
@@ -15,20 +14,19 @@ export class TokenManager {
return TokenManager.instance;
}
public setToken(key: string, value: string): void {
axios.defaults.headers.common[key] = value;
public getToken(key: string): string | undefined {
return getCookie(key);
}
public setRefreshToken(token: string): void {
Cookies.set(REFRESH_TOKEN, token, {
httpOnly: true,
secure: true,
public setToken(key: string, value: string): void {
setCookie(key, value, {
secure: window.location.protocol === "https:",
sameSite: "lax",
});
}
public getRefreshToken(): string | undefined {
return Cookies.get(REFRESH_TOKEN);
public removeToken(key: string): void {
removeCookie(key);
}
public setupRefreshTimer(
@@ -42,19 +40,19 @@ export class TokenManager {
this.refreshTimer = setTimeout(() => {
callback().catch((error) => {
console.error("Silent refresh failed:", error);
this.clearAuth();
this.clearAuthToken();
});
}, expirationTime - 60000);
}
public clearAuth(): void {
public clearAuthToken(): void {
if (this.refreshTimer) {
clearTimeout(this.refreshTimer);
this.refreshTimer = null;
}
Cookies.remove(REFRESH_TOKEN);
delete axios.defaults.headers.common[CLAIM_NAME];
delete axios.defaults.headers.common[TOKEN_ID];
this.removeToken(CLAIM_NAME);
this.removeToken(AUTH_USER_ID);
}
}
@@ -5,4 +5,5 @@ export interface ILogin {
export interface LoginService {
login(payload: ILogin): Promise<void>;
silentRefresh(): Promise<void>;
}
@@ -0,0 +1,49 @@
"use client";
import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { client } from "@/shared/api";
import type { IUserInfo } from "@/shared/store";
import { getCookie, useUserStore } from "@/shared/lib";
import { ENDPOINT, AUTH_USER_ID } from "@/shared/config";
import { LoginApi } from "../api/login-service";
const AuthWrapper = ({ children }: { children: React.ReactNode }) => {
const router = useRouter();
const { userInfo, setUserInfo } = useUserStore((state) => state);
async function authCheck() {
const userId = getCookie(AUTH_USER_ID);
if (!userId) {
throw new Error("Missing required authentication tokens");
}
const response = await client.get<IUserInfo>(
`${ENDPOINT.USER_SERVICE.USERS}/${userId}`,
);
if (!userInfo) setUserInfo(response.data);
}
useEffect(() => {
(async () => {
try {
await authCheck();
} catch (error) {
console.error(error);
try {
await LoginApi.silentRefresh();
await authCheck();
} catch (refreshError) {
console.error("Token refresh failed:", refreshError);
setUserInfo(null);
router.push("/auth/login");
}
}
})();
}, []);
return <>{children}</>;
};
export { AuthWrapper };
@@ -0,0 +1,14 @@
import { client } from "@/shared/api";
import { ENDPOINT } from "@/shared/config";
import type { CodeService, ICode } from "../model/code-interface";
export class CodeApiService implements CodeService {
public async getCode(upCd: string): Promise<ICode[]> {
const response = await client.get<ICode[]>(
`${ENDPOINT.CMS_SERVICE.CODE}/${upCd}`,
);
return response.data;
}
}
export const CodeApi = new CodeApiService();
+1
View File
@@ -0,0 +1 @@
export { CodeSelect } from "./ui/code-select";
@@ -0,0 +1,9 @@
export interface ICode {
lwpoCd: string;
upCd: string;
lwpoCdNm: string;
}
export interface CodeService {
getCode(upCd: string): Promise<ICode[]>;
}
@@ -0,0 +1,45 @@
import { useQuery } from "@tanstack/react-query";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@common/components";
import { ENDPOINT } from "@/shared/config";
import { CodeApi } from "../api/code-service";
type CodeSelectProps = {
upCd: string;
value?: string;
defaultValue?: string;
onValueChange?: (value: string) => void;
};
function CodeSelect({ upCd, defaultValue, ...props }: CodeSelectProps) {
const { data: code } = useQuery({
queryKey: [ENDPOINT.CMS_SERVICE.CODE, upCd],
queryFn: () => CodeApi.getCode(upCd),
enabled: !!upCd,
});
const defaultValueText =
code?.find((item) => item.lwpoCd === defaultValue)?.lwpoCdNm ?? "선택";
return (
<Select {...props}>
<SelectTrigger className="w-[12rem]">
<SelectValue placeholder={defaultValueText} />
</SelectTrigger>
<SelectContent>
{code?.map((item) => (
<SelectItem key={item.lwpoCd} value={item.lwpoCd}>
{item.lwpoCdNm}
</SelectItem>
))}
</SelectContent>
</Select>
);
}
export { CodeSelect };
-89
View File
@@ -1,89 +0,0 @@
import { AxiosError } from "axios";
import { client } from "@/shared/api";
import {
ACCESS_TOKEN,
CLAIM_NAME,
ENDPOINT,
JWT_EXPIRATION_TIME,
REFRESH_TOKEN,
TOKEN_ID,
} from "@/shared/config";
import { tokenManager } from "../lib/token-manager";
import type { LoginService, ILogin } from "../model/login";
export class LoginApiService implements LoginService {
private static instance: LoginApiService;
private constructor() {}
public static getInstance(): LoginApiService {
if (!LoginApiService.instance) {
LoginApiService.instance = new LoginApiService();
}
return LoginApiService.instance;
}
public async login(payload: ILogin): Promise<void> {
try {
const response = await client.post(ENDPOINT.USER_SERVICE.LOGIN, {
userId: payload.userId,
password: payload.password,
});
const accessToken = response.headers[ACCESS_TOKEN];
const refreshToken = response.headers[REFRESH_TOKEN];
const tokenId = response.headers[TOKEN_ID];
if (!refreshToken || !accessToken || !tokenId) {
throw new Error("Missing required authentication tokens");
}
tokenManager.setToken(ACCESS_TOKEN, accessToken);
tokenManager.setToken(TOKEN_ID, tokenId);
tokenManager.setRefreshToken(refreshToken);
tokenManager.setupRefreshTimer(
() => this.silentRefresh(),
JWT_EXPIRATION_TIME,
);
} catch (error) {
if (error instanceof AxiosError) {
throw new Error(
`Login failed: ${error.response?.data?.message || error.message}`,
);
}
throw error;
}
}
public async silentRefresh(): Promise<void> {
try {
const refreshToken = tokenManager.getRefreshToken();
if (!refreshToken) {
throw new Error("No refresh token available");
}
tokenManager.setToken(CLAIM_NAME, refreshToken);
const response = await client.put(ENDPOINT.USER_SERVICE.SILENT_REFRESH);
const accessToken = response.headers[ACCESS_TOKEN];
const tokenId = response.headers[TOKEN_ID];
if (!accessToken || !tokenId) {
throw new Error("Missing required authentication tokens");
}
tokenManager.setToken(ACCESS_TOKEN, accessToken);
tokenManager.setToken(TOKEN_ID, tokenId);
} catch (error) {
if (error instanceof AxiosError) {
throw new Error(
`Silent refresh failed: ${error.response?.data?.message || error.message}`,
);
}
throw error;
}
}
}
export const LoginApi = LoginApiService.getInstance();
@@ -2,18 +2,21 @@
import Image from "next/image";
import { images } from "@common/assets";
import { LoginApi } from "../api/login";
import { LoginApi } from "@/entities/auth";
import "./login.css";
import { useRouter } from "next/navigation";
function LoginPage() {
const router = useRouter();
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const formData = new FormData(e.target as HTMLFormElement);
const userId = formData.get("id") as string;
const password = formData.get("password") as string;
LoginApi.login({ userId, password });
console.log(userId, password);
await LoginApi.login({ userId, password });
router.push("/site");
};
return (
@@ -0,0 +1,28 @@
import { client } from "@/shared/api";
import { ENDPOINT } from "@/shared/config";
import type {
Domain,
DomainService,
DomainList,
IDomainParams,
} from "../model/domain-interface";
export class DomainApiService implements DomainService {
public async getDomainList(params: IDomainParams): Promise<DomainList> {
const response = await client.get<DomainList>(
`${ENDPOINT.CMS_SERVICE.DOMAINS}`,
{ params },
);
return response.data;
}
public async saveDomainList(body: Domain[]): Promise<void> {
const response = await client.post<void>(
`${ENDPOINT.CMS_SERVICE.DOMAINS}`,
body,
);
return response.data;
}
}
export const DomainApi = new DomainApiService();
+22
View File
@@ -0,0 +1,22 @@
import { client } from "@/shared/api";
import { ENDPOINT } from "@/shared/config";
import type { IIpParams, IP, IpList, IpService } from "../model/ip-interface";
export class IpApiService implements IpService {
public async getIpList(params: IIpParams): Promise<IpList> {
const response = await client.get<IpList>(`${ENDPOINT.CMS_SERVICE.IPS}`, {
params,
});
return response.data;
}
public async saveIpList(body: IP[]): Promise<void> {
const response = await client.post<void>(
`${ENDPOINT.CMS_SERVICE.IPS}`,
body,
);
return response.data;
}
}
export const IpApi = new IpApiService();
@@ -0,0 +1,54 @@
import { client } from "@/shared/api";
import { ENDPOINT } from "@/shared/config";
import {
siteFormSchema,
type SiteService,
type SiteList,
type ISiteDetail,
type ISiteParams,
type SiteFormData,
} from "../model/site-interface";
export class SiteApiService implements SiteService {
public async getSiteList(params: ISiteParams): Promise<SiteList> {
const response = await client.get<SiteList>(
`${ENDPOINT.CMS_SERVICE.SITES}`,
{ params },
);
return response.data;
}
public async siteDetail(siteId: string): Promise<ISiteDetail> {
const response = await client.get<ISiteDetail>(
`${ENDPOINT.CMS_SERVICE.SITES}/${siteId}`,
);
return response.data;
}
public async createSite(data: SiteFormData): Promise<void> {
const validatedData = siteFormSchema.parse(data);
const response = await client.post<void>(
`${ENDPOINT.CMS_SERVICE.SITES}`,
validatedData,
);
return response.data;
}
public async modifySite(siteId: string, data: SiteFormData): Promise<void> {
const validatedData = siteFormSchema.parse(data);
const response = await client.put<void>(
`${ENDPOINT.CMS_SERVICE.SITES}/${siteId}`,
validatedData,
);
return response.data;
}
public async deleteSite(siteId: string): Promise<void> {
const response = await client.delete<void>(
`${ENDPOINT.CMS_SERVICE.SITES}/${siteId}`,
);
return response.data;
}
}
export const SiteApi = new SiteApiService();
+2 -1
View File
@@ -1,2 +1,3 @@
export { RegisterPage } from "./ui/register-page";
export { CreatePage } from "./ui/create-page";
export { ModifyPage } from "./ui/modify-page";
export { SitePage } from "./ui/site-page";
@@ -1,59 +0,0 @@
import { createColumnHelper } from "@tanstack/react-table";
import { fakerKO as faker } from "@faker-js/faker";
type Site = {
id: number;
사이트코드: string;
사이트명: string;
대표_URL: string;
기본_사이트_여부: boolean;
사용_여부: boolean;
등록자: string;
등록일: string;
};
faker.seed(123);
const data: Site[] = Array.from({ length: 100 }, (_, i) => ({
id: i + 1,
사이트코드: faker.string.alpha(2).toUpperCase(),
사이트명: faker.lorem.word(),
대표_URL: faker.internet.url(),
기본_사이트_여부: faker.datatype.boolean(),
사용_여부: faker.datatype.boolean(),
등록자: faker.person.fullName(),
등록일: faker.date.recent().toISOString().split("T")[0] as string,
}));
const columnHelper = createColumnHelper<Site>();
const columns = [
columnHelper.accessor("id", {
header: "NO",
}),
columnHelper.accessor("사이트코드", {
header: "사이트코드",
}),
columnHelper.accessor("사이트명", {
header: "사이트명",
}),
columnHelper.accessor("대표_URL", {
header: "대표 URL",
}),
columnHelper.accessor("기본_사이트_여부", {
header: "기본 사이트 여부",
cell: (info) => (info.getValue() ? "Y" : "N"),
}),
columnHelper.accessor("사용_여부", {
header: "사용 여부",
cell: (info) => (info.getValue() ? "Y" : "N"),
}),
columnHelper.accessor("등록자", {
header: "등록자",
}),
columnHelper.accessor("등록일", {
header: "등록일",
}),
];
export { data, columns };
@@ -0,0 +1,31 @@
import { z } from "zod";
import type { IPageableParams, PageableList } from "@/shared/model";
export interface IDomainParams extends IPageableParams {
keywordType?: string;
keyword?: string;
siteId?: string;
useYn?: string;
}
export const domainSchema = z.object({
siteDmnNo: z.number().nullish(),
siteId: z.string(),
dmnAddr: z.string().nonempty(),
useYn: z.string(),
rprsDmnYn: z.string(),
mode: z.string(),
});
export const domainFormSchema = z.object({
domains: z.array(domainSchema),
});
export type Domain = z.infer<typeof domainSchema>;
export type DomainFormData = z.infer<typeof domainFormSchema>;
export type DomainList = PageableList<Domain[]>;
export interface DomainService {
getDomainList(params: IDomainParams): Promise<DomainList>;
saveDomainList(body: Domain[]): Promise<void>;
}
@@ -0,0 +1,29 @@
import { z } from "zod";
import type { IPageableParams, PageableList } from "@/shared/model";
export interface IIpParams extends IPageableParams {
siteId: string;
ipAddr?: string;
prmYn?: string;
}
export const ipSchema = z.object({
mngNo: z.number().nullish(),
siteId: z.string(),
ipAddr: z.string().nonempty(),
prmYn: z.string(),
mode: z.string(),
});
export const ipFormSchema = z.object({
ips: z.array(ipSchema),
});
export type IP = z.infer<typeof ipSchema>;
export type IPFormData = z.infer<typeof ipFormSchema>;
export type IpList = PageableList<IP[]>;
export interface IpService {
getIpList(params: IIpParams): Promise<IpList>;
saveIpList(body: IP[]): Promise<void>;
}
@@ -0,0 +1,57 @@
import { z } from "zod";
import type { IPageableParams, PageableList } from "@/shared/model";
export interface ISiteParams extends IPageableParams {
siteNm?: string;
siteKndCd?: string;
useYn?: string;
}
export interface ISite {
siteId: string;
siteNm: string;
siteKindCode: string;
bscSiteYn: string;
siteAddr: string;
useYn: string;
regDt: string;
rgTrNm: string;
}
export interface ISiteDetail extends SiteFormData {
siteId: string;
siteKindNm: string;
basicSiteYn: string;
faxNumber: string;
regDt: string;
rgTr: string;
mdfcnDt: string;
mdFr: string;
rgTrNm: string;
mdFrNm: string;
}
export const siteFormSchema = z.object({
siteId: z.string().max(2).nonempty(),
siteNm: z.string().max(100).nonempty(),
siteExpln: z.string().max(1000).nullable(),
siteKndCd: z.string().max(10).nonempty(),
siteAddr: z.string().max(2000).nullable(),
faxNo: z.string().max(100).nullable(),
telNo: z.string().max(1000).nullable(),
lwndCn: z.string().max(2000).nullable(),
bscSiteYn: z.string(),
bkmkIcon: z.string().max(100).nullable(),
useYn: z.string(),
siteSkn: z.string().max(10).nullable(),
});
export type SiteFormData = z.infer<typeof siteFormSchema>;
export type SiteList = PageableList<ISite[]>;
export interface SiteService {
getSiteList(params: ISiteParams): Promise<SiteList>;
siteDetail(siteId: string): Promise<ISiteDetail>;
modifySite(siteId: string, data: SiteFormData): Promise<void>;
createSite(data: SiteFormData): Promise<void>;
}
@@ -0,0 +1,48 @@
import dayjs from "dayjs";
import { createColumnHelper } from "@tanstack/react-table";
import type { ISite } from "./site-interface";
const columnHelper = createColumnHelper<ISite>();
const columns = [
columnHelper.accessor((_, index) => index + 1, {
id: "no",
header: "NO",
}),
columnHelper.accessor("siteId", {
id: "siteId",
header: "사이트코드",
}),
columnHelper.accessor("siteNm", {
id: "siteNm",
header: "사이트명",
}),
columnHelper.accessor("siteAddr", {
id: "siteAddr",
header: "대표 URL",
}),
columnHelper.accessor("bscSiteYn", {
id: "bscSiteYn",
header: "기본 사이트 여부",
cell: (info) => (info.getValue() ? "Y" : "N"),
}),
columnHelper.accessor("useYn", {
id: "useYn",
header: "사용 여부",
cell: (info) => (info.getValue() ? "Y" : "N"),
}),
columnHelper.accessor("rgTrNm", {
id: "rgTrNm",
header: "등록자",
}),
columnHelper.accessor("regDt", {
id: "regDt",
header: "등록일",
cell: (info) => {
const date = dayjs(info.getValue());
return date.format("YYYY-MM-DD");
},
}),
];
export { columns };
+48
View File
@@ -0,0 +1,48 @@
"use client";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { useMutation } from "@tanstack/react-query";
import { zodResolver } from "@hookform/resolvers/zod";
import { SiteApi } from "../api/site-service";
import { siteFormSchema, type SiteFormData } from "../model/site-interface";
import { SitePageLayout } from "./layout";
import { SiteForm } from "./site-form";
import { useAlertStore } from "@/shared/lib/use-alert-store";
function CreatePage() {
const router = useRouter();
const { setMessage: alert } = useAlertStore((state) => state);
const { mutateAsync: createSite } = useMutation({
mutationFn: (data: SiteFormData) => SiteApi.createSite(data),
onSuccess: () => {
alert("등록되었습니다.", router.back);
},
});
const form = useForm<SiteFormData>({
resolver: zodResolver(siteFormSchema),
defaultValues: {
siteId: "",
siteNm: "",
siteExpln: "",
siteKndCd: "",
siteAddr: "",
faxNo: "",
telNo: "",
lwndCn: "",
bscSiteYn: "",
bkmkIcon: "",
useYn: "",
siteSkn: "",
},
});
return (
<SitePageLayout>
<SiteForm form={form} handleSave={createSite} />
</SitePageLayout>
);
}
export { CreatePage };
@@ -0,0 +1,321 @@
import { useState } from "react";
import { useMutation, useQuery } from "@tanstack/react-query";
import { zodResolver } from "@hookform/resolvers/zod";
import { useConfirm } from "@frontend-opensource/use-react-hooks";
import { useForm, useFieldArray } from "react-hook-form";
import {
Dialog,
DialogTrigger,
Button,
DialogContent,
DialogHeader,
DialogTitle,
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
Input,
RadioGroup,
RadioGroupItem,
DialogFooter,
DialogClose,
Checkbox,
} from "@common/components";
import {
Form,
FormControl,
FormField,
FormItem,
FormMessage,
} from "@/shared/ui/form";
import { ENDPOINT } from "@/shared/config";
import { DomainApi } from "../api/domain-service";
import {
domainFormSchema,
type Domain,
type DomainFormData,
} from "../model/domain-interface";
import { ConfirmDialog } from "@/shared/ui/confirm-dialog";
import { useAlertStore } from "@/shared/lib/use-alert-store";
type DomainManagementDialogProps = {
siteId: string;
open?: boolean;
onOpenChange?: (open: boolean) => void;
handleSaveDomain?: (rows: Domain[]) => void;
};
function DomainManagementDialog({
siteId,
handleSaveDomain,
...props
}: DomainManagementDialogProps) {
const { confirm } = useConfirm();
const { setMessage: alert } = useAlertStore((state) => state);
const { data: domainList } = useQuery({
queryKey: [ENDPOINT.CMS_SERVICE.DOMAINS, props.open],
queryFn: () => DomainApi.getDomainList({ siteId }),
select: (data) => {
const domains = data.content.map((item) => ({
...item,
mode: "U",
}));
initialForm();
return domains;
},
});
const { mutateAsync } = useMutation({
mutationFn: (body: Domain[]) => DomainApi.saveDomainList(body),
});
const form = useForm<DomainFormData>({
resolver: zodResolver(domainFormSchema),
values: {
domains: domainList ?? [],
},
});
const { fields, append, remove, update } = useFieldArray({
control: form.control,
name: "domains",
});
const [onConfirm, setOnConfirm] = useState(false);
const [selectedRows, setSelectedRows] = useState<number[]>([]);
const initialForm = () => {
form.reset();
setSelectedRows([]);
};
const onSubmit = async (data: DomainFormData) => {
setOnConfirm(true);
if (await confirm("저장하시겠습니까?")) {
setOnConfirm(false);
await mutateAsync(data.domains);
handleSaveDomain?.(data.domains);
alert("저장되었습니다.");
}
setOnConfirm(false);
};
const handleAddDomain = () => {
append({
siteDmnNo: null,
siteId,
dmnAddr: "",
useYn: "Y",
rprsDmnYn: "N",
mode: "C",
});
};
const handleSelectAll = () => {
if (selectedRows.length === fields.length) {
setSelectedRows([]);
} else {
setSelectedRows(fields.map((_, index) => index));
}
};
const handleSelectRow = (i: number) => {
setSelectedRows((prev) =>
prev.includes(i) ? prev.filter((j) => j !== i) : [...prev, i],
);
};
const handleDeleteDomain = async () => {
if (selectedRows.length === 0) return;
const sortedIndices = [...selectedRows].sort((a, b) => b - a);
sortedIndices.forEach((i) => {
const field = fields[i];
if (field?.siteDmnNo) {
update(i, {
...field,
mode: "D",
});
} else {
remove(i);
}
});
setSelectedRows([]);
};
const handleChangeRprsDmnYn = (i: number) => {
fields.forEach((_, j) => {
if (j === i) return;
form.setValue(`domains.${j}.rprsDmnYn`, "N");
});
};
const isAllSelected =
fields.length > 0 && selectedRows.length === fields.length;
return (
<>
<Dialog {...props}>
<DialogTrigger asChild>
<Button>도메인 관리</Button>
</DialogTrigger>
<DialogContent className="max-w-[60rem]" aria-describedby={undefined}>
<DialogHeader>
<DialogTitle>도메인 관리</DialogTitle>
</DialogHeader>
<Form {...form}>
<form
onSubmit={(e) => {
e.preventDefault();
e.stopPropagation();
form.handleSubmit(onSubmit)(e);
}}
>
<div className="mb-4 flex justify-end gap-2">
<Button type="button" size="sm" onClick={handleAddDomain}>
항목 추가
</Button>
<Button
type="button"
size="sm"
color="red"
onClick={handleDeleteDomain}
disabled={selectedRows.length === 0}
>
항목 삭제
</Button>
</div>
<div className="card card-border max-h-[28.5rem] overflow-auto">
<Table variant="secondary">
<colgroup>
<col width="10%" />
<col width="auto" />
<col width="15%" />
<col width="25%" />
</colgroup>
<TableHeader className="sticky -top-[0.6rem]">
<TableRow>
<TableHead className="!px-0">
<Checkbox
checked={isAllSelected}
onCheckedChange={handleSelectAll}
/>
</TableHead>
<TableHead>도메인 주소</TableHead>
<TableHead>대표 URL</TableHead>
<TableHead>사용여부</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{fields.map((field, i) => {
if (field.mode === "D") return null;
return (
<TableRow key={field.id}>
<TableCell align="center" className="!px-0">
<Checkbox
checked={selectedRows.includes(i)}
onCheckedChange={() => handleSelectRow(i)}
/>
</TableCell>
<TableCell align="center">
<FormField
control={form.control}
name={`domains.${i}.dmnAddr`}
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
className="!text-[1.3rem]"
/>
</FormControl>
<FormMessage className="text-left" />
</FormItem>
)}
/>
</TableCell>
<TableCell align="center">
<FormField
control={form.control}
name={`domains.${i}.rprsDmnYn`}
render={({ field }) => (
<FormItem>
<FormControl>
<Checkbox
checked={field.value === "Y"}
onCheckedChange={(checked) => {
field.onChange(checked ? "Y" : "N");
handleChangeRprsDmnYn(i);
}}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
<TableCell align="center">
<FormField
control={form.control}
name={`domains.${i}.useYn`}
render={({ field }) => (
<FormItem>
<FormControl>
<RadioGroup
value={field.value}
onValueChange={field.onChange}
className="flex justify-center"
>
<div className="flex items-center space-x-2">
<RadioGroupItem
value="Y"
id={`useY-${i}`}
/>
<label htmlFor={`useY-${i}`}>예</label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem
value="N"
id={`useN-${i}`}
/>
<label htmlFor={`useN-${i}`}>
아니오
</label>
</div>
</RadioGroup>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</div>
<DialogFooter className="!justify-center">
<Button type="submit" size="lg">
저장
</Button>
<DialogClose asChild>
<Button type="button" size="lg" color="white">
취소
</Button>
</DialogClose>
</DialogFooter>
</form>
</Form>
</DialogContent>
</Dialog>
<ConfirmDialog open={onConfirm} />
</>
);
}
export { DomainManagementDialog };
+252 -131
View File
@@ -1,6 +1,8 @@
"use client";
import { useState } from "react";
import { useMutation, useQuery } from "@tanstack/react-query";
import { zodResolver } from "@hookform/resolvers/zod";
import { useConfirm } from "@frontend-opensource/use-react-hooks";
import { useForm, useFieldArray } from "react-hook-form";
import {
Dialog,
DialogTrigger,
@@ -17,147 +19,266 @@ import {
Input,
RadioGroup,
RadioGroupItem,
DialogFooter,
DialogClose,
Checkbox,
} from "@common/components";
import {
Form,
FormControl,
FormField,
FormItem,
FormMessage,
} from "@/shared/ui/form";
import { ENDPOINT } from "@/shared/config";
import { IpApi } from "../api/ip-service";
import { ipFormSchema, type IP, type IPFormData } from "../model/ip-interface";
import { ConfirmDialog } from "@/shared/ui/confirm-dialog";
import { useAlertStore } from "@/shared/lib/use-alert-store";
type IP = {
id: number;
ipAddress: string;
allowed: boolean;
type IPManagementDialogProps = {
siteId: string;
triggerDisabled?: boolean;
open?: boolean;
onOpenChange?: (open: boolean) => void;
};
function IPManagementDialog() {
const [rows, setRows] = useState<IP[]>([]);
const [rowSelection, setRowSelection] = useState<IP["id"][]>([]);
function IPManagementDialog({
siteId,
triggerDisabled,
...props
}: IPManagementDialogProps) {
const { confirm } = useConfirm();
const { setMessage: alert } = useAlertStore((state) => state);
const handleSave = () => {};
const { data: ipList } = useQuery({
queryKey: [ENDPOINT.CMS_SERVICE.IPS, props.open],
queryFn: () => IpApi.getIpList({ siteId, sort: [] }),
select: (data) => {
const ips = data.content.map((item) => ({
...item,
mode: "U",
}));
initialForm();
return ips;
},
});
const { mutateAsync } = useMutation({
mutationFn: (body: IP[]) => IpApi.saveIpList(body),
});
const form = useForm<IPFormData>({
resolver: zodResolver(ipFormSchema),
values: {
ips: ipList ?? [],
},
});
const { fields, append, remove, update } = useFieldArray({
control: form.control,
name: "ips",
});
const [onConfirm, setOnConfirm] = useState(false);
const [selectedRows, setSelectedRows] = useState<number[]>([]);
const initialForm = () => {
form.reset();
setSelectedRows([]);
};
const onSubmit = async (data: IPFormData) => {
setOnConfirm(true);
if (await confirm("저장하시겠습니까?")) {
setOnConfirm(false);
await mutateAsync(data.ips);
alert("저장되었습니다.");
}
};
const handleAddIP = () => {
const newIP: IP = {
id: Date.now(),
ipAddress: "",
allowed: true,
};
setRows([...rows, newIP]);
};
const handleDeleteIP = () => {
const filteredRows = rows.filter((row) => !rowSelection.includes(row.id));
setRows(filteredRows);
setRowSelection([]);
};
const handleIPAddressChange = (id: number, value: string) => {
setRows(
rows.map((row) => (row.id === id ? { ...row, ipAddress: value } : row)),
);
};
const handleAllowedChange = (id: number, value: boolean) => {
setRows(
rows.map((row) => (row.id === id ? { ...row, allowed: value } : row)),
);
};
const toggleRowSelection = (id: number) => {
setRowSelection((prev) => {
if (prev.includes(id)) {
return prev.filter((item) => item !== id);
} else {
return [...prev, id];
}
append({
mngNo: null,
siteId,
ipAddr: "",
prmYn: "Y",
mode: "C",
});
};
const handleSelectAll = () => {
if (selectedRows.length === fields.length) {
setSelectedRows([]);
} else {
setSelectedRows(fields.map((_, index) => index));
}
};
const handleSelectRow = (i: number) => {
setSelectedRows((prev) =>
prev.includes(i) ? prev.filter((j) => j !== i) : [...prev, i],
);
};
const handleDeleteIP = async () => {
if (selectedRows.length === 0) return;
const sortedIndices = [...selectedRows].sort((a, b) => b - a);
sortedIndices.forEach((i) => {
const field = fields[i];
if (field?.mngNo) {
update(i, {
...field,
mode: "D",
});
} else {
remove(i);
}
});
setSelectedRows([]);
};
const isAllSelected =
fields.length > 0 && selectedRows.length === fields.length;
return (
<Dialog>
<DialogTrigger asChild>
<Button>IP 관리</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[600px]">
<DialogHeader>
<DialogTitle>IP 관리</DialogTitle>
</DialogHeader>
<div className="mb-4 flex justify-end gap-2">
<Button size="sm" color="green">
엑셀 업로드
</Button>
<Button size="sm" onClick={handleSave}>
저장
</Button>
<Button size="sm" color="white" onClick={handleAddIP}>
항목 추가
</Button>
<Button
size="sm"
color="red"
onClick={handleDeleteIP}
disabled={rowSelection.length === 0}
>
항목 삭제
</Button>
</div>
<div className="card card-border">
<Table>
<colgroup>
<col width="10%" />
<col width="10%" />
<col width="55%" />
<col width="25%" />
</colgroup>
<TableHeader>
<TableRow>
<TableHead>NO</TableHead>
<TableHead>선택</TableHead>
<TableHead>IP 주소</TableHead>
<TableHead>허용여부</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{rows.map((row, idx) => (
<TableRow key={row.id}>
<TableCell align="center">{idx + 1}</TableCell>
<TableCell align="center">
<Checkbox
checked={rowSelection.includes(row.id)}
onCheckedChange={() => toggleRowSelection(row.id)}
className="cursor-pointer"
/>
</TableCell>
<TableCell align="center">
<Input
value={row.ipAddress}
onChange={(e) =>
handleIPAddressChange(row.id, e.target.value)
}
className="!text-[1.3rem]"
/>
</TableCell>
<TableCell align="center">
<RadioGroup
value={row.allowed ? "true" : "false"}
onValueChange={(value) =>
handleAllowedChange(row.id, value === "true")
}
className="flex justify-center"
>
<div className="flex items-center space-x-2">
<RadioGroupItem value="true" id={`allow-${row.id}`} />
<label htmlFor={`allow-${row.id}`}>예</label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="false" id={`deny-${row.id}`} />
<label htmlFor={`deny-${row.id}`}>아니오</label>
</div>
</RadioGroup>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
</DialogContent>
</Dialog>
<>
<Dialog {...props}>
<DialogTrigger asChild>
<Button disabled={triggerDisabled}>IP 관리</Button>
</DialogTrigger>
<DialogContent className="max-w-[60rem]" aria-describedby={undefined}>
<DialogHeader>
<DialogTitle>IP 관리</DialogTitle>
</DialogHeader>
<Form {...form}>
<form
onSubmit={(e) => {
e.preventDefault();
e.stopPropagation();
form.handleSubmit(onSubmit)(e);
}}
>
<div className="mb-4 flex justify-end gap-2">
<Button type="button" size="sm" onClick={handleAddIP}>
항목 추가
</Button>
<Button
type="button"
size="sm"
color="red"
onClick={handleDeleteIP}
disabled={selectedRows.length === 0}
>
항목 삭제
</Button>
</div>
<div className="card card-border max-h-[28.5rem] overflow-auto">
<Table variant="secondary">
<colgroup>
<col width="10%" />
<col width="65%" />
<col width="25%" />
</colgroup>
<TableHeader className="sticky -top-[0.6rem]">
<TableRow>
<TableHead className="!px-0">
<Checkbox
checked={isAllSelected}
onCheckedChange={handleSelectAll}
/>
</TableHead>
<TableHead>IP 주소</TableHead>
<TableHead>허용여부</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{fields.map((field, i) => {
if (field.mode === "D") return null;
return (
<TableRow key={field.id}>
<TableCell align="center" className="!px-0">
<Checkbox
checked={selectedRows.includes(i)}
onCheckedChange={() => handleSelectRow(i)}
/>
</TableCell>
<TableCell align="center">
<FormField
control={form.control}
name={`ips.${i}.ipAddr`}
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
className="!text-[1.3rem]"
/>
</FormControl>
<FormMessage className="text-left" />
</FormItem>
)}
/>
</TableCell>
<TableCell align="center">
<FormField
control={form.control}
name={`ips.${i}.prmYn`}
render={({ field }) => (
<FormItem>
<FormControl>
<RadioGroup
value={field.value}
onValueChange={field.onChange}
className="flex justify-center"
>
<div className="flex items-center space-x-2">
<RadioGroupItem
value="Y"
id={`prmY-${i}`}
/>
<label htmlFor={`prmY-${i}`}>예</label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem
value="N"
id={`prmN-${i}`}
/>
<label htmlFor={`prmN-${i}`}>
아니오
</label>
</div>
</RadioGroup>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</div>
<DialogFooter className="!justify-center">
<Button type="submit" size="lg">
저장
</Button>
<DialogClose asChild>
<Button type="button" size="lg" color="white">
취소
</Button>
</DialogClose>
</DialogFooter>
</form>
</Form>
</DialogContent>
</Dialog>
<ConfirmDialog open={onConfirm} />
</>
);
}
+6 -10
View File
@@ -1,15 +1,11 @@
import { BaseLayout } from "@common/components";
function SitePageLayout({ children }: { children: React.ReactNode }) {
return (
<BaseLayout>
<div className="h-auto min-h-full bg-[#f1f6f9]">
<h2 className="px-[1.8rem] pt-[2rem] text-[2.4rem] font-semibold text-[#4c5e6f]">
사이트 관리
</h2>
{children}
</div>
</BaseLayout>
<div className="h-auto min-h-full bg-container">
<h2 className="px-[1.8rem] pt-[2rem] text-[2.4rem] font-semibold text-title">
사이트 관리
</h2>
{children}
</div>
);
}
+77
View File
@@ -0,0 +1,77 @@
"use client";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { zodResolver } from "@hookform/resolvers/zod";
import { ENDPOINT } from "@/shared/config";
import { useAlertStore } from "@/shared/lib/use-alert-store";
import { SiteApi } from "../api/site-service";
import { siteFormSchema, type SiteFormData } from "../model/site-interface";
import { SitePageLayout } from "./layout";
import { SiteForm } from "./site-form";
function ModifyPage({ siteId }: { siteId: string }) {
const isModifyMode = !!siteId;
const router = useRouter();
const queryClient = useQueryClient();
const { setMessage: alert } = useAlertStore((state) => state);
const { data: siteDetail } = useQuery({
queryKey: [ENDPOINT.CMS_SERVICE.SITES, siteId],
queryFn: () => SiteApi.siteDetail(siteId),
select: (data) => {
const keys = Object.keys(siteFormSchema.shape);
const filteredData = Object.fromEntries(
Object.entries(data).filter(([key]) => keys.includes(key)),
);
return {
...filteredData,
faxNo: data.faxNumber,
bscSiteYn: data.basicSiteYn,
};
},
enabled: isModifyMode,
});
const { mutateAsync: modifySite } = useMutation({
mutationFn: (data: SiteFormData) => SiteApi.modifySite(siteId, data),
onSuccess: () => {
alert("수정되었습니다.", () => {
queryClient.invalidateQueries({
queryKey: [ENDPOINT.CMS_SERVICE.SITES],
});
});
},
});
const { mutateAsync: deleteSite } = useMutation({
mutationFn: () => SiteApi.deleteSite(siteId),
onSuccess: () => {
alert("삭제되었습니다.", () => {
queryClient.invalidateQueries({
queryKey: [ENDPOINT.CMS_SERVICE.SITES],
});
router.back();
});
},
});
const form = useForm<SiteFormData>({
resolver: zodResolver(siteFormSchema),
values: siteDetail as SiteFormData,
});
return (
<SitePageLayout>
<SiteForm
form={form}
siteId={siteId}
handleSave={modifySite}
handleDelete={deleteSite}
/>
</SitePageLayout>
);
}
export { ModifyPage };
-196
View File
@@ -1,196 +0,0 @@
import {
Button,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
Input,
Label,
RadioGroup,
RadioGroupItem,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
} from "@common/components";
import { SitePageLayout } from "./layout";
import { IPManagementDialog } from "./ip-management-dialog";
function RegisterPage() {
return (
<SitePageLayout>
<div className="card card-border !mt-6">
<div className="card-header">
<h3 className="text-2xl font-medium text-[#666]">사이트 등록/수정</h3>
</div>
<div className="card">
<Table variant="secondary">
<colgroup>
<col width="20%" />
<col width="80%" />
</colgroup>
<TableBody>
<TableRow>
<TableHead>사이트 코드</TableHead>
<TableCell className="border">
<Input className="w-[12rem] !text-[1.3rem]" />
</TableCell>
</TableRow>
<TableRow>
<TableHead>사이트 구분</TableHead>
<TableCell className="border">
<div className="flex gap-2">
<DropdownMenu>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
color="white"
className="group w-[12rem] justify-between px-4"
>
선택
<i className="diveicon di-chevron-down translate-y-0.5 transition-transform group-data-[state=open]:translate-y-0 group-data-[state=open]:rotate-180" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-[12rem]">
<DropdownMenuItem>내부</DropdownMenuItem>
<DropdownMenuItem>외부</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</DropdownMenu>
<IPManagementDialog />
</div>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사이트 디자인</TableHead>
<TableCell className="border">
<DropdownMenu>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
color="white"
className="group w-[12rem] justify-between px-4"
>
선택
<i className="diveicon di-chevron-down translate-y-0.5 transition-transform group-data-[state=open]:translate-y-0 group-data-[state=open]:rotate-180" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-[12rem]">
<DropdownMenuItem>라이트</DropdownMenuItem>
<DropdownMenuItem>다크</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</DropdownMenu>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사이트명</TableHead>
<TableCell className="border">
<Input
className="!text-[1.3rem]"
placeholder="사이트명을 입력하십시오."
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사이트 설명</TableHead>
<TableCell className="border">
<Input
className="!text-[1.3rem]"
placeholder="사이트 설명을 입력하십시오."
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사이트 하단 표기 주소</TableHead>
<TableCell className="border">
<Input
className="!text-[1.3rem]"
placeholder="사이트 하단 주소를 입력하십시오."
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사이트 하단 표기 전화번호</TableHead>
<TableCell className="border">
<Input
className="!text-[1.3rem]"
placeholder="사이트 하단 전화번호를 입력하십시오."
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사이트 하단 표기 팩스번호</TableHead>
<TableCell className="border">
<Input
className="!text-[1.3rem]"
placeholder="사이트 하단 팩스번호를 입력하십시오."
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사이트 하단 표기 내용</TableHead>
<TableCell className="border">
<Input
className="!text-[1.3rem]"
placeholder="사이트 표기 내용을 입력하십시오. (ex. COPYRIGHT c 2013 KECO. ALL RIGHTS RESERVED.)"
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>북마크 아이콘</TableHead>
<TableCell className="border">
<Input
className="!text-[1.3rem]"
placeholder="아이콘 파일 경로 및 파일명을 입력하여 주십시오."
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>기본 사이트 여부</TableHead>
<TableCell className="border">
<RadioGroup defaultValue="comfortable">
<div className="flex items-center space-x-2">
<RadioGroupItem value="default" id="r1" />
<Label htmlFor="r1">예</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="comfortable" id="r2" />
<Label htmlFor="r2">아니오</Label>
</div>
</RadioGroup>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사용 여부</TableHead>
<TableCell className="border">
<RadioGroup defaultValue="comfortable">
<div className="flex items-center space-x-2">
<RadioGroupItem value="default" id="r1" />
<Label htmlFor="r1">사용</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="comfortable" id="r2" />
<Label htmlFor="r2">사용안함</Label>
</div>
</RadioGroup>
</TableCell>
</TableRow>
</TableBody>
</Table>
</div>
</div>
<div className="flex justify-center gap-4 pb-12 pt-10">
<Button size="lg">저장</Button>
<Button size="lg" color="white">
취소
</Button>
<Button size="lg" color="red">
삭제
</Button>
</div>
</SitePageLayout>
);
}
export { RegisterPage };
+425
View File
@@ -0,0 +1,425 @@
import { useState } from "react";
import { useRouter } from "next/navigation";
import { useConfirm } from "@frontend-opensource/use-react-hooks";
import { type UseFormReturn } from "react-hook-form";
import {
Button,
Input,
Label,
RadioGroup,
RadioGroupItem,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
} from "@common/components";
import { CodeSelect } from "@/entities/code";
import {
FormItem,
FormControl,
FormField,
Form,
FormMessage,
} from "@/shared/ui/form";
import { ConfirmDialog } from "@/shared/ui/confirm-dialog";
import type { SiteFormData } from "../model/site-interface";
import type { Domain } from "../model/domain-interface";
import { IPManagementDialog } from "./ip-management-dialog";
import { DomainManagementDialog } from "./domain-management-dialog";
type SiteFormProps = {
form: UseFormReturn<SiteFormData>;
siteId?: string;
handleSave: (data: SiteFormData) => Promise<void>;
handleDelete?: () => Promise<void>;
};
function SiteForm({ form, siteId, handleSave, handleDelete }: SiteFormProps) {
const isModifyMode = !!siteId;
const router = useRouter();
const { confirm } = useConfirm();
const [onConfirm, setOnConfirm] = useState(false);
const [isIpManagementOpen, setIsIpManagementOpen] = useState(false);
const [isDomainManagementOpen, setIsDomainManagementOpen] = useState(false);
const [domainUrl, setDomainUrl] = useState("");
const handleSaveDomain = (rows: Domain[]) => {
setDomainUrl(rows.find((row) => row.rprsDmnYn === "Y")?.dmnAddr || "");
};
const onSubmit = async (data: SiteFormData) => {
const confirmMessage = isModifyMode
? "수정하시겠습니까?"
: "저장하시겠습니까?";
setOnConfirm(true);
if (await confirm(confirmMessage)) {
setOnConfirm(false);
handleSave(data);
}
setOnConfirm(false);
};
const onDelete = async () => {
setOnConfirm(true);
if (await confirm("삭제하시겠습니까?")) {
setOnConfirm(false);
handleDelete?.();
}
setOnConfirm(false);
};
return (
<>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
<div className="card card-border !mt-6">
<div className="card-header">
<h3 className="text-2xl font-medium text-label">
사이트 등록/수정
</h3>
</div>
<div className="card">
<Table variant="secondary">
<colgroup>
<col width="20%" />
<col width="80%" />
</colgroup>
<TableBody>
<TableRow>
<TableHead>사이트 코드</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="siteId"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
className="w-[12rem] !text-[1.3rem]"
disabled={isModifyMode}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사이트 구분</TableHead>
<TableCell className="border">
<div className="flex gap-2">
<FormField
control={form.control}
name="siteKndCd"
render={({ field }) => (
<FormItem>
<FormControl>
<CodeSelect
{...field}
upCd="SITEKNDCD"
onValueChange={field.onChange}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{isModifyMode && (
<IPManagementDialog
siteId={siteId}
triggerDisabled={form.watch("siteKndCd") === "O"}
open={isIpManagementOpen}
onOpenChange={setIsIpManagementOpen}
/>
)}
</div>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사이트 디자인</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="siteSkn"
render={({ field }) => (
<FormItem>
<FormControl>
<CodeSelect
{...field}
value={field.value ?? ""}
upCd="SITESKINCD"
onValueChange={field.onChange}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사이트명</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="siteNm"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
className="!text-[1.3rem]"
placeholder="사이트명을 입력하십시오."
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사이트 설명</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="siteExpln"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
placeholder="사이트 설명을 입력하십시오."
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
{isModifyMode && (
<TableRow>
<TableHead>사이트 도메인</TableHead>
<TableCell className="border">
<div className="flex gap-2">
<div className="h-[3.2rem] w-[21.5rem] cursor-not-allowed rounded-md border border-input bg-form px-3 py-2 text-[1.3rem] opacity-50">
{domainUrl}
</div>
<DomainManagementDialog
siteId={siteId}
open={isDomainManagementOpen}
onOpenChange={setIsDomainManagementOpen}
handleSaveDomain={handleSaveDomain}
/>
</div>
</TableCell>
</TableRow>
)}
<TableRow>
<TableHead>사이트 하단 표기 주소</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="siteAddr"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
placeholder="사이트 하단 주소를 입력하십시오."
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사이트 하단 표기 전화번호</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="telNo"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
placeholder="사이트 하단 전화번호를 입력하십시오."
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사이트 하단 표기 팩스번호</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="faxNo"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
placeholder="사이트 하단 팩스번호를 입력하십시오."
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사이트 하단 표기 내용</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="lwndCn"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
placeholder="사이트 표기 내용을 입력하십시오. (ex. COPYRIGHT c 2013 KECO. ALL RIGHTS RESERVED.)"
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>북마크 아이콘</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="bkmkIcon"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
placeholder="아이콘 파일 경로 및 파일명을 입력하여 주십시오."
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>기본 사이트 여부</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="bscSiteYn"
render={({ field }) => (
<FormItem>
<FormControl>
<RadioGroup
{...field}
name="bscSiteYn"
onValueChange={field.onChange}
>
<div className="flex items-center space-x-2">
<RadioGroupItem value="Y" id="bscSiteY" />
<Label htmlFor="bscSiteY">예</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="N" id="bscSiteN" />
<Label htmlFor="bscSiteN">아니오</Label>
</div>
</RadioGroup>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>사용 여부</TableHead>
<TableCell className="border">
<FormField
control={form.control}
name="useYn"
render={({ field }) => (
<FormItem>
<FormControl>
<RadioGroup
{...field}
name="useYn"
onValueChange={field.onChange}
>
<div className="flex items-center space-x-2">
<RadioGroupItem value="Y" id="useY" />
<Label htmlFor="useY">사용</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="N" id="useN" />
<Label htmlFor="useN">사용안함</Label>
</div>
</RadioGroup>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</TableCell>
</TableRow>
</TableBody>
</Table>
</div>
</div>
<div className="flex justify-center gap-4 pb-12 pt-10">
<Button
size="lg"
color="white"
type="button"
onClick={() => router.back()}
>
목록
</Button>
<Button size="lg" type="submit">
저장
</Button>
{isModifyMode && (
<Button size="lg" color="red" type="button" onClick={onDelete}>
삭제
</Button>
)}
</div>
</form>
</Form>
<ConfirmDialog open={onConfirm} />
</>
);
}
export { SiteForm };
+46 -11
View File
@@ -3,38 +3,73 @@
import "@common/assets/styles/grid.css";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { getCoreRowModel, useReactTable } from "@tanstack/react-table";
import { Button, Input, DataTable } from "@common/components";
import { data, columns } from "../model/__mocks__";
import { Button, DataTable, Input } from "@common/components";
import { ENDPOINT } from "@/shared/config";
import { SiteApi } from "../api/site-service";
import { columns } from "../model/table-columns";
import { type ISite, type ISiteParams } from "../model/site-interface";
import { SitePageLayout } from "./layout";
function SitePage() {
const router = useRouter();
const { data: siteList, refetch } = useQuery({
queryKey: [ENDPOINT.CMS_SERVICE.SITES],
queryFn: () => SiteApi.getSiteList(siteQuery),
enabled: false,
});
const [siteQuery, setSiteQuery] = useState<ISiteParams>({
siteNm: "",
});
const table = useReactTable({
data,
data: siteList?.content ?? [],
columns,
getCoreRowModel: getCoreRowModel(),
});
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
refetch();
};
const handleRowClick = (row: ISite) => {
router.push(`/site/register/${row.siteId}`);
};
useEffect(() => {
refetch();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<SitePageLayout>
<div className="card card-border !mt-6">
<div className="card card-border !border-[#dbe2e6] !bg-[#eef7ff]">
<div className="flex items-center gap-2 p-2">
<label htmlFor="" className="mr-2 text-[#657481]">
<div className="card card-border">
<form onSubmit={handleSubmit} className="flex items-center gap-2 p-2">
<label htmlFor="" className="mr-2 text-label">
사이트명
</label>
<Input className="h-[3.2rem] w-[24rem] rounded-sm !text-[1.3rem]" />
<Button className="h-[3.2rem]">조회</Button>
</div>
<Input
className="h-[3.2rem] w-[24rem] rounded-sm !text-[1.3rem]"
value={siteQuery.siteNm}
onChange={(e) => setSiteQuery({ siteNm: e.target.value })}
/>
<Button className="h-[3.2rem]" type="submit">
조회
</Button>
</form>
</div>
<div className="card card-border">
<div className="card-header">
<h3 className="text-2xl font-medium text-[#666]">사이트 목록</h3>
<h3 className="text-2xl font-medium text-label">사이트 목록</h3>
<Button onClick={() => router.push("/site/register")}>등록</Button>
</div>
<div className="card !m-[1.2rem] h-[49rem] overflow-auto !p-0">
<DataTable table={table} />
<DataTable table={table} onRowClick={handleRowClick} />
</div>
</div>
</div>
+4 -3
View File
@@ -1,7 +1,8 @@
import { Client } from "@common/network";
import { SERVER_API_URL, SITE_ID } from "../config";
import { BASE_URL } from "../config/api";
import { SITE_ID } from "../config/env";
export const client = Client.getInstance({
baseURL: SERVER_API_URL as string,
siteId: SITE_ID as string,
baseURL: BASE_URL,
siteId: SITE_ID,
});
+11
View File
@@ -1,8 +1,19 @@
import { PROXY_HOST } from "./env";
export const BASE_URL = `${PROXY_HOST}/server`;
export const ENDPOINT = {
USER_SERVICE: {
LOGIN: "/user-service/login",
USERS: "/user-service/api/v1/users",
SILENT_REFRESH: "/user-service/api/v1/users/token/refresh",
},
CMS_SERVICE: {
SITES: "/cms-service/api/v1/sites",
CODE: "/cms-service/api/v1/code/cache",
IPS: "/cms-service/api/v1/site-ips",
DOMAINS: "/cms-service/api/v1/site-dmns",
},
};
export const JWT_EXPIRATION_TIME = 1800000;
+12 -6
View File
@@ -1,7 +1,13 @@
export const SERVER_API_URL = process.env.NEXT_PUBLIC_SERVER_API_URL;
export const SITE_ID = process.env.NEXT_PUBLIC_SITE_ID;
export const PORT = process.env.NEXT_PUBLIC_PORT || "3000";
export const PROXY_HOST =
process.env.NEXT_PUBLIC_PROXY_HOST || `http://localhost:${PORT}`;
export const CLAIM_NAME = process.env.CLAIM_NAME || "Authorization";
export const ACCESS_TOKEN = process.env.ACCESS_TOKEN || "access-token";
export const REFRESH_TOKEN = process.env.REFRESH_TOKEN || "refresh-token";
export const TOKEN_ID = process.env.TOKEN_ID || "token-id";
export const SERVER_API_URL = process.env.NEXT_PUBLIC_SERVER_API_URL;
export const SITE_ID = process.env.NEXT_PUBLIC_SITE_ID || "CS";
export const CLAIM_NAME = process.env.NEXT_PUBLIC_CLAIM_NAME || "Authorization";
export const ACCESS_TOKEN =
process.env.NEXT_PUBLIC_ACCESS_TOKEN || "access-token";
export const REFRESH_TOKEN =
process.env.NEXT_PUBLIC_REFRESH_TOKEN || "refresh-token";
export const AUTH_USER_ID = process.env.NEXT_PUBLIC_AUTH_USER_ID || "token-id";
+29
View File
@@ -0,0 +1,29 @@
import Cookies from "js-cookie";
export function getCookie(name: string): string | undefined {
if (typeof window === "undefined") {
return undefined;
}
return Cookies.get(name);
}
export function setCookie(
name: string,
value: string,
options?: Cookies.CookieAttributes,
): void {
if (typeof window === "undefined") {
return;
}
Cookies.set(name, value, options);
}
export function removeCookie(
name: string,
options?: Cookies.CookieAttributes,
): void {
if (typeof window === "undefined") {
return;
}
Cookies.remove(name, options);
}
+2
View File
@@ -0,0 +1,2 @@
export { getCookie, setCookie, removeCookie } from "./cookie";
export { useUserStore } from "./use-user-store";
+14
View File
@@ -0,0 +1,14 @@
import { useStore } from "zustand";
import { useContext } from "react";
import type { AlertStore } from "../store/alert-store";
import { StoreContext } from "../providers/store-provider";
export const useAlertStore = <T>(selector: (store: AlertStore) => T): T => {
const storeContext = useContext(StoreContext);
if (!storeContext) {
throw new Error("useAlertStore must be used within StoreProvider");
}
return useStore(storeContext.alertStore, selector);
};
+14
View File
@@ -0,0 +1,14 @@
import { useStore } from "zustand";
import { useContext } from "react";
import type { UserStore } from "../store/user-store";
import { StoreContext } from "../providers/store-provider";
export const useUserStore = <T>(selector: (store: UserStore) => T): T => {
const storeContext = useContext(StoreContext);
if (!storeContext) {
throw new Error("useUserStore must be used within StoreProvider");
}
return useStore(storeContext.userStore, selector);
};
+34
View File
@@ -0,0 +1,34 @@
interface SortConfig {
empty: boolean;
sorted: boolean;
unsorted: boolean;
}
interface PageableConfig {
sort: SortConfig;
offset: number;
pageNumber: number;
pageSize: number;
paged: boolean;
unpaged: boolean;
}
export interface PageableList<T> {
content: T;
pageable: PageableConfig;
sort: SortConfig;
totalPages: number;
totalElements: number;
number: number;
numberOfElements: number;
size: number;
first: boolean;
last: boolean;
empty: boolean;
}
export interface IPageableParams {
page?: number;
size?: number;
sort?: string[];
}
+1
View File
@@ -0,0 +1 @@
export * from "./api-interface";
+1
View File
@@ -0,0 +1 @@
export { StoreProvider } from "./store-provider";
@@ -0,0 +1,30 @@
"use client";
import { createContext, useRef } from "react";
import { createAlertStore } from "../store/alert-store";
import { createUserStore } from "../store/user-store";
type StoreContextType = {
alertStore: ReturnType<typeof createAlertStore>;
userStore: ReturnType<typeof createUserStore>;
};
export const StoreContext = createContext<StoreContextType | undefined>(
undefined,
);
export const StoreProvider = ({ children }: { children: React.ReactNode }) => {
const storeRef = useRef<StoreContextType | null>(null);
if (storeRef.current === null) {
storeRef.current = {
alertStore: createAlertStore(),
userStore: createUserStore(),
};
}
return (
<StoreContext.Provider value={storeRef.current}>
{children}
</StoreContext.Provider>
);
};
+25
View File
@@ -0,0 +1,25 @@
import { createStore } from "zustand/vanilla";
export type AlertState = {
message: string;
callback?: () => void;
};
export type AlertActions = {
setMessage: (message: string, callback?: () => void) => void;
};
export type AlertStore = AlertState & AlertActions;
export const defaultInitState: AlertState = {
message: "",
callback: undefined,
};
export const createAlertStore = (initState: AlertState = defaultInitState) => {
return createStore<AlertStore>()((set) => ({
...initState,
setMessage: (message: string, callback?: () => void) =>
set(() => ({ message, callback })),
}));
};
+1
View File
@@ -0,0 +1 @@
export { createUserStore, type IUserInfo } from "./user-store";
+56
View File
@@ -0,0 +1,56 @@
import { createStore } from "zustand/vanilla";
export interface IUserInfo {
regDt: string;
mdfcnDt: string;
rgtr: string;
mdfr: string;
userUnqId: string;
userId: string;
userName: string;
email: string;
encryptedPassword: string;
refreshToken: string;
userStateCode: string;
lastLoginDate: string;
loginFailCount: number;
pswdHnt: string;
pswdAns: string;
mphn: string;
telno: string;
zip: string;
addr: string;
daddr: string;
laeSeCd: string;
ogdpSeCd: string;
aprvYn: string;
autzrId: string;
expryYmd: string;
lastPswdChgDt: string;
googleId: string;
kakaoId: string;
naverId: string;
isSocialUser: boolean;
hasPassword: boolean;
}
export type UserState = {
userInfo: IUserInfo | null;
};
export type UserActions = {
setUserInfo: (userInfo: IUserInfo | null) => void;
};
export type UserStore = UserState & UserActions;
export const defaultInitState: UserState = {
userInfo: null,
};
export const createUserStore = (initState: UserState = defaultInitState) => {
return createStore<UserStore>()((set) => ({
...initState,
setUserInfo: (userInfo: IUserInfo | null) => set(() => ({ userInfo })),
}));
};
+32
View File
@@ -0,0 +1,32 @@
import {
Dialog,
DialogContent,
DialogFooter,
DialogClose,
Button,
} from "@common/components/ui";
import { useAlertStore } from "../lib/use-alert-store";
function AlertDialog() {
const { message, callback, setMessage } = useAlertStore((state) => state);
const handleOpenChange = () => {
setMessage("");
callback?.();
};
return (
<Dialog open={!!message} onOpenChange={handleOpenChange}>
<DialogContent aria-describedby={undefined}>
<div className="py-10">
<p className="text-center text-[1.4rem] text-foreground">{message}</p>
</div>
<DialogFooter className="!justify-center">
<DialogClose asChild>
<Button>확인</Button>
</DialogClose>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
export { AlertDialog };
+46
View File
@@ -0,0 +1,46 @@
import { useConfirm } from "@frontend-opensource/use-react-hooks";
import {
Dialog,
DialogContent,
DialogFooter,
DialogClose,
Button,
type ButtonProps,
} from "@common/components/ui";
type ConfirmDialogProps = {
open: boolean;
confirmButtonProps?: ButtonProps & { label?: string };
cancelButtonProps?: ButtonProps & { label?: string };
};
function ConfirmDialog({
open,
confirmButtonProps,
cancelButtonProps,
}: ConfirmDialogProps) {
const { message, onConfirm, onCancel } = useConfirm();
return (
<Dialog open={open} onOpenChange={onCancel}>
<DialogContent aria-describedby={undefined}>
<div className="py-10">
<p className="text-center text-[1.4rem] text-foreground">{message}</p>
</div>
<DialogFooter className="!justify-center">
<DialogClose asChild>
<Button onClick={onConfirm} {...confirmButtonProps}>
{confirmButtonProps?.label ?? "확인"}
</Button>
</DialogClose>
<DialogClose asChild>
<Button onClick={onCancel} color="white" {...cancelButtonProps}>
{cancelButtonProps?.label ?? "취소"}
</Button>
</DialogClose>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
export { ConfirmDialog };
+175
View File
@@ -0,0 +1,175 @@
import * as React from "react";
import * as LabelPrimitive from "@radix-ui/react-label";
import { Slot } from "@radix-ui/react-slot";
import {
Controller,
FormProvider,
useFormContext,
type ControllerProps,
type FieldPath,
type FieldValues,
} from "react-hook-form";
import { cn, Label } from "@common/components";
const Form = FormProvider;
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
> = {
name: TName;
};
const FormFieldContext = React.createContext<FormFieldContextValue>(
{} as FormFieldContextValue,
);
const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
>({
...props
}: ControllerProps<TFieldValues, TName>) => {
return (
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
);
};
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext);
const itemContext = React.useContext(FormItemContext);
const { getFieldState, formState } = useFormContext();
const fieldState = getFieldState(fieldContext.name, formState);
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>");
}
const { id } = itemContext;
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
};
};
type FormItemContextValue = {
id: string;
};
const FormItemContext = React.createContext<FormItemContextValue>(
{} as FormItemContextValue,
);
const FormItem = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const id = React.useId();
return (
<FormItemContext.Provider value={{ id }}>
<div ref={ref} className={cn("space-y-2", className)} {...props} />
</FormItemContext.Provider>
);
});
FormItem.displayName = "FormItem";
const FormLabel = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
>(({ className, ...props }, ref) => {
const { error, formItemId } = useFormField();
return (
<Label
ref={ref}
className={cn(error && "text-destructive", className)}
htmlFor={formItemId}
{...props}
/>
);
});
FormLabel.displayName = "FormLabel";
const FormControl = React.forwardRef<
React.ElementRef<typeof Slot>,
React.ComponentPropsWithoutRef<typeof Slot>
>(({ ...props }, ref) => {
const { error, formItemId, formDescriptionId, formMessageId } =
useFormField();
return (
<Slot
ref={ref}
id={formItemId}
aria-describedby={
!error
? `${formDescriptionId}`
: `${formDescriptionId} ${formMessageId}`
}
aria-invalid={!!error}
{...props}
/>
);
});
FormControl.displayName = "FormControl";
const FormDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => {
const { formDescriptionId } = useFormField();
return (
<p
ref={ref}
id={formDescriptionId}
className={cn("text-[0.8rem] text-muted-foreground", className)}
{...props}
/>
);
});
FormDescription.displayName = "FormDescription";
const FormMessage = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, children, ...props }, ref) => {
const { error, formMessageId } = useFormField();
const body = error ? String(error?.message ?? "") : children;
if (!body) {
return null;
}
return (
<p
ref={ref}
id={formMessageId}
className={cn("text-[1rem] font-medium text-destructive", className)}
{...props}
>
{body}
</p>
);
});
FormMessage.displayName = "FormMessage";
export {
useFormField,
Form,
FormItem,
FormLabel,
FormControl,
FormDescription,
FormMessage,
FormField,
};
-1
View File
@@ -4,7 +4,6 @@ import presetConfig from "../../tailwind.config.preset";
export default {
presets: [presetConfig],
darkMode: ["class", "[data-mode='dark']"],
content: [
"./src/**/*.{js,ts,jsx,tsx,mdx}",
"../../packages/common/components/src/ui/**/*.{js,ts,jsx,tsx,mdx}",
+4 -1
View File
@@ -12,14 +12,17 @@
"build": "turbo run build",
"dev": "turbo run dev",
"dev:cs": "turbo run dev --filter=cs",
"dev:wr": "turbo run dev --filter=wr",
"preview:components": "turbo run storybook --filter=@common/components",
"preinstall": "npx only-allow pnpm"
},
"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1"
"react-dom": "^18.3.1",
"zustand": "^5.0.3"
},
"devDependencies": {
"@types/node": "^22.13.9",
"@types/react": "^18.3.18",
"@types/react-dom": "^18.3.5",
"turbo": "2.4.2"
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

@@ -1,6 +1,10 @@
export const images = {
logo: require("./logo.png"),
menuBtn: require("./mob_menuBtn.svg"),
menuBtnClose: require("./mob_menuBtn_close.svg"),
iconFolderOff: require("./icon_folder_off.png"),
iconFolderOn: require("./icon_folder_on.png"),
iconFile: require("./icon_file.png"),
} as const;
export type ImageType = keyof typeof images;
+27 -1
View File
@@ -23,6 +23,7 @@
--border: #e5e5e5;
--input: #e5e5e5;
--label: #666666;
--placeholder: #a2a2a2;
--ring: #0a0a0a;
--chart-1: #2094fa;
--chart-2: #00dfe5;
@@ -31,8 +32,20 @@
--chart-5: #ff7865;
--chart-6: #e65db5;
--radius: 1rem;
--sidebar-background: 0 0% 98%;
--sidebar-foreground: 240 5.3% 26.1%;
--sidebar-primary: 240 5.9% 10%;
--sidebar-primary-foreground: 0 0% 98%;
--sidebar-accent: 240 4.8% 95.9%;
--sidebar-accent-foreground: 240 5.9% 10%;
--sidebar-border: 220 13% 91%;
--sidebar-ring: 217.2 91.2% 59.8%;
--field: #fff;
--form: #fff;
--container: #f1f6f9;
--title: #4c5e6f;
}
[data-mode="dark"] {
[data-theme="black"] {
--background: #0a0a0a;
--foreground: #fafafa;
--card: #0a0a0a;
@@ -52,6 +65,7 @@
--border: #262626;
--input: #262626;
--label: #f1f1f1;
--placeholder: #737373;
--ring: #d4d4d4;
--chart-1: #66b3ff;
--chart-2: #66f0f2;
@@ -60,5 +74,17 @@
--chart-5: #ffbcad;
--chart-6: #f4a0d3;
--radius: 1rem;
--sidebar-background: 240 5.9% 10%;
--sidebar-foreground: 240 4.8% 95.9%;
--sidebar-primary: 224.3 76.3% 48%;
--sidebar-primary-foreground: 0 0% 100%;
--sidebar-accent: 240 3.7% 15.9%;
--sidebar-accent-foreground: 240 4.8% 95.9%;
--sidebar-border: 240 3.7% 15.9%;
--sidebar-ring: 217.2 91.2% 59.8%;
--field: #5b6269;
--form: #1a1a1a;
--container: #0a0a0a;
--title: #fff;
}
}
@@ -0,0 +1,30 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
*storybook.log
storybook-static
.vercel
.env.production
@@ -0,0 +1,3 @@
{
"plugins": ["prettier-plugin-tailwindcss"]
}
@@ -0,0 +1,33 @@
## business_components 패키지
### 원앤올에서 제공받는 컴포넌트 외에 업무 파트에서 사용할 수 있는 별도 components 패키지지
&emsp; 1) 환경설정
&emsp; &emsp; (1) tsconfig.json 'path'에 '@common/business_components' 변수를 추가
```json
"paths": {
"@/*": ["./*"],
"@common/components/*": ["../../packages/common/components/src/*"],
"@common/components": ["../../packages/common/components/src/index"],
//아래에 해당하는 부분을 추가해줘야함.
"@common/business_components/*": ["../../packages/common/business_components/src/*"],
"@common/business_components": ["../../packages/common/business_components/src/index"]
}
```
&emsp; &emsp; (2) package.json 'dependencies'에 '@common/business_components' 추가
```json
"dependencies": {
"@common/business_components": "workspace:*",
"next": "15.1.7"
},
```
&emsp; &emsp; (3) tailwind.config.ts 추가
``` json
content: [
"./app/**/*.{js,ts,jsx,tsx,mdx}",
"../../packages/common/components/src/ui/**/*.{js,ts,jsx,tsx,mdx}",
//아래에 해당하는 부분을 추가해줘야함.
"../../packages/common/business_components/src/ui/**/*.{js,ts,jsx,tsx,mdx}",
],
```
@@ -0,0 +1,21 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "default",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "tailwind.config.js",
"css": "src/index.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}
@@ -0,0 +1,28 @@
import js from "@eslint/js";
import globals from "globals";
import reactHooks from "eslint-plugin-react-hooks";
import reactRefresh from "eslint-plugin-react-refresh";
import tseslint from "typescript-eslint";
export default tseslint.config(
{ ignores: ["dist"] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ["**/*.{ts,tsx}"],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
plugins: {
"react-hooks": reactHooks,
"react-refresh": reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
"react-refresh/only-export-components": [
"warn",
{ allowConstantExport: true },
],
},
}
);
@@ -0,0 +1,83 @@
{
"name": "@common/business_components",
"version": "0.0.0",
"private": true,
"sideEffects": false,
"type": "module",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.js"
}
},
"files": [
"dist/**"
],
"scripts": {
"build": "tsup",
"storybook": "storybook dev -p 6006",
"build:storybook": "storybook build",
"lint": "eslint .",
"clean": "rm -rf dist"
},
"dependencies": {
"@common/components": "workspace:*",
"@hookform/resolvers": "^4.1.3",
"@radix-ui/react-label": "^2.1.2",
"@radix-ui/react-scroll-area": "^1.2.3",
"@radix-ui/react-select": "^2.1.6",
"@radix-ui/react-slot": "^1.1.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"date-fns": "^3.6.0",
"lucide-react": "^0.474.0",
"path": "^0.12.7",
"react-day-picker": "^8.10.1",
"react-dropzone": "^14.3.8",
"react-hook-form": "^7.54.2",
"recharts": "^2.15.1",
"sonner": "^2.0.1",
"tailwind-merge": "^3.0.1",
"zod": "^3.24.2"
},
"devDependencies": {
"@eslint/js": "^9.17.0",
"@storybook/addon-essentials": "^8.5.3",
"@storybook/addon-interactions": "^8.5.3",
"@storybook/addon-onboarding": "^8.5.3",
"@storybook/addon-themes": "^8.5.4",
"@storybook/blocks": "^8.5.3",
"@storybook/manager-api": "^8.5.5",
"@storybook/react": "^8.5.3",
"@storybook/react-vite": "^8.5.3",
"@storybook/test": "^8.5.3",
"@storybook/theming": "^8.5.5",
"@vitejs/plugin-react": "^4.3.4",
"autoprefixer": "^10.4.20",
"eslint": "^9.17.0",
"eslint-plugin-react-hooks": "^5.0.0",
"eslint-plugin-react-refresh": "^0.4.16",
"eslint-plugin-storybook": "^0.11.2",
"globals": "^15.14.0",
"postcss": "^8.5.1",
"prettier": "^3.4.2",
"prettier-plugin-tailwindcss": "^0.6.11",
"storybook": "^8.5.3",
"tailwindcss": "^3.4.17",
"tsup": "8.3.6",
"typescript": "~5.6.2",
"typescript-eslint": "^8.18.2",
"vite": "^6.0.5",
"vite-tsconfig-paths": "5.1.4"
},
"eslintConfig": {
"extends": [
"plugin:storybook/recommended"
]
},
"packageManager": "pnpm@8.15.5+sha1.a58c038faac410c947dbdb93eb30994037d0fce2"
}
@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
@@ -0,0 +1,73 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--background: #ffffff;
--foreground: #0a0a0a;
--card: #ffffff;
--card-foreground: #0a0a0a;
--popover: #ffffff;
--popover-foreground: #0a0a0a;
--primary: #2094fa;
--primary-foreground: #fafafa;
--secondary: #f5f5f5;
--secondary-foreground: #0f1e33;
--muted: #f5f5f5;
--muted-foreground: #737373;
--accent: #f5f5f5;
--accent-foreground: #0f1e33;
--destructive: #ff4141;
--destructive-foreground: #fafafa;
--border: #e5e5e5;
--input: #e5e5e5;
--label: #666666;
--ring: #0a0a0a;
--chart-1: #d95b43;
--chart-2: #299392;
--chart-3: #263e4d;
--chart-4: #dfb938;
--chart-5: #f08634;
--radius: 1rem;
}
[data-mode="dark"] {
--background: #0a0a0a;
--foreground: #fafafa;
--card: #0a0a0a;
--card-foreground: #fafafa;
--popover: #0a0a0a;
--popover-foreground: #fafafa;
--primary: #2094fa;
--primary-foreground: #171717;
--secondary: #262626;
--secondary-foreground: #fafafa;
--muted: #262626;
--muted-foreground: #a2a2a2;
--accent: #262626;
--accent-foreground: #fafafa;
--destructive: #b22222;
--destructive-foreground: #fafafa;
--border: #262626;
--input: #262626;
--label: #f1f1f1;
--ring: #d4d4d4;
--chart-1: #3399ff;
--chart-2: #339966;
--chart-3: #ff9933;
--chart-4: #cc66ff;
--chart-5: #ff3399;
}
}
@layer base {
* {
@apply border-border;
}
html {
@apply text-[10px];
}
body {
@apply bg-background text-foreground;
}
}
@@ -0,0 +1,54 @@
## Chart 모듈
### 공통 모듈 중 Chart를 다양한 테마로 적용시킬 수 있도록 해주는 모듈
&emsp; 1. 차트 모듈 사용법
&emsp; &emsp; 1-1) 호출방법
&emsp; &emsp; &emsp; (1) 파일에 차트생성에 필요한 form, MainChart, MainConfig 임폴트
```js
import {type ChartConfig, MainChart, CHART_FORM } from "@common/business_components";
```
&emsp; &emsp; &emsp; (2) ChartForm 지정
```js
/**
* CHART_FORM.BAR : Bar차트
* CHART_FORM.LINE : Line차트
* DN : Daughnut차트
**/
const chartForm = CHART_FORM.BAR;
```
&emsp; &emsp; &emsp; (3) chartData 정의
``` js
/**
* label : 차트항목 / val : 데이터값
**/
const chartData = [
{ label: "January", val: 186},
{ label: "March", val: 237},
{ label: "February", val: 305},
{ label: "April", val: 73},
{ label: "May", val: 209},
{ label: "June", val: 214},
]
```
&emsp; &emsp; &emsp; (4) Chart생성에 필요한 chartConfig 정의
``` js
/**
* 차트 Config
*/
const chartConfig = chartData.reduce((config,>>element) => {
label: element.label,
config[element.label] = {
color : "hsl(var(--chart-1))"
};
return config;
}, {} as Record<string, { label: string; color: string; }>) satisfies ChartConfig;
```
&emsp; &emsp; &emsp; (5) Chart 객체 생성
```html
return (
<div>
<MainChart chartConfig={chartConfig} chartForm={chartForm} chartData={chartData}></MainChart>
</div>
);
```
File diff suppressed because it is too large Load Diff
@@ -0,0 +1 @@
export const BASE_ASSETS_PATH = process.env.BASE_ASSETS_PATH ?? "/assets";
@@ -0,0 +1,93 @@
## form 모듈
### 공통 모듈 중 chart를 다양한 테마로 적용시킬 수 있도록 해주는 모듈
&emsp; 1. 폼 모듈 사용법
&emsp; &emsp; 1-1) 패키지 사용법
&emsp; &emsp; &emsp; (1) zod 사용법
https://zod.dev/?id=introduction
&emsp; &emsp; 1-2) 호출방법
&emsp; &emsp; &emsp; (1) form에 필요한 Form,FormField,useForm useForm,z, zodResolver import
```js
import {
Form,
FormField,
SelectBox,
} from "@common/business_components/ui";
import { Input } from "@common/components/ui";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { FormUi } from "@common/business_components";
```
&emsp; &emsp; &emsp; (2)zod 정의
```js
const formSchema = z.object({
facilityName: z.string().min(2).max(50),
instlCmptnDt:z.string(), // FormField 내 name의 타입및 min max 구성 가능
});
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
//초기값 세팅 z.object에 등록한 값은 반드시 세팅해야함.
defaultValues: {
facilityName :'',
instlCmptnDt:'', //
},
});
function onSubmit(values: z.infer<typeof formSchema>) {
// form submit 함수
console.log(values);// zod.object에 등록하고 form에 구현한 값이 출력됨.
}
```
&emsp; &emsp; &emsp; (3) form구성
```js
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
<div className="col-span-3 pl-6" >
<FormField
control={form.control}
name="grntchCstSprtYn" //zodobject에 등록한 값 삽입
render={({ field }) => (
// zod에 등록된 name 값의 폼 객체 생성
//select box 삽입시
<FormUi label="인증여부">
<SelectBox className={""} selectClass={selectClass} label={""} selectArray={rain.selectYN} onSelectValue={onSelectValue} {...field}/>
</FormUi>
)}
/>
</div>
<div className="col-span-3" >
<FormField
control={form.control}
name="grntchBdstCertYr"
render={({ field }) => (
// zod에 등록된 name 값의 폼 객체 생성
//input 삽입시
<FormUi label="인증년도">
<Input className="" placeholder="2024" type="" {...field} />
</FormUi>
)}
/>
</div>
</form>
</Form>
```
@@ -0,0 +1,11 @@
@layer base {}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
}
@@ -0,0 +1 @@
export * from "./ui";
@@ -0,0 +1,6 @@
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
@@ -0,0 +1,42 @@
"use client"
import type { CSSProperties } from "react";
import {
Card,
CardContent
} from "./lib/card";
import {
ChartContainer,
ChartTooltip,
ChartTooltipContent,
type ChartConfig
} from "./lib/chart";
import { Bar, BarChart, CartesianGrid, XAxis } from "recharts";
export default function Chart(props: { chartConfig: ChartConfig; chartData: any[] | undefined; chartTitle: string}) {
return (
<Card className="h-full">
<CardContent className="h-full">
{props.chartTitle && props.chartTitle !== "" && props.chartTitle !== "undefined" ? (
<div style={{ textAlign: "left", fontSize: "13px", fontWeight: "bold", marginTop:"13px", marginBottom: "10px" }}>
{props.chartTitle}
</div>): null}
<div className="h-[calc(100%-42px)] flex justify-center">
<ChartContainer config={props.chartConfig} className="h-full w-full">
<BarChart accessibilityLayer data={props.chartData} className="h-full">
<CartesianGrid vertical={false} />
<XAxis
dataKey="label"
tickLine={false}
tickMargin={10}
axisLine={false}
tickFormatter={(value) => value.slice(0, 3)}
/>
<ChartTooltip cursor={false} content={<ChartTooltipContent indicator="dashed" />}/>
<Bar dataKey="val" radius={10} />
</BarChart>
</ChartContainer>
</div>
</CardContent>
</Card>
)
}
@@ -0,0 +1,47 @@
"use client"
import { Pie, PieChart } from "recharts";
import {
Card,
CardContent
} from "./lib/card";
import {
ChartContainer,
ChartTooltip,
ChartTooltipContent,
type ChartConfig
} from "./lib/chart";
// eslint-disable-next-line react-refresh/only-export-components
export default (props: { chartConfig: ChartConfig; chartData: never[] | undefined; chartTitle:string}) =>{
return (
<Card className="flex flex-col">
<CardContent className="flex-1 pb-0">
{props.chartTitle && props.chartTitle !== "" && props.chartTitle !== "undefined" ? (
<div style={{ textAlign: "left", fontSize: "13px", fontWeight: "bold", marginTop:"13px", marginBottom: "10px" }}>
{props.chartTitle}
</div>): null}
<div className="h-[calc(100%-42px)] justify-center">
<ChartContainer
config={props.chartConfig}
className="mx-auto aspect-square max-h-[300px]"
>
<PieChart>
<ChartTooltip
cursor={false}
content={<ChartTooltipContent hideLabel />}
/>
<Pie
data={props.chartData}
dataKey="val"
nameKey="label"
innerRadius={60}
/>
</PieChart>
</ChartContainer>
</div>
</CardContent>
</Card>
)
}
@@ -0,0 +1,108 @@
"use client"
import type { CSSProperties } from "react";
import { Bar, CartesianGrid, ComposedChart, Legend, Line, Tooltip, XAxis, YAxis } from "recharts";
import {
Card,
CardContent
} from "./lib/card";
import {
ChartContainer,
type ChartConfig
} from "./lib/chart";
import React from "react";
// 툴팁 커스텀 css
/** 차트 기본 스타일 */
const styles = {
tooltipDiv: {
borderRadius: "5px",
backgroundColor: "white",
padding: "10px",
boxShadow: "0px 2px 10px rgba(0,0,0,0.2)",
width: "180px", // 적절한 크기로 설정
} as React.CSSProperties,
tooltipLabel: {
fontWeight: "bold",
fontSize: "12px",
marginBottom: "5px",
borderBottom: "1px solid #ddd",
paddingBottom: "3px",
} as React.CSSProperties,
tooltipText: {
fontSize: "11px",
fontWeight:"bold",
} as React.CSSProperties,
legendContainer: {
display: "flex",
justifyContent: "center",
gap: "20px",
fontSize: "9px",
fontWeight : "bold",
marginTop: "10px",
} as CSSProperties,
};
// 커스텀 툴팁
const CustomTooltip = ({ active, payload, label }) => {
if (active && payload && payload.length) {
return (
<div style={styles.tooltipDiv}>
<p style={styles.tooltipLabel}>{label}</p>
{payload.map((item, index) => (
<div key={index} style={{ marginTop: "10px", display: "flex", alignItems: "center", gap: "8px" }}>
{/* 색상 박스 추가 (범례 색상과 동일) */}
<div style={{ width: "10px", height: "10px", backgroundColor: item.color, borderRadius: "50%" }}></div>
<span style={styles.tooltipText}>{`${item.name}: ${item.value}`}</span>
</div>
))}
</div>
);
}
return null;
};
// 커스텀 범례 (글씨 크기 키우기 + 스타일 추가)
const CustomLegend = (props: any) => {
const { payload } = props;
return (
<div style={styles.legendContainer}>
{payload.map((entry, index) => (
<div key={`legend-${index}`} style={{ display: "flex", alignItems: "center", gap: "8px" }}>
<div style={{ width: "12px", height: "12px", backgroundColor: entry.color, borderRadius: "50%" }}></div>
<span>{entry.value}</span>
</div>
))}
</div>
);
};
export default function LineBarchart(props: { chartConfig: ChartConfig; chartData: any[] | undefined; chartTitle:string }) {
return (
<Card className="h-full">
<CardContent className="h-full">
{props.chartTitle && props.chartTitle !== "" && props.chartTitle !== "undefined" ? (
<div style={{ textAlign: "left", fontSize: "13px", fontWeight: "bold", marginTop:"13px", marginBottom: "10px" }}>
{props.chartTitle}
</div>): null}
<div className="h-[calc(100%-42px)] flex justify-center">
<ChartContainer config={props.chartConfig} className="h-full w-full" >
<ComposedChart data={props.chartData} className="h-full ">
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="label" fontSize="8px" fontWeight="bold"/>
{/* 왼쪽 Y축: lineVal (정상) */}
<YAxis yAxisId="left" orientation="left" />
{/* 오른쪽 Y축: barVal (위에서 아래로 반전) */}
<YAxis yAxisId="right" orientation="right" reversed />
<Tooltip content={<CustomTooltip active={undefined} payload={undefined} label={undefined} />} />
<Legend content={CustomLegend}/>
{/* 바 차트 (오른쪽 Y축 사용, 위에서 아래로) */}
<Bar yAxisId="right" dataKey="barVal" fill="#8884d8" name="강수량(mm/일)"/>
{/* 라인 차트 (왼쪽 Y축 사용) */}
<Line yAxisId="left" type="monotone" dataKey="lineVal" stroke="orange" strokeWidth={2} dot={{r: 0}} name="BOD(mg/L)"/>
</ComposedChart>
</ChartContainer>
</div>
</CardContent>
</Card>
)
}
@@ -0,0 +1,121 @@
"use client"
import type { CSSProperties } from "react";
import {
Card,
CardContent
} from "./lib/card";
import {
ChartContainer,
ChartTooltip,
ChartTooltipContent,
type ChartConfig
} from "./lib/chart";
import { CartesianGrid, Legend, Line, LineChart, Tooltip, XAxis, YAxis } from "recharts";
/** 차트 기본 스타일 */
const styles = {
tooltipDiv: {
borderRadius: "5px",
backgroundColor: "white",
padding: "10px",
boxShadow: "0px 2px 10px rgba(0,0,0,0.2)",
width: "180px", // 적절한 크기로 설정
} as React.CSSProperties,
tooltipLabel: {
fontWeight: "bold",
fontSize: "12px",
marginBottom: "5px",
borderBottom: "1px solid #ddd",
paddingBottom: "3px",
} as React.CSSProperties,
tooltipText: {
fontSize: "11px",
fontWeight:"bold",
} as React.CSSProperties,
legendContainer: {
display: "flex",
justifyContent: "center",
gap: "20px",
fontSize: "9px",
fontWeight : "bold",
marginTop: "10px",
} as CSSProperties,
};
// 커스텀 툴팁
const CustomTooltip = ({ active, payload, label }) => {
if (active && payload && payload.length) {
return (
<div style={styles.tooltipDiv}>
<p style={styles.tooltipLabel}>{label}</p>
{payload.map((item, index) => (
<div key={index} style={{ marginTop: "10px", display: "flex", alignItems: "center", gap: "8px" }}>
{/* 색상 박스 추가 (범례 색상과 동일) */}
<div style={{ width: "10px", height: "10px", backgroundColor: item.color, borderRadius: "50%" }}></div>
<span style={styles.tooltipText}>{`${item.name}: ${item.value}`}</span>
</div>
))}
</div>
);
}
return null;
};
// 커스텀 범례 (글씨 크기 키우기 + 스타일 추가)
const CustomLegend = (props: any) => {
const { payload } = props;
return (
<div style={styles.legendContainer}>
{payload.map((entry, index) => (
<div key={`legend-${index}`} style={{ display: "flex", alignItems: "center", gap: "8px" }}>
<div style={{ width: "12px", height: "12px", backgroundColor: entry.color, borderRadius: "50%" }}></div>
<span>{entry.value}</span>
</div>
))}
</div>
);
};
type DataType = {label : string; val:number};
type ChartDataType = {
chartData1: DataType[];
chartData2: DataType[];
};
export default function Linechart(props: { chartConfig: ChartConfig; chartData: ChartDataType; chartTitle:string}) {
const mergedData = Object.values(props.chartData).reduce((acc, dataset) => {
dataset.forEach((entry, index) => {
if (!acc[index]) {
acc[index] = { label: entry.label }; // label 추가
}
const key = Object.keys(props.chartData).find(k => props.chartData[k] === dataset);
if (key) acc[index][key] = entry.val;
});
return acc;
}, [] as any[]);
return (
<Card className="h-full">
<CardContent className="h-full">
{props.chartTitle && props.chartTitle !== "" && props.chartTitle !== "undefined" ? (
<div style={{ textAlign: "left", fontSize: "13px", fontWeight: "bold", marginTop:"13px", marginBottom: "10px" }}>
{props.chartTitle}
</div>): null}
<div className="h-[calc(100%-42px)] flex justify-center">
<ChartContainer config={props.chartConfig} className="h-full w-full">
<LineChart data={mergedData} className="h-full">
<CartesianGrid vertical={false} />
<XAxis dataKey="label" fontSize="8px" fontWeight="bold"/>
<YAxis yAxisId="left" orientation="left" />
<Tooltip content={<CustomTooltip active={undefined} payload={undefined} label={undefined} />} />
<Legend content={CustomLegend}/>
{Object.keys(props.chartData).map((key, index) => (
<Line key={key} yAxisId="left" dataKey={key} type="linear" strokeWidth={2} dot={false} name={key} />
))}
</LineChart>
</ChartContainer>
</div>
</CardContent>
</Card>
)
}
@@ -0,0 +1,48 @@
import React from 'react';
import BarChart from './BarChart';
import DoughnutChart from './DoughnutChart';
import { type ChartConfig } from './lib/chart';
import LineChart from './LineChart';
import LineBarchart from './LineBarChart';
/**차트 FORM */
const CHART_FORM = {
/**바 차트 형태*/
BAR : 'bar',
/**라인 차트 형태*/
LINE:'line',
/**도넛 차트 형태*/
DN :'daughnut',
/**LINE,BAR차트 */
LINEBAR : 'linebar'
};
function MainChart(props: { chartForm: string; chartConfig: any; chartData: any; chartTitle:string; }) {
if( props.chartForm == CHART_FORM.BAR ){
return (
<BarChart chartConfig={props.chartConfig} chartData={props.chartData} chartTitle={props.chartTitle}>
</BarChart>
);
} else if( props.chartForm == CHART_FORM.LINE ){
return (
<LineChart chartConfig={props.chartConfig} chartData={props.chartData} chartTitle={props.chartTitle}>
</LineChart>
);
} else if( props.chartForm == CHART_FORM.DN ){
return (
<DoughnutChart chartConfig={props.chartConfig} chartData={props.chartData} chartTitle={props.chartTitle}>
</DoughnutChart>
);
} else if (props.chartForm == CHART_FORM.LINEBAR){
return (
<LineBarchart chartConfig={props.chartConfig} chartData={props.chartData} chartTitle={props.chartTitle}>
</LineBarchart>
);
}
}
export { MainChart };
// eslint-disable-next-line react-refresh/only-export-components
export { CHART_FORM };
export type { ChartConfig };
@@ -0,0 +1,77 @@
import * as React from "react"
import { cn } from "../../../lib/utils"
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"rounded-xl border bg-card text-card-foreground shadow",
className
)}
{...props}
/>
))
Card.displayName = "Card"
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
))
CardHeader.displayName = "CardHeader"
const CardTitle = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("font-semibold leading-none tracking-tight", className)}
{...props}
/>
))
CardTitle.displayName = "CardTitle"
const CardDescription = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
CardDescription.displayName = "CardDescription"
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
))
CardContent.displayName = "CardContent"
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
))
CardFooter.displayName = "CardFooter"
export { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle }
@@ -0,0 +1,364 @@
"use client"
import * as React from "react"
import * as RechartsPrimitive from "recharts"
import { cn } from "../../../lib/utils"
// Format: { THEME_NAME: CSS_SELECTOR }
const THEMES = { light: "", dark: ".dark" } as const
export type ChartConfig = {
[k in string]: {
label?: React.ReactNode
icon?: React.ComponentType
} & (
| { color?: string; theme?: never }
| { color?: never; theme: Record<keyof typeof THEMES, string> }
)
}
type ChartContextProps = {
config: ChartConfig
}
const ChartContext = React.createContext<ChartContextProps | null>(null)
function useChart() {
const context = React.useContext(ChartContext)
if (!context) {
throw new Error("useChart must be used within a <ChartContainer />")
}
return context
}
const ChartContainer = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> & {
config: ChartConfig
children: React.ComponentProps<
typeof RechartsPrimitive.ResponsiveContainer
>["children"]
}
>(({ id, className, children, config, ...props }, ref) => {
const uniqueId = React.useId()
const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`
return (
<ChartContext.Provider value={{ config }}>
<div
data-chart={chartId}
ref={ref}
className={cn(
"flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-none [&_.recharts-surface]:outline-none",
className
)}
{...props}
>
<ChartStyle id={chartId} config={config} />
<RechartsPrimitive.ResponsiveContainer>
{children}
</RechartsPrimitive.ResponsiveContainer>
</div>
</ChartContext.Provider>
)
})
ChartContainer.displayName = "Chart"
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
const colorConfig = Object.entries(config).filter(
([, config]) => config.theme || config.color
)
if (!colorConfig.length) {
return null
}
return (
<style
dangerouslySetInnerHTML={{
__html: Object.entries(THEMES)
.map(
([theme, prefix]) => `
${prefix} [data-chart=${id}] {
${colorConfig
.map(([key, itemConfig]) => {
const color =
itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ||
itemConfig.color
return color ? ` --color-${key}: ${color};` : null
})
.join("\n")}
}
`
)
.join("\n"),
}}
/>
)
}
const ChartTooltip = RechartsPrimitive.Tooltip
const ChartTooltipContent = React.forwardRef<
HTMLDivElement,
React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
React.ComponentProps<"div"> & {
hideLabel?: boolean
hideIndicator?: boolean
indicator?: "line" | "dot" | "dashed"
nameKey?: string
labelKey?: string
}
>(
(
{
active,
payload,
className,
indicator = "dot",
hideLabel = false,
hideIndicator = false,
label,
labelFormatter,
labelClassName,
formatter,
color,
nameKey,
labelKey,
},
ref
) => {
const { config } = useChart()
const tooltipLabel = React.useMemo(() => {
if (hideLabel || !payload?.length) {
return null
}
const [item] = payload
const key = `${labelKey || "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const value =
!labelKey && typeof label === "string"
? config[label as keyof typeof config]?.label || label
: itemConfig?.label
if (labelFormatter) {
return (
<div className={cn("font-medium", labelClassName)}>
{labelFormatter(value, payload)}
</div>
)
}
if (!value) {
return null
}
return <div className={cn("font-medium", labelClassName)}>{value}</div>
}, [
label,
labelFormatter,
payload,
hideLabel,
labelClassName,
config,
labelKey,
])
if (!active || !payload?.length) {
return null
}
const nestLabel = payload.length === 1 && indicator !== "dot"
return (
<div
ref={ref}
className={cn(
"grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",
className
)}
>
{!nestLabel ? tooltipLabel : null}
<div className="grid gap-1.5">
{payload.map((item, index) => {
const key = `${nameKey || item.name || item.dataKey || "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const indicatorColor = color || item.payload.fill || item.color
return (
<div
key={item.dataKey}
className={cn(
"flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",
indicator === "dot" && "items-center"
)}
>
{formatter && item?.value !== undefined && item.name ? (
formatter(item.value, item.name, item, index, item.payload)
) : (
<>
{itemConfig?.icon ? (
<itemConfig.icon />
) : (
!hideIndicator && (
<div
className={cn(
"shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",
{
"h-2.5 w-2.5": indicator === "dot",
"w-1": indicator === "line",
"w-0 border-[1.5px] border-dashed bg-transparent":
indicator === "dashed",
"my-0.5": nestLabel && indicator === "dashed",
}
)}
style={
{
"--color-bg": indicatorColor,
"--color-border": indicatorColor,
} as React.CSSProperties
}
/>
)
)}
<div
className={cn(
"flex flex-1 justify-between leading-none",
nestLabel ? "items-end" : "items-center"
)}
>
<div className="grid gap-1.5">
{nestLabel ? tooltipLabel : null}
<span className="text-muted-foreground">
{itemConfig?.label || item.name}
</span>
</div>
{item.value && (
<span className="font-mono font-medium tabular-nums text-foreground">
{item.value.toLocaleString()}
</span>
)}
</div>
</>
)}
</div>
)
})}
</div>
</div>
)
}
)
ChartTooltipContent.displayName = "ChartTooltip"
const ChartLegend = RechartsPrimitive.Legend
const ChartLegendContent = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> &
Pick<RechartsPrimitive.LegendProps, "payload" | "verticalAlign"> & {
hideIcon?: boolean
nameKey?: string
}
>(
(
{ className, hideIcon = false, payload, verticalAlign = "bottom", nameKey },
ref
) => {
const { config } = useChart()
if (!payload?.length) {
return null
}
return (
<div
ref={ref}
className={cn(
"flex items-center justify-center gap-4",
verticalAlign === "top" ? "pb-3" : "pt-3",
className
)}
>
{payload.map((item) => {
const key = `${nameKey || item.dataKey || "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
return (
<div
key={item.value}
className={cn(
"flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"
)}
>
{itemConfig?.icon && !hideIcon ? (
<itemConfig.icon />
) : (
<div
className="h-2 w-2 shrink-0 rounded-[2px]"
style={{
backgroundColor: item.color,
}}
/>
)}
{itemConfig?.label}
</div>
)
})}
</div>
)
}
)
ChartLegendContent.displayName = "ChartLegend"
// Helper to extract item config from a payload.
function getPayloadConfigFromPayload(
config: ChartConfig,
payload: unknown,
key: string
) {
if (typeof payload !== "object" || payload === null) {
return undefined
}
const payloadPayload =
"payload" in payload &&
typeof payload.payload === "object" &&
payload.payload !== null
? payload.payload
: undefined
let configLabelKey: string = key
if (
key in payload &&
typeof payload[key as keyof typeof payload] === "string"
) {
configLabelKey = payload[key as keyof typeof payload] as string
} else if (
payloadPayload &&
key in payloadPayload &&
typeof payloadPayload[key as keyof typeof payloadPayload] === "string"
) {
configLabelKey = payloadPayload[
key as keyof typeof payloadPayload
] as string
}
return configLabelKey in config
? config[configLabelKey]
: config[key as keyof typeof config]
}
export {
ChartContainer, ChartLegend,
ChartLegendContent,
ChartStyle, ChartTooltip,
ChartTooltipContent
}
@@ -0,0 +1,7 @@
@tailwind components;
@layer components {
.date-picker-trigger {
@apply h-[3rem] w-[12rem] justify-between border-input !bg-background px-4 py-2 text-left text-[1.3rem] font-normal leading-none text-muted-foreground hover:!bg-accent;
}
}
@@ -0,0 +1,48 @@
"use client";
import "./date-picker.css";
import { format } from "date-fns";
import { CalendarIcon } from "lucide-react";
import type { DayPickerSingleProps } from "react-day-picker";
import { Button, Calendar, Popover, PopoverContent, PopoverTrigger } from "@common/components/ui";
import { cn } from "../../lib/utils";
import { FormControl } from "../form";
type DatePickerProps = DayPickerSingleProps & { field: { value: Date; onChange: (date: Date | undefined) => void } ,selectClass:string|undefined };
export function DatePicker({ field, selectClass }: DatePickerProps) {
return (
<Popover>
<PopoverTrigger asChild>
<FormControl>
<Button
color="white"
variant={"outline"}
className={!selectClass? cn(
"w-[240px] pl-3 text-left font-normal",
!field?.value && "text-muted-foreground",
):selectClass}
>
{field?.value ? (
format(field?.value, "PPP")
) : (
<span>Pick a date</span>
)}
<CalendarIcon className="h-4" />
</Button>
</FormControl>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
mode="single"
selected={field?.value}
onSelect={field?.onChange}
initialFocus
/>
</PopoverContent>
</Popover>
);
}
@@ -0,0 +1,46 @@
"use client";
import { CloudUpload, Paperclip } from "lucide-react";
import { FileInput, FileUploader, FileUploaderContent, FileUploaderItem } from "./lib/file_upload";
const dropZoneConfig = {
maxFiles: 5,
maxSize: 1024 * 1024 * 4,
multiple: true,
};
export const FileUpload =
(({ ...props }) => {
return (
<FileUploader
value={props.files}
onValueChange={props.setFiles}
dropzoneOptions={dropZoneConfig}
acceptName={props?.fileTypes}
className="relative bg-background rounded-lg p-2"
>
<FileInput
id="fileInput"
className="outline-dashed outline-1 outline-slate-500"
>
<div className="flex items-center justify-center flex-col p-8 w-full ">
<CloudUpload className='text-gray-500 w-10 h-10' />
<p className="mb-1 text-sm text-gray-500 dark:text-gray-400">
<span className="font-semibold">Click to upload</span>
&nbsp; or drag and drop
</p>
<p className="text-xs text-gray-500 dark:text-gray-400">
{!props?.fileTypes?"SVG, PNG, JPG, GIF":props?.fileTypes}
</p>
</div>
</FileInput>
<FileUploaderContent>
{props.files &&
props.files.length > 0 &&
props.files.map((file:File, i:number) => (
<FileUploaderItem key={i} index={i}>
<Paperclip className="h-4 w-4 stroke-current" />
<span>{file.name}</span>
</FileUploaderItem>
))}
</FileUploaderContent>
</FileUploader>
)
})
@@ -0,0 +1,364 @@
"use client";
import { Input, buttonVariants } from "@common/components";
import { Trash2 as RemoveIcon } from "lucide-react";
import {
type Dispatch,
type SetStateAction,
createContext,
forwardRef,
useCallback,
useContext,
useEffect,
useRef,
useState,
} from "react";
import {
type DropzoneOptions,
type DropzoneState,
type FileRejection,
useDropzone,
} from "react-dropzone";
import { toast } from "sonner";
import { cn } from "../../../lib/utils";
type DirectionOptions = "rtl" | "ltr" | undefined;
type FileUploaderContextType = {
dropzoneState: DropzoneState;
isLOF: boolean;
isFileTooBig: boolean;
removeFileFromSet: (index: number) => void;
activeIndex: number;
setActiveIndex: Dispatch<SetStateAction<number>>;
orientation: "horizontal" | "vertical";
direction: DirectionOptions;
};
const FileUploaderContext = createContext<FileUploaderContextType | null>(null);
export const useFileUpload = () => {
const context = useContext(FileUploaderContext);
if (!context) {
throw new Error("useFileUpload must be used within a FileUploaderProvider");
}
return context;
};
type FileUploaderProps = {
value: File[] | null;
reSelect?: boolean;
onValueChange: (value: File[] | null) => void;
dropzoneOptions: DropzoneOptions;
orientation?: "horizontal" | "vertical";
};
/**
* File upload Docs: {@link: https://localhost:3000/docs/file-upload}
*/
export const FileUploader = forwardRef<
HTMLDivElement,
FileUploaderProps & React.HTMLAttributes<HTMLDivElement> & {acceptName?: string|undefined}
>(
(
{
className,
dropzoneOptions,
value,
onValueChange,
reSelect,
orientation = "vertical",
children,
dir,
acceptName,
...props
},
ref,
) => {
const [isFileTooBig, setIsFileTooBig] = useState(false);
const [isLOF, setIsLOF] = useState(false);
const [activeIndex, setActiveIndex] = useState(-1);
const {
accept = {
"image/*": acceptName?acceptName.split(",").map(extend=>("."+extend)):[".jpg", ".jpeg", ".png", ".gif"],
},
maxFiles = 1,
maxSize = 4 * 1024 * 1024,
multiple = true,
} = dropzoneOptions;
const reSelectAll = maxFiles === 1 ? true : reSelect;
const direction: DirectionOptions = dir === "rtl" ? "rtl" : "ltr";
const removeFileFromSet = useCallback(
(i: number) => {
if (!value) return;
const newFiles = value.filter((_, index) => index !== i);
onValueChange(newFiles);
},
[value, onValueChange],
);
const handleKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLDivElement>) => {
e.preventDefault();
e.stopPropagation();
if (!value) return;
const moveNext = () => {
const nextIndex = activeIndex + 1;
setActiveIndex(nextIndex > value.length - 1 ? 0 : nextIndex);
};
const movePrev = () => {
const nextIndex = activeIndex - 1;
setActiveIndex(nextIndex < 0 ? value.length - 1 : nextIndex);
};
const prevKey =
orientation === "horizontal"
? direction === "ltr"
? "ArrowLeft"
: "ArrowRight"
: "ArrowUp";
const nextKey =
orientation === "horizontal"
? direction === "ltr"
? "ArrowRight"
: "ArrowLeft"
: "ArrowDown";
if (e.key === nextKey) {
moveNext();
} else if (e.key === prevKey) {
movePrev();
} else if (e.key === "Enter" || e.key === "Space") {
if (activeIndex === -1) {
dropzoneState.inputRef.current?.click();
}
} else if (e.key === "Delete" || e.key === "Backspace") {
if (activeIndex !== -1) {
removeFileFromSet(activeIndex);
if (value.length - 1 === 0) {
setActiveIndex(-1);
return;
}
movePrev();
}
} else if (e.key === "Escape") {
setActiveIndex(-1);
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[value, activeIndex, removeFileFromSet],
);
const onDrop = useCallback(
(acceptedFiles: File[], rejectedFiles: FileRejection[]) => {
const files = acceptedFiles;
if (!files) {
toast.error("file error , probably too big");
return;
}
const newValues: File[] = value ? [...value] : [];
if (reSelectAll) {
newValues.splice(0, newValues.length);
}
files.forEach((file) => {
if (newValues.length < maxFiles) {
newValues.push(file);
}
});
onValueChange(newValues);
if (rejectedFiles?.length > 0) {
for (let i = 0; i < rejectedFiles?.length; i++) {
if (rejectedFiles[i]?.errors[0]?.code === "file-too-large") {
toast.error(
`File is too large. Max size is ${maxSize / 1024 / 1024}MB`,
);
break;
}
if (rejectedFiles[i]?.errors[0]?.message) {
toast.error(rejectedFiles[i]?.errors[0]?.message);
break;
}
}
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[reSelectAll, value],
);
useEffect(() => {
if (!value) return;
if (value.length === maxFiles) {
setIsLOF(true);
return;
}
setIsLOF(false);
}, [value, maxFiles]);
const opts = dropzoneOptions
? dropzoneOptions
: { accept, maxFiles, maxSize, multiple };
const dropzoneState = useDropzone({
...opts,
onDrop,
onDropRejected: () => setIsFileTooBig(true),
onDropAccepted: () => setIsFileTooBig(false),
});
return (
<FileUploaderContext.Provider
value={{
dropzoneState,
isLOF,
isFileTooBig,
removeFileFromSet,
activeIndex,
setActiveIndex,
orientation,
direction,
}}
>
<div
ref={ref}
tabIndex={0}
onKeyDownCapture={handleKeyDown}
className={cn(
"grid w-full focus:outline-none overflow-hidden ",
className,
{
"gap-2": value && value.length > 0,
},
)}
dir={dir}
{...props}
>
{children}
</div>
</FileUploaderContext.Provider>
);
},
);
FileUploader.displayName = "FileUploader";
export const FileUploaderContent = forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ children, className, ...props }, ref) => {
const { orientation } = useFileUpload();
const containerRef = useRef<HTMLDivElement>(null);
return (
<div
className={cn("w-full px-1")}
ref={containerRef}
aria-description="content file holder"
>
<div
{...props}
ref={ref}
className={cn(
"flex rounded-xl gap-1",
orientation === "horizontal" ? "flex-raw flex-wrap" : "flex-col",
className,
)}
>
{children}
</div>
</div>
);
});
FileUploaderContent.displayName = "FileUploaderContent";
export const FileUploaderItem = forwardRef<
HTMLDivElement,
{ index: number } & React.HTMLAttributes<HTMLDivElement>
>(({ className, index, children, ...props }, ref) => {
const { removeFileFromSet, activeIndex, direction } = useFileUpload();
const isSelected = index === activeIndex;
return (
<div
ref={ref}
className={cn(
buttonVariants({ variant: "ghost" }),
"h-6 p-1 justify-between cursor-pointer relative",
className,
isSelected ? "bg-muted" : "",
)}
{...props}
>
<div className="font-medium leading-none tracking-tight flex items-center gap-1.5 h-full w-full">
{children}
</div>
<button
type="button"
className={cn(
"absolute",
direction === "rtl" ? "top-1 left-1" : "top-1 right-1",
)}
onClick={() => removeFileFromSet(index)}
>
<span className="sr-only">remove item {index}</span>
<RemoveIcon className="w-4 h-4 hover:stroke-destructive duration-200 ease-in-out" />
</button>
</div>
);
});
FileUploaderItem.displayName = "FileUploaderItem";
export const FileInput = forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, children, ...props }, ref) => {
const { dropzoneState, isFileTooBig, isLOF } = useFileUpload();
const rootProps = isLOF ? {} : dropzoneState.getRootProps();
return (
<div
ref={ref}
{...props}
className={`relative w-full ${
isLOF ? "opacity-50 cursor-not-allowed " : "cursor-pointer "
}`}
>
<div
className={cn(
`w-full rounded-lg duration-300 ease-in-out
${
dropzoneState.isDragAccept
? "border-green-500"
: dropzoneState.isDragReject || isFileTooBig
? "border-red-500"
: "border-gray-300"
}`,
className,
)}
{...rootProps}
>
{children}
</div>
<Input
ref={dropzoneState.inputRef}
disabled={isLOF}
{...dropzoneState.getInputProps()}
className={`${isLOF ? "cursor-not-allowed" : ""}`}
/>
</div>
);
});
FileInput.displayName = "FileInput";
@@ -0,0 +1,174 @@
"use client"
import * as LabelPrimitive from "@radix-ui/react-label"
import { Slot } from "@radix-ui/react-slot"
import * as React from "react"
import {
Controller,
type ControllerProps,
type FieldPath,
type FieldValues,
FormProvider,
useFormContext,
} from "react-hook-form"
import { cn } from "../../lib/utils"
import { Label } from "./lib/label"
const Form = FormProvider
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
> = {
name: TName
}
const FormFieldContext = React.createContext<FormFieldContextValue>(
{} as FormFieldContextValue
)
const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
>({
...props
}: ControllerProps<TFieldValues, TName>) => {
return (
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
)
}
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext)
const itemContext = React.useContext(FormItemContext)
const { getFieldState, formState } = useFormContext()
const fieldState = getFieldState(fieldContext.name, formState)
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>")
}
const { id } = itemContext
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
}
}
type FormItemContextValue = {
id: string
}
const FormItemContext = React.createContext<FormItemContextValue>(
{} as FormItemContextValue
)
const FormItem = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const id = React.useId()
return (
<FormItemContext.Provider value={{ id }}>
<div ref={ref} className={cn("space-y-2", className)} {...props} />
</FormItemContext.Provider>
)
})
FormItem.displayName = "FormItem"
const FormLabel = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
>(({ className, ...props }, ref) => {
const { error, formItemId } = useFormField()
return (
<Label
ref={ref}
className={cn(error && "text-destructive", className)}
htmlFor={formItemId}
{...props}
/>
)
})
FormLabel.displayName = "FormLabel"
const FormControl = React.forwardRef<
React.ElementRef<typeof Slot>,
React.ComponentPropsWithoutRef<typeof Slot>
>(({ ...props }, ref) => {
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
return (
<Slot
ref={ref}
id={formItemId}
aria-describedby={
!error
? `${formDescriptionId}`
: `${formDescriptionId} ${formMessageId}`
}
aria-invalid={!!error}
{...props}
/>
)
})
FormControl.displayName = "FormControl"
const FormDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => {
const { formDescriptionId } = useFormField()
return (
<p
ref={ref}
id={formDescriptionId}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
})
FormDescription.displayName = "FormDescription"
const FormMessage = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, children, ...props }, ref) => {
const { error, formMessageId } = useFormField()
const body = error ? String(error?.message ?? "") : children
if (!body) {
return null
}
return (
<p
ref={ref}
id={formMessageId}
className={cn("text-sm font-medium text-destructive", className)}
{...props}
>
{body}
</p>
)
})
FormMessage.displayName = "FormMessage"
export {
Form, FormControl,
FormDescription, FormField, FormItem,
FormLabel, FormMessage, useFormField
}
@@ -0,0 +1,58 @@
"use client"
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline:
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-md px-8",
icon: "h-10 w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = "Button"
export { Button, buttonVariants }
@@ -0,0 +1,174 @@
"use client"
import * as LabelPrimitive from "@radix-ui/react-label"
import { Slot } from "@radix-ui/react-slot"
import * as React from "react"
import {
Controller,
type ControllerProps,
type FieldPath,
type FieldValues,
FormProvider,
useFormContext,
} from "react-hook-form"
import { cn } from "../../../lib/utils"
import { Label } from "../lib/label"
const Form = FormProvider
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
> = {
name: TName
}
const FormFieldContext = React.createContext<FormFieldContextValue>(
{} as FormFieldContextValue
)
const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
>({
...props
}: ControllerProps<TFieldValues, TName>) => {
return (
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
)
}
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext)
const itemContext = React.useContext(FormItemContext)
const { getFieldState, formState } = useFormContext()
const fieldState = getFieldState(fieldContext.name, formState)
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>")
}
const { id } = itemContext
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
}
}
type FormItemContextValue = {
id: string
}
const FormItemContext = React.createContext<FormItemContextValue>(
{} as FormItemContextValue
)
const FormItem = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const id = React.useId()
return (
<FormItemContext.Provider value={{ id }}>
<div ref={ref} className={cn("space-y-2", className)} {...props} />
</FormItemContext.Provider>
)
})
FormItem.displayName = "FormItem"
const FormLabel = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
>(({ className, ...props }, ref) => {
const { error, formItemId } = useFormField()
return (
<Label
ref={ref}
className={cn(error && "text-destructive", className)}
htmlFor={formItemId}
{...props}
/>
)
})
FormLabel.displayName = "FormLabel"
const FormControl = React.forwardRef<
React.ElementRef<typeof Slot>,
React.ComponentPropsWithoutRef<typeof Slot>
>(({ ...props }, ref) => {
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
return (
<Slot
ref={ref}
id={formItemId}
aria-describedby={
!error
? `${formDescriptionId}`
: `${formDescriptionId} ${formMessageId}`
}
aria-invalid={!!error}
{...props}
/>
)
})
FormControl.displayName = "FormControl"
const FormDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => {
const { formDescriptionId } = useFormField()
return (
<p
ref={ref}
id={formDescriptionId}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
})
FormDescription.displayName = "FormDescription"
const FormMessage = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, children, ...props }, ref) => {
const { error, formMessageId } = useFormField()
const body = error ? String(error?.message ?? "") : children
if (!body) {
return null
}
return (
<p
ref={ref}
id={formMessageId}
className={cn("text-sm font-medium text-destructive", className)}
{...props}
>
{body}
</p>
)
})
FormMessage.displayName = "FormMessage"
export {
Form, FormControl,
FormDescription, FormField, FormItem,
FormLabel, FormMessage, useFormField
}

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