From a114dd3ed335b8d4cd67576636c57f30a181a7cf Mon Sep 17 00:00:00 2001 From: a2751012962 Date: Fri, 2 Oct 2026 14:01:29 +0800 Subject: [PATCH 1/9] refactor(ui): extract Typewriter into the @iguide/ui package The dorm feature is moving into its own workspace package and still needs Typewriter, so the component moves out of the web app into a package both can depend on. --- apps/web/package.json | 1 + apps/web/src/components/housing/AIChat.tsx | 2 +- .../components/layout/ConversationSidebar.tsx | 2 +- .../web/src/components/layout/DormSidebar.tsx | 2 +- .../src/components/layout/LibrarySidebar.tsx | 2 +- apps/web/src/index.css | 3 +++ packages/ui/package.json | 26 +++++++++++++++++++ .../ui => packages/ui/src}/Typewriter.tsx | 0 packages/ui/src/index.ts | 2 ++ packages/ui/tsconfig.json | 16 ++++++++++++ pnpm-lock.yaml | 25 ++++++++++++++++++ vite.config.ts | 2 +- 12 files changed, 78 insertions(+), 5 deletions(-) create mode 100644 packages/ui/package.json rename {apps/web/src/components/ui => packages/ui/src}/Typewriter.tsx (100%) create mode 100644 packages/ui/src/index.ts create mode 100644 packages/ui/tsconfig.json diff --git a/apps/web/package.json b/apps/web/package.json index e387407d..cb4d653c 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -19,6 +19,7 @@ "@assistant-ui/react": "^0.15.22", "@assistant-ui/react-markdown": "0.14.17", "@headlessui/react": "^2.2.10", + "@iguide/ui": "workspace:*", "@supabase/supabase-js": "^2.117.2", "framer-motion": "^13.4.4", "lucide-react": "^1.48.0", diff --git a/apps/web/src/components/housing/AIChat.tsx b/apps/web/src/components/housing/AIChat.tsx index eaf691b5..557c4f0c 100644 --- a/apps/web/src/components/housing/AIChat.tsx +++ b/apps/web/src/components/housing/AIChat.tsx @@ -1,3 +1,4 @@ +import { Typewriter } from "@iguide/ui" import { motion, AnimatePresence } from "framer-motion" import { MessageCircle, X, Send, Sparkles, Loader2 } from "lucide-react" import React, { useState, useRef, useEffect } from "react" @@ -8,7 +9,6 @@ import remarkGfm from "remark-gfm" import { streamChatResponse } from "../../services/ai" import { Language } from "../../types" import { isDormMention, findMentionedDorms } from "../../utils/housingUtils" -import { Typewriter } from "../ui/Typewriter" import { aiChatTexts } from "./i18n/dormTexts" import { ChatMessage } from "./types/index" diff --git a/apps/web/src/components/layout/ConversationSidebar.tsx b/apps/web/src/components/layout/ConversationSidebar.tsx index 3f892ca9..98f5f220 100644 --- a/apps/web/src/components/layout/ConversationSidebar.tsx +++ b/apps/web/src/components/layout/ConversationSidebar.tsx @@ -1,3 +1,4 @@ +import { Typewriter } from "@iguide/ui" import * as React from "react" import { useEffect, useState } from "react" @@ -5,7 +6,6 @@ import { useAuth } from "../../contexts/AuthContext" import { conversationService } from "../../services/conversationService" import { localConversationService } from "../../services/localConversationService" import { ConversationSummary } from "../../types" -import { Typewriter } from "../ui/Typewriter" import { BaseSidebar, SidebarItem, diff --git a/apps/web/src/components/layout/DormSidebar.tsx b/apps/web/src/components/layout/DormSidebar.tsx index d939bcd3..602eb28b 100644 --- a/apps/web/src/components/layout/DormSidebar.tsx +++ b/apps/web/src/components/layout/DormSidebar.tsx @@ -1,3 +1,4 @@ +import { Typewriter } from "@iguide/ui" import { AnimatePresence, motion } from "framer-motion" import { Clock, Heart, Trash2 } from "lucide-react" import React, { useMemo } from "react" @@ -7,7 +8,6 @@ import { Language } from "../../types" import { useDormData } from "../housing/store/DormDataContext" import { useSharedDormInteraction } from "../housing/store/DormUserInteractionContext" import { Dorm } from "../housing/types/index" -import { Typewriter } from "../ui/Typewriter" interface DormSidebarProps { language: Language diff --git a/apps/web/src/components/layout/LibrarySidebar.tsx b/apps/web/src/components/layout/LibrarySidebar.tsx index d554b541..3b7dee33 100644 --- a/apps/web/src/components/layout/LibrarySidebar.tsx +++ b/apps/web/src/components/layout/LibrarySidebar.tsx @@ -1,10 +1,10 @@ +import { Typewriter } from "@iguide/ui" import React, { useEffect, useState } from "react" import { useNavigate } from "react-router-dom" import { libraryService } from "../../services/libraryService" import { supabase } from "../../services/supabase" import { LibraryHistoryItem } from "../../types" -import { Typewriter } from "../ui/Typewriter" import { BaseSidebar, SidebarItem, diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 97078e85..d50d8ff6 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -2,6 +2,9 @@ /* [根组件] 全局样式和 Tailwind CSS 指令。 */ @import "tailwindcss"; +/* Workspace UI packages sit outside this app's root, so Tailwind won't find their classes on its own. */ +@source "../../../packages/ui/src"; + @theme { --color-illini-blue: #13294b; --color-illini-orange: #ff5f05; diff --git a/packages/ui/package.json b/packages/ui/package.json new file mode 100644 index 00000000..686fb00d --- /dev/null +++ b/packages/ui/package.json @@ -0,0 +1,26 @@ +{ + "name": "@iguide/ui", + "version": "0.0.0", + "private": true, + "description": "Business-agnostic UI primitives shared by IlliniGuide apps and feature packages.", + "type": "module", + "exports": { + ".": "./src/index.ts" + }, + "scripts": { + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "framer-motion": "^13.4.4", + "react-markdown": "^10.1.0", + "remark-gfm": "^4.0.1" + }, + "devDependencies": { + "@types/react": "^19.3.0", + "react": "^19.3.0", + "typescript": "~7.0.2" + }, + "peerDependencies": { + "react": "^19.3.0" + } +} diff --git a/apps/web/src/components/ui/Typewriter.tsx b/packages/ui/src/Typewriter.tsx similarity index 100% rename from apps/web/src/components/ui/Typewriter.tsx rename to packages/ui/src/Typewriter.tsx diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts new file mode 100644 index 00000000..01dbbdb2 --- /dev/null +++ b/packages/ui/src/index.ts @@ -0,0 +1,2 @@ +export { Typewriter } from "./Typewriter" +export type { TypewriterMode, TypewriterProps } from "./Typewriter" diff --git a/packages/ui/tsconfig.json b/packages/ui/tsconfig.json new file mode 100644 index 00000000..df4bcce1 --- /dev/null +++ b/packages/ui/tsconfig.json @@ -0,0 +1,16 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "skipLibCheck": true, + "moduleResolution": "bundler", + "isolatedModules": true, + "moduleDetection": "force", + "esModuleInterop": true, + "jsx": "react-jsx", + "noEmit": true + }, + "include": ["src"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 64d769d2..28e5d786 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -196,6 +196,9 @@ importers: '@headlessui/react': specifier: ^2.2.10 version: 2.2.10(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + '@iguide/ui': + specifier: workspace:* + version: link:../../packages/ui '@supabase/supabase-js': specifier: ^2.117.2 version: 2.117.2 @@ -282,6 +285,28 @@ importers: specifier: 'catalog:' version: 0.3.3(@types/node@26.6.3)(esbuild@0.28.1)(jiti@2.7.0)(typescript@7.0.2) + packages/ui: + dependencies: + framer-motion: + specifier: ^13.4.4 + version: 13.4.4(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + react-markdown: + specifier: ^10.1.0 + version: 10.1.0(@types/react@19.3.0)(react@19.3.0)(supports-color@10.2.2) + remark-gfm: + specifier: ^4.0.1 + version: 4.0.1(supports-color@10.2.2) + devDependencies: + '@types/react': + specifier: ^19.3.0 + version: 19.3.0 + react: + specifier: ^19.3.0 + version: 19.3.0 + typescript: + specifier: ~7.0.2 + version: 7.0.2 + tools/vite-bin: dependencies: vite-plus: diff --git a/vite.config.ts b/vite.config.ts index d54ddebc..32428025 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -28,7 +28,7 @@ export default defineConfig({ ignorePatterns, overrides: [ { - files: ["apps/web/**"], + files: ["apps/web/**", "packages/ui/**"], env: { browser: true }, }, { From 62df922e19b41a1baf04a2355b3992b38d3a8933 Mon Sep 17 00:00:00 2001 From: a2751012962 Date: Fri, 2 Oct 2026 14:02:19 +0800 Subject: [PATCH 2/9] refactor(dorm): move the dorm feature into the @iguide/dorm package Dorm providers wrapped the whole app, so every page loaded dorm code and fetched every dorm from Supabase on startup, and the shell layout reached into housing state. The feature now lives in its own package behind one lazy /dorms/* route: the host lends it the Supabase client, session, chat stream, and two shell slots, and the package imports nothing from the app. Its dependencies (Mapbox GL, rc-slider, Headless UI) leave the web app with it. Filters, search, and the compare list now reset when you leave /dorms; favorites and history persist through localStorage as before. --- apps/web/package.json | 6 +- apps/web/src/App.tsx | 42 ++--- apps/web/src/app/pageRegistry.ts | 4 +- apps/web/src/app/routes.tsx | 6 +- apps/web/src/components/layout/Layout.tsx | 134 +--------------- .../src/components/layout/SidebarPanel.tsx | 17 +-- apps/web/src/contexts/LayoutContext.tsx | 9 ++ apps/web/src/index.css | 26 +--- apps/web/src/pages/dorms/DormRoute.tsx | 47 ++++++ apps/web/tsconfig.json | 2 +- packages/dorm/package.json | 46 ++++++ .../dorm}/scripts/audit-dorm-media.ts | 0 .../scripts/create_dorm_user_features.sql | 0 .../migrations/add_categorized_tags.sql | 0 .../scripts/migrations/add_dorm_address.sql | 0 .../migrations/add_dorm_comment_hidden.sql | 0 .../scripts/migrations/add_dorm_comments.sql | 0 .../migrations/add_dorm_edit_history.sql | 0 .../scripts/migrations/add_dorm_website.sql | 0 .../migrations/add_floor_plan_bed_size.sql | 0 .../migrations/add_floor_plan_photo_url.sql | 0 .../scripts/migrations/create_dorms_table.sql | 0 .../migrations/create_storage_bucket.sql | 0 .../migrations/fix_dorm_edit_history_rls.sql | 0 .../dorm}/scripts/seed-dorms-table.ts | 0 .../dorm}/scripts/validate-dorm-data.ts | 0 packages/dorm/src/DormRoutes.tsx | 70 +++++++++ .../dorm}/src/components/housing/AIChat.tsx | 2 +- .../src/components/housing/DORM_DATA_AUDIT.md | 0 .../dorm}/src/components/housing/DormCard.tsx | 0 .../src/components/housing/DormComparison.tsx | 0 .../src/components/housing/DormDetail.tsx | 3 +- .../housing/DormDetailFloorPlans.tsx | 0 .../components/housing/DormDetailGallery.tsx | 0 .../components/housing/DormDetailHeader.tsx | 0 .../src/components/housing/DormDetailInfo.tsx | 0 .../components/housing/DormDetailReviews.tsx | 0 .../src/components/housing/DormEditPanel.tsx | 0 .../dorm}/src/components/housing/DormList.tsx | 2 +- .../dorm}/src/components/housing/DormMap.tsx | 3 + .../src/components/housing/FilterModal.tsx | 0 .../src/components/housing/ImageLightbox.tsx | 0 .../dorm}/src/components/housing/README.md | 0 .../components/housing/SortingDropdown.tsx | 0 .../src/components/housing/constants/chat.ts | 0 .../components/housing/constants/dormData.ts | 0 .../constants/dormOfficialOverrideUtils.ts | 0 .../constants/dormOfficialOverrides.ts | 0 .../constants/dormOfficialOverridesPch.ts | 0 .../dormOfficialOverridesUrhNorth.ts | 0 .../dormOfficialOverridesUrhSouth.ts | 0 .../housing/constants/featureFlags.ts | 0 .../components/housing/constants/filters.ts | 0 .../housing/constants/googleReviews.ts | 0 .../src/components/housing/constants/index.ts | 0 .../components/housing/constants/mapData.ts | 0 .../components/housing/constants/metadata.ts | 0 .../components/housing/constants/pricing.ts | 0 .../components/housing/dorm-list/DormGrid.tsx | 0 .../housing/dorm-list/DormListHeader.tsx | 0 .../housing/dorm-list/DormListMapPane.tsx | 0 .../dorm-list/DormListMobileHeader.tsx | 144 ++++++++++++++++++ .../housing/dorm-list/EmptyStates.tsx | 0 .../housing/dorm-list/FavoriteFlyEffect.tsx | 0 .../housing/dorm-list/MapCarousel.tsx | 0 .../housing/dorm-list/favoriteConstants.ts | 0 .../components/housing/dorm-list/filtering.ts | 0 .../src/components/housing/dorm-list/types.ts | 0 .../dorm-list/useDormListController.ts | 2 +- .../src/components/housing/dorm-map/layers.ts | 0 .../components/housing/dorm-map/mapAssets.ts | 0 .../housing/dorm-map/mapConstants.ts | 0 .../housing/dorm-map/mapFeatureBuilders.ts | 0 .../src/components/housing/dorm-map/types.ts | 0 .../housing/edit-panel/ContentTab.tsx | 0 .../housing/edit-panel/DetailsTab.tsx | 0 .../housing/edit-panel/DormEditPanelShell.tsx | 0 .../housing/edit-panel/EditPanelFields.tsx | 0 .../housing/edit-panel/HistoryTab.tsx | 0 .../housing/edit-panel/MediaTab.tsx | 0 .../components/housing/edit-panel/TagsTab.tsx | 0 .../housing/edit-panel/editPanelText.ts | 0 .../housing/edit-panel/useDormEditForm.ts | 2 +- .../housing/filter-modal/AmenitiesSection.tsx | 0 .../housing/filter-modal/ChipSection.tsx | 0 .../filter-modal/HousingTypeSection.tsx | 0 .../housing/filter-modal/PriceSection.tsx | 0 .../housing/filter-modal/RoomTypeSection.tsx | 0 .../housing/filter-modal/TagFilterSection.tsx | 0 .../housing/filter-modal/modalText.ts | 0 .../housing/hooks/useDormCommentStats.ts | 0 .../housing/hooks/useDormComments.ts | 2 +- .../housing/hooks/useDormFilterBadge.ts | 0 .../housing/hooks/useDormUserInteraction.ts | 2 +- .../src/components/housing/i18n/dormTexts.ts | 0 .../housing/store/CompareContext.tsx | 0 .../housing/store/DormDataContext.tsx | 0 .../store/DormUserInteractionContext.tsx | 0 .../housing/store/HousingContext.tsx | 0 .../src/components/housing/types/index.ts | 0 .../src/components/layout/DormSidebar.tsx | 0 .../src/components/layout/useShellSlot.tsx | 21 +++ .../dorm}/src/constants/housing.ts | 0 .../dorm/src/contexts/DormHostContext.tsx | 52 +++++++ packages/dorm/src/dorm.css | 24 +++ packages/dorm/src/index.ts | 7 + .../dorm}/src/pages/dorms/DormDetailPage.tsx | 0 .../dorm}/src/pages/dorms/DormListPage.tsx | 2 + .../dorm}/src/services/dormAdminService.ts | 28 ++-- .../dorm}/src/services/dormCommentsService.ts | 34 +++-- .../src/services/dormFavoritesService.ts | 35 +++-- .../dorm}/src/services/dormService.ts | 6 +- .../dorm}/src/services/dormViewingService.ts | 47 +++--- packages/dorm/src/services/host.ts | 49 ++++++ packages/dorm/src/types.ts | 2 + .../dorm}/src/utils/dormData.ts | 0 .../dorm}/src/utils/housingLabels.ts | 0 .../dorm}/src/utils/housingUtils.ts | 0 .../dorm}/src/utils/roomOptions.ts | 0 .../dorm}/src/utils/tagLabels.ts | 0 packages/dorm/tsconfig.json | 18 +++ pnpm-lock.yaml | 82 ++++++++-- vite.config.ts | 2 +- 123 files changed, 677 insertions(+), 303 deletions(-) create mode 100644 apps/web/src/pages/dorms/DormRoute.tsx create mode 100644 packages/dorm/package.json rename {apps/web => packages/dorm}/scripts/audit-dorm-media.ts (100%) rename {apps/web => packages/dorm}/scripts/create_dorm_user_features.sql (100%) rename {apps/web => packages/dorm}/scripts/migrations/add_categorized_tags.sql (100%) rename {apps/web => packages/dorm}/scripts/migrations/add_dorm_address.sql (100%) rename {apps/web => packages/dorm}/scripts/migrations/add_dorm_comment_hidden.sql (100%) rename {apps/web => packages/dorm}/scripts/migrations/add_dorm_comments.sql (100%) rename {apps/web => packages/dorm}/scripts/migrations/add_dorm_edit_history.sql (100%) rename {apps/web => packages/dorm}/scripts/migrations/add_dorm_website.sql (100%) rename {apps/web => packages/dorm}/scripts/migrations/add_floor_plan_bed_size.sql (100%) rename {apps/web => packages/dorm}/scripts/migrations/add_floor_plan_photo_url.sql (100%) rename {apps/web => packages/dorm}/scripts/migrations/create_dorms_table.sql (100%) rename {apps/web => packages/dorm}/scripts/migrations/create_storage_bucket.sql (100%) rename {apps/web => packages/dorm}/scripts/migrations/fix_dorm_edit_history_rls.sql (100%) rename {apps/web => packages/dorm}/scripts/seed-dorms-table.ts (100%) rename {apps/web => packages/dorm}/scripts/validate-dorm-data.ts (100%) create mode 100644 packages/dorm/src/DormRoutes.tsx rename {apps/web => packages/dorm}/src/components/housing/AIChat.tsx (99%) rename {apps/web => packages/dorm}/src/components/housing/DORM_DATA_AUDIT.md (100%) rename {apps/web => packages/dorm}/src/components/housing/DormCard.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/DormComparison.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/DormDetail.tsx (99%) rename {apps/web => packages/dorm}/src/components/housing/DormDetailFloorPlans.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/DormDetailGallery.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/DormDetailHeader.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/DormDetailInfo.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/DormDetailReviews.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/DormEditPanel.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/DormList.tsx (99%) rename {apps/web => packages/dorm}/src/components/housing/DormMap.tsx (99%) rename {apps/web => packages/dorm}/src/components/housing/FilterModal.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/ImageLightbox.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/README.md (100%) rename {apps/web => packages/dorm}/src/components/housing/SortingDropdown.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/constants/chat.ts (100%) rename {apps/web => packages/dorm}/src/components/housing/constants/dormData.ts (100%) rename {apps/web => packages/dorm}/src/components/housing/constants/dormOfficialOverrideUtils.ts (100%) rename {apps/web => packages/dorm}/src/components/housing/constants/dormOfficialOverrides.ts (100%) rename {apps/web => packages/dorm}/src/components/housing/constants/dormOfficialOverridesPch.ts (100%) rename {apps/web => packages/dorm}/src/components/housing/constants/dormOfficialOverridesUrhNorth.ts (100%) rename {apps/web => packages/dorm}/src/components/housing/constants/dormOfficialOverridesUrhSouth.ts (100%) rename {apps/web => packages/dorm}/src/components/housing/constants/featureFlags.ts (100%) rename {apps/web => packages/dorm}/src/components/housing/constants/filters.ts (100%) rename {apps/web => packages/dorm}/src/components/housing/constants/googleReviews.ts (100%) rename {apps/web => packages/dorm}/src/components/housing/constants/index.ts (100%) rename {apps/web => packages/dorm}/src/components/housing/constants/mapData.ts (100%) rename {apps/web => packages/dorm}/src/components/housing/constants/metadata.ts (100%) rename {apps/web => packages/dorm}/src/components/housing/constants/pricing.ts (100%) rename {apps/web => packages/dorm}/src/components/housing/dorm-list/DormGrid.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/dorm-list/DormListHeader.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/dorm-list/DormListMapPane.tsx (100%) create mode 100644 packages/dorm/src/components/housing/dorm-list/DormListMobileHeader.tsx rename {apps/web => packages/dorm}/src/components/housing/dorm-list/EmptyStates.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/dorm-list/FavoriteFlyEffect.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/dorm-list/MapCarousel.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/dorm-list/favoriteConstants.ts (100%) rename {apps/web => packages/dorm}/src/components/housing/dorm-list/filtering.ts (100%) rename {apps/web => packages/dorm}/src/components/housing/dorm-list/types.ts (100%) rename {apps/web => packages/dorm}/src/components/housing/dorm-list/useDormListController.ts (99%) rename {apps/web => packages/dorm}/src/components/housing/dorm-map/layers.ts (100%) rename {apps/web => packages/dorm}/src/components/housing/dorm-map/mapAssets.ts (100%) rename {apps/web => packages/dorm}/src/components/housing/dorm-map/mapConstants.ts (100%) rename {apps/web => packages/dorm}/src/components/housing/dorm-map/mapFeatureBuilders.ts (100%) rename {apps/web => packages/dorm}/src/components/housing/dorm-map/types.ts (100%) rename {apps/web => packages/dorm}/src/components/housing/edit-panel/ContentTab.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/edit-panel/DetailsTab.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/edit-panel/DormEditPanelShell.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/edit-panel/EditPanelFields.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/edit-panel/HistoryTab.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/edit-panel/MediaTab.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/edit-panel/TagsTab.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/edit-panel/editPanelText.ts (100%) rename {apps/web => packages/dorm}/src/components/housing/edit-panel/useDormEditForm.ts (99%) rename {apps/web => packages/dorm}/src/components/housing/filter-modal/AmenitiesSection.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/filter-modal/ChipSection.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/filter-modal/HousingTypeSection.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/filter-modal/PriceSection.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/filter-modal/RoomTypeSection.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/filter-modal/TagFilterSection.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/filter-modal/modalText.ts (100%) rename {apps/web => packages/dorm}/src/components/housing/hooks/useDormCommentStats.ts (100%) rename {apps/web => packages/dorm}/src/components/housing/hooks/useDormComments.ts (98%) rename {apps/web => packages/dorm}/src/components/housing/hooks/useDormFilterBadge.ts (100%) rename {apps/web => packages/dorm}/src/components/housing/hooks/useDormUserInteraction.ts (99%) rename {apps/web => packages/dorm}/src/components/housing/i18n/dormTexts.ts (100%) rename {apps/web => packages/dorm}/src/components/housing/store/CompareContext.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/store/DormDataContext.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/store/DormUserInteractionContext.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/store/HousingContext.tsx (100%) rename {apps/web => packages/dorm}/src/components/housing/types/index.ts (100%) rename {apps/web => packages/dorm}/src/components/layout/DormSidebar.tsx (100%) create mode 100644 packages/dorm/src/components/layout/useShellSlot.tsx rename {apps/web => packages/dorm}/src/constants/housing.ts (100%) create mode 100644 packages/dorm/src/contexts/DormHostContext.tsx create mode 100644 packages/dorm/src/dorm.css create mode 100644 packages/dorm/src/index.ts rename {apps/web => packages/dorm}/src/pages/dorms/DormDetailPage.tsx (100%) rename {apps/web => packages/dorm}/src/pages/dorms/DormListPage.tsx (73%) rename {apps/web => packages/dorm}/src/services/dormAdminService.ts (92%) rename {apps/web => packages/dorm}/src/services/dormCommentsService.ts (87%) rename {apps/web => packages/dorm}/src/services/dormFavoritesService.ts (76%) rename {apps/web => packages/dorm}/src/services/dormService.ts (94%) rename {apps/web => packages/dorm}/src/services/dormViewingService.ts (62%) create mode 100644 packages/dorm/src/services/host.ts create mode 100644 packages/dorm/src/types.ts rename {apps/web => packages/dorm}/src/utils/dormData.ts (100%) rename {apps/web => packages/dorm}/src/utils/housingLabels.ts (100%) rename {apps/web => packages/dorm}/src/utils/housingUtils.ts (100%) rename {apps/web => packages/dorm}/src/utils/roomOptions.ts (100%) rename {apps/web => packages/dorm}/src/utils/tagLabels.ts (100%) create mode 100644 packages/dorm/tsconfig.json diff --git a/apps/web/package.json b/apps/web/package.json index cb4d653c..d48f8cad 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -18,16 +18,13 @@ "dependencies": { "@assistant-ui/react": "^0.15.22", "@assistant-ui/react-markdown": "0.14.17", - "@headlessui/react": "^2.2.10", + "@iguide/dorm": "workspace:*", "@iguide/ui": "workspace:*", "@supabase/supabase-js": "^2.117.2", "framer-motion": "^13.4.4", "lucide-react": "^1.48.0", - "mapbox-gl": "^3.31.0", - "rc-slider": "^11.1.9", "react": "^19.3.0", "react-dom": "^19.3.0", - "react-map-gl": "^8.1.3", "react-markdown": "^10.1.0", "react-router-dom": "^7.18.4", "remark-gfm": "^4.0.1" @@ -37,7 +34,6 @@ "@cloudflare/workers-types": "^5.20260927.1", "@iguide/vite-bin": "workspace:*", "@tailwindcss/vite": "^4.3.3", - "@types/geojson": "^7946.0.16", "@types/node": "^26.6.3", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index 019e980a..c94de737 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -4,10 +4,6 @@ import { useCallback, useEffect, useState } from "react" import { AppRoutes } from "./app/routes" import { LoginScreen } from "./components/auth/LoginScreen" -import { CompareProvider } from "./components/housing/store/CompareContext" -import { DormDataProvider } from "./components/housing/store/DormDataContext" -import { DormUserInteractionProvider } from "./components/housing/store/DormUserInteractionContext" -import { HousingProvider } from "./components/housing/store/HousingContext" import { Layout } from "./components/layout/Layout" import { useAuth } from "./contexts/AuthContext" import { Language } from "./types" @@ -101,29 +97,21 @@ export default function App() { transition={{ duration: 0.4, ease: "easeOut" }} className="size-full" > - - - - - setIsGuest(false)} - currentConversationId={currentConversationId} - onNewConversation={handleNewConversation} - onSelectConversation={handleSelectConversation} - > - - - - - - + setIsGuest(false)} + currentConversationId={currentConversationId} + onNewConversation={handleNewConversation} + onSelectConversation={handleSelectConversation} + > + + )} diff --git a/apps/web/src/app/pageRegistry.ts b/apps/web/src/app/pageRegistry.ts index 92decf1c..67a6841c 100644 --- a/apps/web/src/app/pageRegistry.ts +++ b/apps/web/src/app/pageRegistry.ts @@ -75,7 +75,7 @@ export const PAGE_REGISTRY: PageRegistryItem[] = [ { id: "dorm-list", path: "/dorms", - componentPath: "src/pages/dorms/DormListPage.tsx", + componentPath: "@iguide/dorm/src/pages/dorms/DormListPage.tsx", ownerFeature: "dorms", contexts: ["auth", "housing", "dorm-user-interaction"], status: "active", @@ -83,7 +83,7 @@ export const PAGE_REGISTRY: PageRegistryItem[] = [ { id: "dorm-detail", path: "/dorms/:id", - componentPath: "src/pages/dorms/DormDetailPage.tsx", + componentPath: "@iguide/dorm/src/pages/dorms/DormDetailPage.tsx", ownerFeature: "dorms", contexts: ["auth", "housing", "dorm-user-interaction"], status: "active", diff --git a/apps/web/src/app/routes.tsx b/apps/web/src/app/routes.tsx index d79a8bfd..a5d9c6c3 100644 --- a/apps/web/src/app/routes.tsx +++ b/apps/web/src/app/routes.tsx @@ -10,8 +10,7 @@ const LibraryArticlePage = React.lazy(() => import("../pages/library/LibraryArti const ProfilePage = React.lazy(() => import("../pages/profile/ProfilePage")) const CoursesLandingPage = React.lazy(() => import("../pages/courses/CoursesLandingPage")) const ResumeLandingPage = React.lazy(() => import("../pages/resume/ResumeLandingPage")) -const DormListPage = React.lazy(() => import("../pages/dorms/DormListPage")) -const DormDetailPage = React.lazy(() => import("../pages/dorms/DormDetailPage")) +const DormRoute = React.lazy(() => import("../pages/dorms/DormRoute")) export interface AppRoutesProps { language: Language @@ -59,8 +58,7 @@ export const AppRoutes: React.FC = ({ } /> } /> } /> - } /> - } /> + } /> } /> } /> } /> diff --git a/apps/web/src/components/layout/Layout.tsx b/apps/web/src/components/layout/Layout.tsx index 557559aa..5852aeaa 100644 --- a/apps/web/src/components/layout/Layout.tsx +++ b/apps/web/src/components/layout/Layout.tsx @@ -1,4 +1,3 @@ -import { Search, SlidersHorizontal, Map as MapIcon, List, ArrowUpDown } from "lucide-react" import * as React from "react" import { useEffect, useRef, useState } from "react" import { useLocation, useNavigate } from "react-router-dom" @@ -7,75 +6,11 @@ import { useAuth } from "../../contexts/AuthContext" import { LayoutProvider } from "../../contexts/LayoutContext" import { UI_TEXT } from "../../i18n/uiText" import { Language } from "../../types" -import { useDormFilterBadge } from "../housing/hooks/useDormFilterBadge" -import { useHousingFilters } from "../housing/store/HousingContext" import { AppShell } from "./AppShell" import { PrimaryNav } from "./PrimaryNav" import { SidebarFooter } from "./SidebarFooter" import { SidebarPanel } from "./SidebarPanel" -// Duplicated from the housing domain's SortingDropdown to avoid a cross-domain -// import between the shared layout and the housing feature. -const SORT_OPTIONS = [ - { value: "name-asc", label: "A-Z" }, - { value: "name-desc", label: "Z-A" }, - { value: "price-asc", label: "Price ↑" }, - { value: "price-desc", label: "Price ↓" }, -] as const - -const SortDropdownMobile: React.FC<{ - sortBy: string - onSortChange: (v: string) => void -}> = ({ sortBy, onSortChange }) => { - const [open, setOpen] = React.useState(false) - const ref = React.useRef(null) - - React.useEffect(() => { - const handler = (e: MouseEvent) => { - if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false) - } - document.addEventListener("mousedown", handler) - return () => document.removeEventListener("mousedown", handler) - }, []) - - return ( -
- - {open && ( -
- {SORT_OPTIONS.map((o) => ( - - ))} -
- )} -
- ) -} - interface LayoutProps { children: React.ReactNode language: Language @@ -102,16 +37,6 @@ export const Layout: React.FC = ({ }) => { const t = UI_TEXT[language] const { user } = useAuth() - const { - searchTerm, - setSearchTerm, - setIsFilterModalOpen, - viewMode, - setViewMode, - sortBy, - setSortBy, - } = useHousingFilters() - const { hasActiveDormFilters, activeDormFilterCount } = useDormFilterBadge() const navigate = useNavigate() const location = useLocation() const [isSidebarOpen, setIsSidebarOpen] = useState(true) @@ -130,9 +55,6 @@ export const Layout: React.FC = ({ return "chat" }, [location.pathname, propActiveTab]) - const isDormListPage = location.pathname === "/dorms" - const isHousingMobileHeader = activeTab === "dorms" && isDormListPage - useEffect(() => { const mediaQuery = window.matchMedia("(min-width: 768px)") const handleMediaChange = (event: MediaQueryListEvent | MediaQueryList) => { @@ -247,60 +169,7 @@ export const Layout: React.FC = ({ }, ] - const mobileHeader = isHousingMobileHeader ? ( -
-
- - setSearchTerm(event.target.value)} - /> -
-
- - {hasActiveDormFilters && ( -
- {activeDormFilterCount} -
- )} -
- - -
- ) : ( + const mobileHeader = ( {activeTab === "chat" ? t.chatTab @@ -349,7 +218,6 @@ export const Layout: React.FC = ({ currentConversationId={currentConversationId} onNewConversation={onNewConversation} onSelectConversation={onSelectConversation} - favoritesIconRef={favoritesIconRef} /> void onSelectConversation?: (conversationId: string | null) => void - favoritesIconRef: React.RefObject } export const SidebarPanel: React.FC = ({ @@ -22,8 +21,10 @@ export const SidebarPanel: React.FC = ({ currentConversationId, onNewConversation, onSelectConversation, - favoritesIconRef, }) => { + // Feature packages (e.g. @iguide/dorm) fill this from inside their own route tree. + const { sidebarSlot } = useLayout() + return (
{activeTab === "chat" && ( @@ -42,15 +43,7 @@ export const SidebarPanel: React.FC = ({ } /> )} - {activeTab === "dorms" && ( - - )} + {sidebarSlot}
) } diff --git a/apps/web/src/contexts/LayoutContext.tsx b/apps/web/src/contexts/LayoutContext.tsx index b37a0817..0c4d502e 100644 --- a/apps/web/src/contexts/LayoutContext.tsx +++ b/apps/web/src/contexts/LayoutContext.tsx @@ -18,6 +18,9 @@ interface LayoutContextType { /** Custom mobile header slot — when set, replaces the default mobileHeader content */ mobileHeaderSlot: ReactNode | null setMobileHeaderSlot: (node: ReactNode | null) => void + /** Feature-owned sidebar content, rendered below the primary nav while set */ + sidebarSlot: ReactNode | null + setSidebarSlot: (node: ReactNode | null) => void } const LayoutContext = createContext(null) @@ -40,6 +43,8 @@ export const LayoutProvider: React.FC<{ (node: ReactNode | null) => setMobileHeaderSlotState(node), [], ) + const [sidebarSlot, setSidebarSlotState] = useState(null) + const setSidebarSlot = useCallback((node: ReactNode | null) => setSidebarSlotState(node), []) return ( {children} @@ -72,6 +79,8 @@ export const useLayout = (): LayoutContextType => { } as React.RefObject, mobileHeaderSlot: null, setMobileHeaderSlot: () => {}, + sidebarSlot: null, + setSidebarSlot: () => {}, } } return ctx diff --git a/apps/web/src/index.css b/apps/web/src/index.css index d50d8ff6..71880656 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -3,6 +3,7 @@ @import "tailwindcss"; /* Workspace UI packages sit outside this app's root, so Tailwind won't find their classes on its own. */ +@source "../../../packages/dorm/src"; @source "../../../packages/ui/src"; @theme { @@ -112,31 +113,6 @@ body { animation: slide-in 0.3s ease-out; } -/* Reduce paint/render cost while scrolling long dorm lists. */ -.dorm-card { - content-visibility: auto; - contain-intrinsic-size: 420px; -} - -/* Highlight glow effect for active map marker */ -@keyframes marker-glow { - 0%, - 100% { - box-shadow: - 0 0 20px rgba(255, 95, 5, 0.5), - 0 0 30px rgba(255, 95, 5, 0.3); - } - 50% { - box-shadow: - 0 0 25px rgba(255, 95, 5, 0.6), - 0 0 35px rgba(255, 95, 5, 0.4); - } -} - -.marker-glow { - animation: marker-glow 2s ease-in-out infinite; -} - /* Prose styles for markdown content */ .prose { line-height: 1.6; diff --git a/apps/web/src/pages/dorms/DormRoute.tsx b/apps/web/src/pages/dorms/DormRoute.tsx new file mode 100644 index 00000000..3213ee65 --- /dev/null +++ b/apps/web/src/pages/dorms/DormRoute.tsx @@ -0,0 +1,47 @@ +import { configureDormServices, DormLayoutBridge, DormRoutes } from "@iguide/dorm" +import React, { useMemo } from "react" + +import { useAuth } from "../../contexts/AuthContext" +import { useLayout } from "../../contexts/LayoutContext" +import { streamChatResponse } from "../../services/ai" +import { supabase } from "../../services/supabase" +import { Language } from "../../types" + +// This module is lazy-loaded with the /dorms route, so the dorm package and its +// services are wired up only when someone opens a dorm page. +configureDormServices({ supabase, streamChatResponse }) + +const DormRoute: React.FC<{ language: Language }> = ({ language }) => { + const { user, requestLogin } = useAuth() + const { + isSidebarOpen, + favoritesIconRef, + sidebarToggleButtonRef, + mobileSidebarButtonRef, + setMobileHeaderSlot, + setSidebarSlot, + } = useLayout() + + const layout = useMemo( + () => ({ + isSidebarOpen, + favoritesIconRef, + sidebarToggleButtonRef, + mobileSidebarButtonRef, + setMobileHeaderSlot, + setSidebarSlot, + }), + [ + isSidebarOpen, + favoritesIconRef, + sidebarToggleButtonRef, + mobileSidebarButtonRef, + setMobileHeaderSlot, + setSidebarSlot, + ], + ) + + return +} + +export default DormRoute diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 2248a591..b01e3e1e 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -19,6 +19,6 @@ }, "allowImportingTsExtensions": true, "noEmit": true, - "types": ["vite/client", "@cloudflare/workers-types", "geojson"] + "types": ["vite/client", "@cloudflare/workers-types"] } } diff --git a/packages/dorm/package.json b/packages/dorm/package.json new file mode 100644 index 00000000..dd4f9c69 --- /dev/null +++ b/packages/dorm/package.json @@ -0,0 +1,46 @@ +{ + "name": "@iguide/dorm", + "version": "0.0.0", + "private": true, + "description": "Dorm (housing) feature for IlliniGuide: list, map, detail, compare, reviews, and admin editing.", + "type": "module", + "exports": { + ".": "./src/index.ts" + }, + "scripts": { + "audit:media": "pnpm dlx tsx scripts/audit-dorm-media.ts", + "seed": "pnpm dlx tsx scripts/seed-dorms-table.ts", + "typecheck": "tsc --noEmit", + "validate:data": "pnpm dlx tsx scripts/validate-dorm-data.ts" + }, + "dependencies": { + "@headlessui/react": "^2.2.10", + "@iguide/ui": "workspace:*", + "framer-motion": "^13.4.4", + "lucide-react": "^1.48.0", + "mapbox-gl": "^3.31.0", + "rc-slider": "^11.1.9", + "react-map-gl": "^8.1.3", + "react-markdown": "^10.1.0", + "remark-gfm": "^4.0.1" + }, + "devDependencies": { + "@supabase/supabase-js": "^2.117.2", + "@types/geojson": "^7946.0.16", + "@types/node": "^26.6.3", + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", + "react": "^19.3.0", + "react-dom": "^19.3.0", + "react-router-dom": "^7.18.4", + "typescript": "~7.0.2", + "vite": "catalog:", + "vite-plus": "catalog:" + }, + "peerDependencies": { + "@supabase/supabase-js": "^2.117.2", + "react": "^19.3.0", + "react-dom": "^19.3.0", + "react-router-dom": "^7.18.4" + } +} diff --git a/apps/web/scripts/audit-dorm-media.ts b/packages/dorm/scripts/audit-dorm-media.ts similarity index 100% rename from apps/web/scripts/audit-dorm-media.ts rename to packages/dorm/scripts/audit-dorm-media.ts diff --git a/apps/web/scripts/create_dorm_user_features.sql b/packages/dorm/scripts/create_dorm_user_features.sql similarity index 100% rename from apps/web/scripts/create_dorm_user_features.sql rename to packages/dorm/scripts/create_dorm_user_features.sql diff --git a/apps/web/scripts/migrations/add_categorized_tags.sql b/packages/dorm/scripts/migrations/add_categorized_tags.sql similarity index 100% rename from apps/web/scripts/migrations/add_categorized_tags.sql rename to packages/dorm/scripts/migrations/add_categorized_tags.sql diff --git a/apps/web/scripts/migrations/add_dorm_address.sql b/packages/dorm/scripts/migrations/add_dorm_address.sql similarity index 100% rename from apps/web/scripts/migrations/add_dorm_address.sql rename to packages/dorm/scripts/migrations/add_dorm_address.sql diff --git a/apps/web/scripts/migrations/add_dorm_comment_hidden.sql b/packages/dorm/scripts/migrations/add_dorm_comment_hidden.sql similarity index 100% rename from apps/web/scripts/migrations/add_dorm_comment_hidden.sql rename to packages/dorm/scripts/migrations/add_dorm_comment_hidden.sql diff --git a/apps/web/scripts/migrations/add_dorm_comments.sql b/packages/dorm/scripts/migrations/add_dorm_comments.sql similarity index 100% rename from apps/web/scripts/migrations/add_dorm_comments.sql rename to packages/dorm/scripts/migrations/add_dorm_comments.sql diff --git a/apps/web/scripts/migrations/add_dorm_edit_history.sql b/packages/dorm/scripts/migrations/add_dorm_edit_history.sql similarity index 100% rename from apps/web/scripts/migrations/add_dorm_edit_history.sql rename to packages/dorm/scripts/migrations/add_dorm_edit_history.sql diff --git a/apps/web/scripts/migrations/add_dorm_website.sql b/packages/dorm/scripts/migrations/add_dorm_website.sql similarity index 100% rename from apps/web/scripts/migrations/add_dorm_website.sql rename to packages/dorm/scripts/migrations/add_dorm_website.sql diff --git a/apps/web/scripts/migrations/add_floor_plan_bed_size.sql b/packages/dorm/scripts/migrations/add_floor_plan_bed_size.sql similarity index 100% rename from apps/web/scripts/migrations/add_floor_plan_bed_size.sql rename to packages/dorm/scripts/migrations/add_floor_plan_bed_size.sql diff --git a/apps/web/scripts/migrations/add_floor_plan_photo_url.sql b/packages/dorm/scripts/migrations/add_floor_plan_photo_url.sql similarity index 100% rename from apps/web/scripts/migrations/add_floor_plan_photo_url.sql rename to packages/dorm/scripts/migrations/add_floor_plan_photo_url.sql diff --git a/apps/web/scripts/migrations/create_dorms_table.sql b/packages/dorm/scripts/migrations/create_dorms_table.sql similarity index 100% rename from apps/web/scripts/migrations/create_dorms_table.sql rename to packages/dorm/scripts/migrations/create_dorms_table.sql diff --git a/apps/web/scripts/migrations/create_storage_bucket.sql b/packages/dorm/scripts/migrations/create_storage_bucket.sql similarity index 100% rename from apps/web/scripts/migrations/create_storage_bucket.sql rename to packages/dorm/scripts/migrations/create_storage_bucket.sql diff --git a/apps/web/scripts/migrations/fix_dorm_edit_history_rls.sql b/packages/dorm/scripts/migrations/fix_dorm_edit_history_rls.sql similarity index 100% rename from apps/web/scripts/migrations/fix_dorm_edit_history_rls.sql rename to packages/dorm/scripts/migrations/fix_dorm_edit_history_rls.sql diff --git a/apps/web/scripts/seed-dorms-table.ts b/packages/dorm/scripts/seed-dorms-table.ts similarity index 100% rename from apps/web/scripts/seed-dorms-table.ts rename to packages/dorm/scripts/seed-dorms-table.ts diff --git a/apps/web/scripts/validate-dorm-data.ts b/packages/dorm/scripts/validate-dorm-data.ts similarity index 100% rename from apps/web/scripts/validate-dorm-data.ts rename to packages/dorm/scripts/validate-dorm-data.ts diff --git a/packages/dorm/src/DormRoutes.tsx b/packages/dorm/src/DormRoutes.tsx new file mode 100644 index 00000000..1c47ec89 --- /dev/null +++ b/packages/dorm/src/DormRoutes.tsx @@ -0,0 +1,70 @@ +import React, { Suspense, useMemo } from "react" +import { createPortal } from "react-dom" +import { Navigate, Route, Routes, useMatch } from "react-router-dom" + +import { CompareProvider } from "./components/housing/store/CompareContext" +import { DormDataProvider } from "./components/housing/store/DormDataContext" +import { DormUserInteractionProvider } from "./components/housing/store/DormUserInteractionContext" +import { HousingProvider } from "./components/housing/store/HousingContext" +import { DormSidebar } from "./components/layout/DormSidebar" +import { useShellSlot } from "./components/layout/useShellSlot" +import { DormHost, DormHostProvider, useLayout } from "./contexts/DormHostContext" +import { Language } from "./types" + +import "./dorm.css" + +const DormListPage = React.lazy(() => import("./pages/dorms/DormListPage")) +const DormDetailPage = React.lazy(() => import("./pages/dorms/DormDetailPage")) + +export interface DormRoutesProps extends DormHost { + language: Language +} + +const DormSidebarPortal: React.FC<{ language: Language }> = ({ language }) => { + const { setSidebarSlot, favoritesIconRef } = useLayout() + const target = useShellSlot(setSidebarSlot) + const detailMatch = useMatch("/dorms/:id") + if (!target) return null + return createPortal( + , + target, + ) +} + +/** + * Everything under `/dorms`. Mount it at `/dorms/*`. + * + * Dorm state (data, filters, compare, favorites) lives and dies with this tree, + * so no other page pays for it. + */ +export const DormRoutes: React.FC = ({ language, user, requestLogin, layout }) => { + const host = useMemo(() => ({ user, requestLogin, layout }), [user, requestLogin, layout]) + const loadingText = language === "zh" ? "页面加载中..." : "Loading page..." + + return ( + + + + + + + {loadingText}} + > + + } /> + } /> + } /> + + + + + + + + ) +} diff --git a/apps/web/src/components/housing/AIChat.tsx b/packages/dorm/src/components/housing/AIChat.tsx similarity index 99% rename from apps/web/src/components/housing/AIChat.tsx rename to packages/dorm/src/components/housing/AIChat.tsx index 557c4f0c..5f1ce2c2 100644 --- a/apps/web/src/components/housing/AIChat.tsx +++ b/packages/dorm/src/components/housing/AIChat.tsx @@ -6,7 +6,7 @@ import ReactMarkdown from "react-markdown" import { useNavigate } from "react-router-dom" import remarkGfm from "remark-gfm" -import { streamChatResponse } from "../../services/ai" +import { streamChatResponse } from "../../services/host" import { Language } from "../../types" import { isDormMention, findMentionedDorms } from "../../utils/housingUtils" import { aiChatTexts } from "./i18n/dormTexts" diff --git a/apps/web/src/components/housing/DORM_DATA_AUDIT.md b/packages/dorm/src/components/housing/DORM_DATA_AUDIT.md similarity index 100% rename from apps/web/src/components/housing/DORM_DATA_AUDIT.md rename to packages/dorm/src/components/housing/DORM_DATA_AUDIT.md diff --git a/apps/web/src/components/housing/DormCard.tsx b/packages/dorm/src/components/housing/DormCard.tsx similarity index 100% rename from apps/web/src/components/housing/DormCard.tsx rename to packages/dorm/src/components/housing/DormCard.tsx diff --git a/apps/web/src/components/housing/DormComparison.tsx b/packages/dorm/src/components/housing/DormComparison.tsx similarity index 100% rename from apps/web/src/components/housing/DormComparison.tsx rename to packages/dorm/src/components/housing/DormComparison.tsx diff --git a/apps/web/src/components/housing/DormDetail.tsx b/packages/dorm/src/components/housing/DormDetail.tsx similarity index 99% rename from apps/web/src/components/housing/DormDetail.tsx rename to packages/dorm/src/components/housing/DormDetail.tsx index 46b073aa..dada6057 100644 --- a/apps/web/src/components/housing/DormDetail.tsx +++ b/packages/dorm/src/components/housing/DormDetail.tsx @@ -3,8 +3,7 @@ import { ArrowLeft, Heart, Pencil } from "lucide-react" import React, { useEffect, useState } from "react" import { useParams, useNavigate, useLocation } from "react-router-dom" -import { useAuth } from "../../contexts/AuthContext" -import { useLayout } from "../../contexts/LayoutContext" +import { useAuth, useLayout } from "../../contexts/DormHostContext" import { dormService } from "../../services/dormService" import { Language } from "../../types" import { getStorageBathroomScope, normalizeFloorPlan } from "../../utils/roomOptions" diff --git a/apps/web/src/components/housing/DormDetailFloorPlans.tsx b/packages/dorm/src/components/housing/DormDetailFloorPlans.tsx similarity index 100% rename from apps/web/src/components/housing/DormDetailFloorPlans.tsx rename to packages/dorm/src/components/housing/DormDetailFloorPlans.tsx diff --git a/apps/web/src/components/housing/DormDetailGallery.tsx b/packages/dorm/src/components/housing/DormDetailGallery.tsx similarity index 100% rename from apps/web/src/components/housing/DormDetailGallery.tsx rename to packages/dorm/src/components/housing/DormDetailGallery.tsx diff --git a/apps/web/src/components/housing/DormDetailHeader.tsx b/packages/dorm/src/components/housing/DormDetailHeader.tsx similarity index 100% rename from apps/web/src/components/housing/DormDetailHeader.tsx rename to packages/dorm/src/components/housing/DormDetailHeader.tsx diff --git a/apps/web/src/components/housing/DormDetailInfo.tsx b/packages/dorm/src/components/housing/DormDetailInfo.tsx similarity index 100% rename from apps/web/src/components/housing/DormDetailInfo.tsx rename to packages/dorm/src/components/housing/DormDetailInfo.tsx diff --git a/apps/web/src/components/housing/DormDetailReviews.tsx b/packages/dorm/src/components/housing/DormDetailReviews.tsx similarity index 100% rename from apps/web/src/components/housing/DormDetailReviews.tsx rename to packages/dorm/src/components/housing/DormDetailReviews.tsx diff --git a/apps/web/src/components/housing/DormEditPanel.tsx b/packages/dorm/src/components/housing/DormEditPanel.tsx similarity index 100% rename from apps/web/src/components/housing/DormEditPanel.tsx rename to packages/dorm/src/components/housing/DormEditPanel.tsx diff --git a/apps/web/src/components/housing/DormList.tsx b/packages/dorm/src/components/housing/DormList.tsx similarity index 99% rename from apps/web/src/components/housing/DormList.tsx rename to packages/dorm/src/components/housing/DormList.tsx index 609482ee..5f142c33 100644 --- a/apps/web/src/components/housing/DormList.tsx +++ b/packages/dorm/src/components/housing/DormList.tsx @@ -3,7 +3,7 @@ import { GitCompareArrows, X } from "lucide-react" import React, { Suspense, useCallback } from "react" import { useNavigate } from "react-router-dom" -import { useAuth } from "../../contexts/AuthContext" +import { useAuth } from "../../contexts/DormHostContext" import { Language } from "../../types" import { SHOW_COMMENTS } from "./constants/featureFlags" import DormGrid from "./dorm-list/DormGrid" diff --git a/apps/web/src/components/housing/DormMap.tsx b/packages/dorm/src/components/housing/DormMap.tsx similarity index 99% rename from apps/web/src/components/housing/DormMap.tsx rename to packages/dorm/src/components/housing/DormMap.tsx index 837c13ab..013aeadb 100644 --- a/apps/web/src/components/housing/DormMap.tsx +++ b/packages/dorm/src/components/housing/DormMap.tsx @@ -1,3 +1,6 @@ +// mapbox-gl's types use the global GeoJSON namespace. Referencing it here gives it +// to every program that compiles this file, the host app's included. +/// import mapboxgl from "mapbox-gl" import React, { Component, diff --git a/apps/web/src/components/housing/FilterModal.tsx b/packages/dorm/src/components/housing/FilterModal.tsx similarity index 100% rename from apps/web/src/components/housing/FilterModal.tsx rename to packages/dorm/src/components/housing/FilterModal.tsx diff --git a/apps/web/src/components/housing/ImageLightbox.tsx b/packages/dorm/src/components/housing/ImageLightbox.tsx similarity index 100% rename from apps/web/src/components/housing/ImageLightbox.tsx rename to packages/dorm/src/components/housing/ImageLightbox.tsx diff --git a/apps/web/src/components/housing/README.md b/packages/dorm/src/components/housing/README.md similarity index 100% rename from apps/web/src/components/housing/README.md rename to packages/dorm/src/components/housing/README.md diff --git a/apps/web/src/components/housing/SortingDropdown.tsx b/packages/dorm/src/components/housing/SortingDropdown.tsx similarity index 100% rename from apps/web/src/components/housing/SortingDropdown.tsx rename to packages/dorm/src/components/housing/SortingDropdown.tsx diff --git a/apps/web/src/components/housing/constants/chat.ts b/packages/dorm/src/components/housing/constants/chat.ts similarity index 100% rename from apps/web/src/components/housing/constants/chat.ts rename to packages/dorm/src/components/housing/constants/chat.ts diff --git a/apps/web/src/components/housing/constants/dormData.ts b/packages/dorm/src/components/housing/constants/dormData.ts similarity index 100% rename from apps/web/src/components/housing/constants/dormData.ts rename to packages/dorm/src/components/housing/constants/dormData.ts diff --git a/apps/web/src/components/housing/constants/dormOfficialOverrideUtils.ts b/packages/dorm/src/components/housing/constants/dormOfficialOverrideUtils.ts similarity index 100% rename from apps/web/src/components/housing/constants/dormOfficialOverrideUtils.ts rename to packages/dorm/src/components/housing/constants/dormOfficialOverrideUtils.ts diff --git a/apps/web/src/components/housing/constants/dormOfficialOverrides.ts b/packages/dorm/src/components/housing/constants/dormOfficialOverrides.ts similarity index 100% rename from apps/web/src/components/housing/constants/dormOfficialOverrides.ts rename to packages/dorm/src/components/housing/constants/dormOfficialOverrides.ts diff --git a/apps/web/src/components/housing/constants/dormOfficialOverridesPch.ts b/packages/dorm/src/components/housing/constants/dormOfficialOverridesPch.ts similarity index 100% rename from apps/web/src/components/housing/constants/dormOfficialOverridesPch.ts rename to packages/dorm/src/components/housing/constants/dormOfficialOverridesPch.ts diff --git a/apps/web/src/components/housing/constants/dormOfficialOverridesUrhNorth.ts b/packages/dorm/src/components/housing/constants/dormOfficialOverridesUrhNorth.ts similarity index 100% rename from apps/web/src/components/housing/constants/dormOfficialOverridesUrhNorth.ts rename to packages/dorm/src/components/housing/constants/dormOfficialOverridesUrhNorth.ts diff --git a/apps/web/src/components/housing/constants/dormOfficialOverridesUrhSouth.ts b/packages/dorm/src/components/housing/constants/dormOfficialOverridesUrhSouth.ts similarity index 100% rename from apps/web/src/components/housing/constants/dormOfficialOverridesUrhSouth.ts rename to packages/dorm/src/components/housing/constants/dormOfficialOverridesUrhSouth.ts diff --git a/apps/web/src/components/housing/constants/featureFlags.ts b/packages/dorm/src/components/housing/constants/featureFlags.ts similarity index 100% rename from apps/web/src/components/housing/constants/featureFlags.ts rename to packages/dorm/src/components/housing/constants/featureFlags.ts diff --git a/apps/web/src/components/housing/constants/filters.ts b/packages/dorm/src/components/housing/constants/filters.ts similarity index 100% rename from apps/web/src/components/housing/constants/filters.ts rename to packages/dorm/src/components/housing/constants/filters.ts diff --git a/apps/web/src/components/housing/constants/googleReviews.ts b/packages/dorm/src/components/housing/constants/googleReviews.ts similarity index 100% rename from apps/web/src/components/housing/constants/googleReviews.ts rename to packages/dorm/src/components/housing/constants/googleReviews.ts diff --git a/apps/web/src/components/housing/constants/index.ts b/packages/dorm/src/components/housing/constants/index.ts similarity index 100% rename from apps/web/src/components/housing/constants/index.ts rename to packages/dorm/src/components/housing/constants/index.ts diff --git a/apps/web/src/components/housing/constants/mapData.ts b/packages/dorm/src/components/housing/constants/mapData.ts similarity index 100% rename from apps/web/src/components/housing/constants/mapData.ts rename to packages/dorm/src/components/housing/constants/mapData.ts diff --git a/apps/web/src/components/housing/constants/metadata.ts b/packages/dorm/src/components/housing/constants/metadata.ts similarity index 100% rename from apps/web/src/components/housing/constants/metadata.ts rename to packages/dorm/src/components/housing/constants/metadata.ts diff --git a/apps/web/src/components/housing/constants/pricing.ts b/packages/dorm/src/components/housing/constants/pricing.ts similarity index 100% rename from apps/web/src/components/housing/constants/pricing.ts rename to packages/dorm/src/components/housing/constants/pricing.ts diff --git a/apps/web/src/components/housing/dorm-list/DormGrid.tsx b/packages/dorm/src/components/housing/dorm-list/DormGrid.tsx similarity index 100% rename from apps/web/src/components/housing/dorm-list/DormGrid.tsx rename to packages/dorm/src/components/housing/dorm-list/DormGrid.tsx diff --git a/apps/web/src/components/housing/dorm-list/DormListHeader.tsx b/packages/dorm/src/components/housing/dorm-list/DormListHeader.tsx similarity index 100% rename from apps/web/src/components/housing/dorm-list/DormListHeader.tsx rename to packages/dorm/src/components/housing/dorm-list/DormListHeader.tsx diff --git a/apps/web/src/components/housing/dorm-list/DormListMapPane.tsx b/packages/dorm/src/components/housing/dorm-list/DormListMapPane.tsx similarity index 100% rename from apps/web/src/components/housing/dorm-list/DormListMapPane.tsx rename to packages/dorm/src/components/housing/dorm-list/DormListMapPane.tsx diff --git a/packages/dorm/src/components/housing/dorm-list/DormListMobileHeader.tsx b/packages/dorm/src/components/housing/dorm-list/DormListMobileHeader.tsx new file mode 100644 index 00000000..3079c325 --- /dev/null +++ b/packages/dorm/src/components/housing/dorm-list/DormListMobileHeader.tsx @@ -0,0 +1,144 @@ +import { Search, SlidersHorizontal, Map as MapIcon, List, ArrowUpDown } from "lucide-react" +import * as React from "react" +import { createPortal } from "react-dom" + +import { useLayout } from "../../../contexts/DormHostContext" +import { Language } from "../../../types" +import { useShellSlot } from "../../layout/useShellSlot" +import { useDormFilterBadge } from "../hooks/useDormFilterBadge" +import { useHousingFilters } from "../store/HousingContext" + +const SORT_OPTIONS = [ + { value: "name-asc", label: "A-Z" }, + { value: "name-desc", label: "Z-A" }, + { value: "price-asc", label: "Price ↑" }, + { value: "price-desc", label: "Price ↓" }, +] as const + +const SortDropdownMobile: React.FC<{ + sortBy: string + onSortChange: (v: string) => void +}> = ({ sortBy, onSortChange }) => { + const [open, setOpen] = React.useState(false) + const ref = React.useRef(null) + + React.useEffect(() => { + const handler = (e: MouseEvent) => { + if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false) + } + document.addEventListener("mousedown", handler) + return () => document.removeEventListener("mousedown", handler) + }, []) + + return ( +
+ + {open && ( +
+ {SORT_OPTIONS.map((o) => ( + + ))} +
+ )} +
+ ) +} + +const DormListMobileHeader: React.FC<{ language: Language }> = ({ language }) => { + const { + searchTerm, + setSearchTerm, + setIsFilterModalOpen, + viewMode, + setViewMode, + sortBy, + setSortBy, + } = useHousingFilters() + const { hasActiveDormFilters, activeDormFilterCount } = useDormFilterBadge() + + return ( +
+
+ + setSearchTerm(event.target.value)} + /> +
+
+ + {hasActiveDormFilters && ( +
+ {activeDormFilterCount} +
+ )} +
+ + +
+ ) +} + +/** Search, filter, sort, and view toggle in the shell's mobile header. */ +export const DormListMobileHeaderPortal: React.FC<{ language: Language }> = ({ language }) => { + const { setMobileHeaderSlot } = useLayout() + const target = useShellSlot(setMobileHeaderSlot) + return target ? createPortal(, target) : null +} diff --git a/apps/web/src/components/housing/dorm-list/EmptyStates.tsx b/packages/dorm/src/components/housing/dorm-list/EmptyStates.tsx similarity index 100% rename from apps/web/src/components/housing/dorm-list/EmptyStates.tsx rename to packages/dorm/src/components/housing/dorm-list/EmptyStates.tsx diff --git a/apps/web/src/components/housing/dorm-list/FavoriteFlyEffect.tsx b/packages/dorm/src/components/housing/dorm-list/FavoriteFlyEffect.tsx similarity index 100% rename from apps/web/src/components/housing/dorm-list/FavoriteFlyEffect.tsx rename to packages/dorm/src/components/housing/dorm-list/FavoriteFlyEffect.tsx diff --git a/apps/web/src/components/housing/dorm-list/MapCarousel.tsx b/packages/dorm/src/components/housing/dorm-list/MapCarousel.tsx similarity index 100% rename from apps/web/src/components/housing/dorm-list/MapCarousel.tsx rename to packages/dorm/src/components/housing/dorm-list/MapCarousel.tsx diff --git a/apps/web/src/components/housing/dorm-list/favoriteConstants.ts b/packages/dorm/src/components/housing/dorm-list/favoriteConstants.ts similarity index 100% rename from apps/web/src/components/housing/dorm-list/favoriteConstants.ts rename to packages/dorm/src/components/housing/dorm-list/favoriteConstants.ts diff --git a/apps/web/src/components/housing/dorm-list/filtering.ts b/packages/dorm/src/components/housing/dorm-list/filtering.ts similarity index 100% rename from apps/web/src/components/housing/dorm-list/filtering.ts rename to packages/dorm/src/components/housing/dorm-list/filtering.ts diff --git a/apps/web/src/components/housing/dorm-list/types.ts b/packages/dorm/src/components/housing/dorm-list/types.ts similarity index 100% rename from apps/web/src/components/housing/dorm-list/types.ts rename to packages/dorm/src/components/housing/dorm-list/types.ts diff --git a/apps/web/src/components/housing/dorm-list/useDormListController.ts b/packages/dorm/src/components/housing/dorm-list/useDormListController.ts similarity index 99% rename from apps/web/src/components/housing/dorm-list/useDormListController.ts rename to packages/dorm/src/components/housing/dorm-list/useDormListController.ts index edcde45d..155dec3e 100644 --- a/apps/web/src/components/housing/dorm-list/useDormListController.ts +++ b/packages/dorm/src/components/housing/dorm-list/useDormListController.ts @@ -1,7 +1,7 @@ import { useLayoutEffect, useMemo, useRef, useState } from "react" import { useNavigate } from "react-router-dom" -import { useLayout } from "../../../contexts/LayoutContext" +import { useLayout } from "../../../contexts/DormHostContext" import { Language } from "../../../types" import { getPriceRangeFromData } from "../constants/pricing" import { useDormData } from "../store/DormDataContext" diff --git a/apps/web/src/components/housing/dorm-map/layers.ts b/packages/dorm/src/components/housing/dorm-map/layers.ts similarity index 100% rename from apps/web/src/components/housing/dorm-map/layers.ts rename to packages/dorm/src/components/housing/dorm-map/layers.ts diff --git a/apps/web/src/components/housing/dorm-map/mapAssets.ts b/packages/dorm/src/components/housing/dorm-map/mapAssets.ts similarity index 100% rename from apps/web/src/components/housing/dorm-map/mapAssets.ts rename to packages/dorm/src/components/housing/dorm-map/mapAssets.ts diff --git a/apps/web/src/components/housing/dorm-map/mapConstants.ts b/packages/dorm/src/components/housing/dorm-map/mapConstants.ts similarity index 100% rename from apps/web/src/components/housing/dorm-map/mapConstants.ts rename to packages/dorm/src/components/housing/dorm-map/mapConstants.ts diff --git a/apps/web/src/components/housing/dorm-map/mapFeatureBuilders.ts b/packages/dorm/src/components/housing/dorm-map/mapFeatureBuilders.ts similarity index 100% rename from apps/web/src/components/housing/dorm-map/mapFeatureBuilders.ts rename to packages/dorm/src/components/housing/dorm-map/mapFeatureBuilders.ts diff --git a/apps/web/src/components/housing/dorm-map/types.ts b/packages/dorm/src/components/housing/dorm-map/types.ts similarity index 100% rename from apps/web/src/components/housing/dorm-map/types.ts rename to packages/dorm/src/components/housing/dorm-map/types.ts diff --git a/apps/web/src/components/housing/edit-panel/ContentTab.tsx b/packages/dorm/src/components/housing/edit-panel/ContentTab.tsx similarity index 100% rename from apps/web/src/components/housing/edit-panel/ContentTab.tsx rename to packages/dorm/src/components/housing/edit-panel/ContentTab.tsx diff --git a/apps/web/src/components/housing/edit-panel/DetailsTab.tsx b/packages/dorm/src/components/housing/edit-panel/DetailsTab.tsx similarity index 100% rename from apps/web/src/components/housing/edit-panel/DetailsTab.tsx rename to packages/dorm/src/components/housing/edit-panel/DetailsTab.tsx diff --git a/apps/web/src/components/housing/edit-panel/DormEditPanelShell.tsx b/packages/dorm/src/components/housing/edit-panel/DormEditPanelShell.tsx similarity index 100% rename from apps/web/src/components/housing/edit-panel/DormEditPanelShell.tsx rename to packages/dorm/src/components/housing/edit-panel/DormEditPanelShell.tsx diff --git a/apps/web/src/components/housing/edit-panel/EditPanelFields.tsx b/packages/dorm/src/components/housing/edit-panel/EditPanelFields.tsx similarity index 100% rename from apps/web/src/components/housing/edit-panel/EditPanelFields.tsx rename to packages/dorm/src/components/housing/edit-panel/EditPanelFields.tsx diff --git a/apps/web/src/components/housing/edit-panel/HistoryTab.tsx b/packages/dorm/src/components/housing/edit-panel/HistoryTab.tsx similarity index 100% rename from apps/web/src/components/housing/edit-panel/HistoryTab.tsx rename to packages/dorm/src/components/housing/edit-panel/HistoryTab.tsx diff --git a/apps/web/src/components/housing/edit-panel/MediaTab.tsx b/packages/dorm/src/components/housing/edit-panel/MediaTab.tsx similarity index 100% rename from apps/web/src/components/housing/edit-panel/MediaTab.tsx rename to packages/dorm/src/components/housing/edit-panel/MediaTab.tsx diff --git a/apps/web/src/components/housing/edit-panel/TagsTab.tsx b/packages/dorm/src/components/housing/edit-panel/TagsTab.tsx similarity index 100% rename from apps/web/src/components/housing/edit-panel/TagsTab.tsx rename to packages/dorm/src/components/housing/edit-panel/TagsTab.tsx diff --git a/apps/web/src/components/housing/edit-panel/editPanelText.ts b/packages/dorm/src/components/housing/edit-panel/editPanelText.ts similarity index 100% rename from apps/web/src/components/housing/edit-panel/editPanelText.ts rename to packages/dorm/src/components/housing/edit-panel/editPanelText.ts diff --git a/apps/web/src/components/housing/edit-panel/useDormEditForm.ts b/packages/dorm/src/components/housing/edit-panel/useDormEditForm.ts similarity index 99% rename from apps/web/src/components/housing/edit-panel/useDormEditForm.ts rename to packages/dorm/src/components/housing/edit-panel/useDormEditForm.ts index 88f6ecf2..37e1c72b 100644 --- a/apps/web/src/components/housing/edit-panel/useDormEditForm.ts +++ b/packages/dorm/src/components/housing/edit-panel/useDormEditForm.ts @@ -1,6 +1,6 @@ import { useLayoutEffect, useMemo, useRef, useState } from "react" -import { useAuth } from "../../../contexts/AuthContext" +import { useAuth } from "../../../contexts/DormHostContext" import { buildSummary, DormUpdate, diff --git a/apps/web/src/components/housing/filter-modal/AmenitiesSection.tsx b/packages/dorm/src/components/housing/filter-modal/AmenitiesSection.tsx similarity index 100% rename from apps/web/src/components/housing/filter-modal/AmenitiesSection.tsx rename to packages/dorm/src/components/housing/filter-modal/AmenitiesSection.tsx diff --git a/apps/web/src/components/housing/filter-modal/ChipSection.tsx b/packages/dorm/src/components/housing/filter-modal/ChipSection.tsx similarity index 100% rename from apps/web/src/components/housing/filter-modal/ChipSection.tsx rename to packages/dorm/src/components/housing/filter-modal/ChipSection.tsx diff --git a/apps/web/src/components/housing/filter-modal/HousingTypeSection.tsx b/packages/dorm/src/components/housing/filter-modal/HousingTypeSection.tsx similarity index 100% rename from apps/web/src/components/housing/filter-modal/HousingTypeSection.tsx rename to packages/dorm/src/components/housing/filter-modal/HousingTypeSection.tsx diff --git a/apps/web/src/components/housing/filter-modal/PriceSection.tsx b/packages/dorm/src/components/housing/filter-modal/PriceSection.tsx similarity index 100% rename from apps/web/src/components/housing/filter-modal/PriceSection.tsx rename to packages/dorm/src/components/housing/filter-modal/PriceSection.tsx diff --git a/apps/web/src/components/housing/filter-modal/RoomTypeSection.tsx b/packages/dorm/src/components/housing/filter-modal/RoomTypeSection.tsx similarity index 100% rename from apps/web/src/components/housing/filter-modal/RoomTypeSection.tsx rename to packages/dorm/src/components/housing/filter-modal/RoomTypeSection.tsx diff --git a/apps/web/src/components/housing/filter-modal/TagFilterSection.tsx b/packages/dorm/src/components/housing/filter-modal/TagFilterSection.tsx similarity index 100% rename from apps/web/src/components/housing/filter-modal/TagFilterSection.tsx rename to packages/dorm/src/components/housing/filter-modal/TagFilterSection.tsx diff --git a/apps/web/src/components/housing/filter-modal/modalText.ts b/packages/dorm/src/components/housing/filter-modal/modalText.ts similarity index 100% rename from apps/web/src/components/housing/filter-modal/modalText.ts rename to packages/dorm/src/components/housing/filter-modal/modalText.ts diff --git a/apps/web/src/components/housing/hooks/useDormCommentStats.ts b/packages/dorm/src/components/housing/hooks/useDormCommentStats.ts similarity index 100% rename from apps/web/src/components/housing/hooks/useDormCommentStats.ts rename to packages/dorm/src/components/housing/hooks/useDormCommentStats.ts diff --git a/apps/web/src/components/housing/hooks/useDormComments.ts b/packages/dorm/src/components/housing/hooks/useDormComments.ts similarity index 98% rename from apps/web/src/components/housing/hooks/useDormComments.ts rename to packages/dorm/src/components/housing/hooks/useDormComments.ts index df12629a..a98cd53f 100644 --- a/apps/web/src/components/housing/hooks/useDormComments.ts +++ b/packages/dorm/src/components/housing/hooks/useDormComments.ts @@ -1,6 +1,6 @@ import { useState, useEffect, useCallback } from "react" -import { useAuth } from "../../../contexts/AuthContext" +import { useAuth } from "../../../contexts/DormHostContext" import { dormCommentsService, DormComment } from "../../../services/dormCommentsService" import { SHOW_COMMENTS, SHOW_GOOGLE_REVIEWS } from "../constants/featureFlags" diff --git a/apps/web/src/components/housing/hooks/useDormFilterBadge.ts b/packages/dorm/src/components/housing/hooks/useDormFilterBadge.ts similarity index 100% rename from apps/web/src/components/housing/hooks/useDormFilterBadge.ts rename to packages/dorm/src/components/housing/hooks/useDormFilterBadge.ts diff --git a/apps/web/src/components/housing/hooks/useDormUserInteraction.ts b/packages/dorm/src/components/housing/hooks/useDormUserInteraction.ts similarity index 99% rename from apps/web/src/components/housing/hooks/useDormUserInteraction.ts rename to packages/dorm/src/components/housing/hooks/useDormUserInteraction.ts index 5e2fda5f..979a8405 100644 --- a/apps/web/src/components/housing/hooks/useDormUserInteraction.ts +++ b/packages/dorm/src/components/housing/hooks/useDormUserInteraction.ts @@ -1,6 +1,6 @@ import { useState, useEffect, useCallback, useMemo } from "react" -import { useAuth } from "../../../contexts/AuthContext" +import { useAuth } from "../../../contexts/DormHostContext" import { dormFavoritesService, type DormFavorite } from "../../../services/dormFavoritesService" import { dormViewingService } from "../../../services/dormViewingService" import { useDormData } from "../store/DormDataContext" diff --git a/apps/web/src/components/housing/i18n/dormTexts.ts b/packages/dorm/src/components/housing/i18n/dormTexts.ts similarity index 100% rename from apps/web/src/components/housing/i18n/dormTexts.ts rename to packages/dorm/src/components/housing/i18n/dormTexts.ts diff --git a/apps/web/src/components/housing/store/CompareContext.tsx b/packages/dorm/src/components/housing/store/CompareContext.tsx similarity index 100% rename from apps/web/src/components/housing/store/CompareContext.tsx rename to packages/dorm/src/components/housing/store/CompareContext.tsx diff --git a/apps/web/src/components/housing/store/DormDataContext.tsx b/packages/dorm/src/components/housing/store/DormDataContext.tsx similarity index 100% rename from apps/web/src/components/housing/store/DormDataContext.tsx rename to packages/dorm/src/components/housing/store/DormDataContext.tsx diff --git a/apps/web/src/components/housing/store/DormUserInteractionContext.tsx b/packages/dorm/src/components/housing/store/DormUserInteractionContext.tsx similarity index 100% rename from apps/web/src/components/housing/store/DormUserInteractionContext.tsx rename to packages/dorm/src/components/housing/store/DormUserInteractionContext.tsx diff --git a/apps/web/src/components/housing/store/HousingContext.tsx b/packages/dorm/src/components/housing/store/HousingContext.tsx similarity index 100% rename from apps/web/src/components/housing/store/HousingContext.tsx rename to packages/dorm/src/components/housing/store/HousingContext.tsx diff --git a/apps/web/src/components/housing/types/index.ts b/packages/dorm/src/components/housing/types/index.ts similarity index 100% rename from apps/web/src/components/housing/types/index.ts rename to packages/dorm/src/components/housing/types/index.ts diff --git a/apps/web/src/components/layout/DormSidebar.tsx b/packages/dorm/src/components/layout/DormSidebar.tsx similarity index 100% rename from apps/web/src/components/layout/DormSidebar.tsx rename to packages/dorm/src/components/layout/DormSidebar.tsx diff --git a/packages/dorm/src/components/layout/useShellSlot.tsx b/packages/dorm/src/components/layout/useShellSlot.tsx new file mode 100644 index 00000000..9d953430 --- /dev/null +++ b/packages/dorm/src/components/layout/useShellSlot.tsx @@ -0,0 +1,21 @@ +import { ReactNode, useLayoutEffect, useState } from "react" + +/** + * Claims a slot in the host shell and returns a DOM node to portal into. + * + * Nodes handed to a shell slot render in the shell's tree, out of reach of the + * dorm providers. Portaling into a placeholder instead keeps dorm context and + * state, and `contents` lets the portaled children lay out as the slot's own. + * The layout effect fills the slot before paint, so the shell default never + * flashes. + */ +export const useShellSlot = (setSlot: (node: ReactNode | null) => void): HTMLElement | null => { + const [target, setTarget] = useState(null) + + useLayoutEffect(() => { + setSlot(
) + return () => setSlot(null) + }, [setSlot]) + + return target +} diff --git a/apps/web/src/constants/housing.ts b/packages/dorm/src/constants/housing.ts similarity index 100% rename from apps/web/src/constants/housing.ts rename to packages/dorm/src/constants/housing.ts diff --git a/packages/dorm/src/contexts/DormHostContext.tsx b/packages/dorm/src/contexts/DormHostContext.tsx new file mode 100644 index 00000000..b06b81fe --- /dev/null +++ b/packages/dorm/src/contexts/DormHostContext.tsx @@ -0,0 +1,52 @@ +import React, { createContext, ReactNode, RefObject, useContext } from "react" + +/** The signed-in user fields dorm features read. The host's user type is a superset. */ +export interface DormUser { + id: string + email: string + isAdmin: boolean +} + +/** The parts of the host shell the dorm UI drives. */ +export interface DormLayoutBridge { + isSidebarOpen: boolean + /** Flying-heart target while the sidebar is open. */ + favoritesIconRef: RefObject + /** Flying-heart target while the sidebar is closed (md+). */ + sidebarToggleButtonRef: RefObject + /** Flying-heart target while the sidebar is closed ( + /** Replaces the shell's mobile header content; null restores the default. */ + setMobileHeaderSlot: (node: ReactNode | null) => void + /** Adds content below the shell's primary nav; null removes it. */ + setSidebarSlot: (node: ReactNode | null) => void +} + +export interface DormHost { + user: DormUser | null + /** Sends a guest to the host's login screen. */ + requestLogin: () => void + layout: DormLayoutBridge +} + +const DormHostContext = createContext(null) + +export const DormHostProvider: React.FC<{ value: DormHost; children: ReactNode }> = ({ + value, + children, +}) => {children} + +const useDormHost = (): DormHost => { + const ctx = useContext(DormHostContext) + if (!ctx) { + throw new Error("@iguide/dorm: dorm components must render inside DormRoutes") + } + return ctx +} + +export const useAuth = (): Pick => { + const { user, requestLogin } = useDormHost() + return { user, requestLogin } +} + +export const useLayout = (): DormLayoutBridge => useDormHost().layout diff --git a/packages/dorm/src/dorm.css b/packages/dorm/src/dorm.css new file mode 100644 index 00000000..21f1d4fa --- /dev/null +++ b/packages/dorm/src/dorm.css @@ -0,0 +1,24 @@ +/* Reduce paint/render cost while scrolling long dorm lists. */ +.dorm-card { + content-visibility: auto; + contain-intrinsic-size: 420px; +} + +/* Highlight glow effect for active map marker */ +@keyframes marker-glow { + 0%, + 100% { + box-shadow: + 0 0 20px rgba(255, 95, 5, 0.5), + 0 0 30px rgba(255, 95, 5, 0.3); + } + 50% { + box-shadow: + 0 0 25px rgba(255, 95, 5, 0.6), + 0 0 35px rgba(255, 95, 5, 0.4); + } +} + +.marker-glow { + animation: marker-glow 2s ease-in-out infinite; +} diff --git a/packages/dorm/src/index.ts b/packages/dorm/src/index.ts new file mode 100644 index 00000000..97d5d66d --- /dev/null +++ b/packages/dorm/src/index.ts @@ -0,0 +1,7 @@ +// The package's whole public surface. Hosts import from here, never from deeper paths. +export { DormRoutes } from "./DormRoutes" +export type { DormRoutesProps } from "./DormRoutes" +export type { DormHost, DormLayoutBridge, DormUser } from "./contexts/DormHostContext" +export { configureDormServices } from "./services/host" +export type { ChatHistoryItem, DormServices, StreamChatResponseFn } from "./services/host" +export type { Language } from "./types" diff --git a/apps/web/src/pages/dorms/DormDetailPage.tsx b/packages/dorm/src/pages/dorms/DormDetailPage.tsx similarity index 100% rename from apps/web/src/pages/dorms/DormDetailPage.tsx rename to packages/dorm/src/pages/dorms/DormDetailPage.tsx diff --git a/apps/web/src/pages/dorms/DormListPage.tsx b/packages/dorm/src/pages/dorms/DormListPage.tsx similarity index 73% rename from apps/web/src/pages/dorms/DormListPage.tsx rename to packages/dorm/src/pages/dorms/DormListPage.tsx index f751030c..40e21f9c 100644 --- a/apps/web/src/pages/dorms/DormListPage.tsx +++ b/packages/dorm/src/pages/dorms/DormListPage.tsx @@ -1,6 +1,7 @@ import React from "react" import AIChat from "../../components/housing/AIChat" +import { DormListMobileHeaderPortal } from "../../components/housing/dorm-list/DormListMobileHeader" import DormList from "../../components/housing/DormList" import { Language } from "../../types" @@ -11,6 +12,7 @@ interface DormListPageProps { const DormListPage: React.FC = ({ language }) => { return ( <> + diff --git a/apps/web/src/services/dormAdminService.ts b/packages/dorm/src/services/dormAdminService.ts similarity index 92% rename from apps/web/src/services/dormAdminService.ts rename to packages/dorm/src/services/dormAdminService.ts index 9d62a475..6bc920eb 100644 --- a/apps/web/src/services/dormAdminService.ts +++ b/packages/dorm/src/services/dormAdminService.ts @@ -1,7 +1,7 @@ import { Dorm } from "../components/housing/types/index" import { getDormPriceRange, sanitizeFloorPlansForStorage } from "../utils/dormData" import { getPersistedBathroomType } from "../utils/roomOptions" -import { supabase } from "./supabase" +import { getSupabase } from "./host" const TABLE = "dorms" @@ -113,7 +113,7 @@ export function buildSummary(dorm: Dorm, updates: DormUpdate): string { * Fetch the last 20 edit history entries for a dorm, newest first. */ async function getEditHistory(dormId: string): Promise { - const { data, error } = await supabase + const { data, error } = await getSupabase() .from("dorm_edit_history") .select("*") .eq("dorm_id", dormId) @@ -136,7 +136,7 @@ async function logEdit( summary: string, snapshotBefore: Record, ): Promise { - const { error } = await supabase.from("dorm_edit_history").insert({ + const { error } = await getSupabase().from("dorm_edit_history").insert({ dorm_id: dormId, dorm_name: dormName, changed_by: changedBy, @@ -161,7 +161,7 @@ async function restoreSnapshot(dormId: string, entry: EditHistoryEntry): Promise : value } } - const { error } = await supabase.from(TABLE).update(safeSnapshot).eq("id", dormId) + const { error } = await getSupabase().from(TABLE).update(safeSnapshot).eq("id", dormId) if (error) { console.error("[dormAdminService] restoreSnapshot error:", error) return false @@ -195,7 +195,7 @@ async function updateDorm(dormId: string, updates: DormUpdate): Promise { - const { error: refreshError } = await supabase.auth.refreshSession() + const { error: refreshError } = await getSupabase().auth.refreshSession() if (refreshError) { console.warn("[dormAdminService] refreshSession warning:", refreshError.message) } const { data: { session }, - } = await supabase.auth.getSession() + } = await getSupabase().auth.getSession() if (!session) { return { publicUrl: null, @@ -282,11 +282,13 @@ async function uploadDormImage(file: File): Promise { const fileName = `${Date.now()}-${Math.random().toString(36).substring(2, 9)}.${fileExt}` const filePath = `user_uploads/${fileName}` - const { error: uploadError } = await supabase.storage.from("dorm-images").upload(filePath, file, { - cacheControl: "3600", - upsert: false, - contentType: file.type || undefined, - }) + const { error: uploadError } = await getSupabase() + .storage.from("dorm-images") + .upload(filePath, file, { + cacheControl: "3600", + upsert: false, + contentType: file.type || undefined, + }) if (uploadError) { console.error("[dormAdminService] uploadDormImage error:", uploadError) @@ -296,7 +298,7 @@ async function uploadDormImage(file: File): Promise { } } - const { data } = supabase.storage.from("dorm-images").getPublicUrl(filePath) + const { data } = getSupabase().storage.from("dorm-images").getPublicUrl(filePath) if (!data?.publicUrl) { return { publicUrl: null, diff --git a/apps/web/src/services/dormCommentsService.ts b/packages/dorm/src/services/dormCommentsService.ts similarity index 87% rename from apps/web/src/services/dormCommentsService.ts rename to packages/dorm/src/services/dormCommentsService.ts index 2e3484f0..b18a4d03 100644 --- a/apps/web/src/services/dormCommentsService.ts +++ b/packages/dorm/src/services/dormCommentsService.ts @@ -1,5 +1,4 @@ -import { authService } from "./authService" -import { supabase } from "./supabase" +import { getCurrentUser, getSupabase } from "./host" export interface DormComment { id: string @@ -77,11 +76,13 @@ export interface DormCommentStats { export const dormCommentsService = { async getAllDormStats(): Promise> { - let { data, error } = await supabase.from("dorm_comments").select("dorm_id, dorm_vote, hidden") + let { data, error } = await getSupabase() + .from("dorm_comments") + .select("dorm_id, dorm_vote, hidden") // Fall back if add_dorm_comment_hidden.sql has not been run yet (42703). if (error?.code === "42703") { - ;({ data, error } = await supabase.from("dorm_comments").select("dorm_id, dorm_vote")) + ;({ data, error } = await getSupabase().from("dorm_comments").select("dorm_id, dorm_vote")) } if (error) { @@ -112,9 +113,9 @@ export const dormCommentsService = { }, async getComments(dormId: string): Promise { - const user = await authService.getCurrentUser() + const user = await getCurrentUser() - const { data, error } = await supabase + const { data, error } = await getSupabase() .from("dorm_comments") .select(`*, dorm_comment_votes(vote, user_id)`) .eq("dorm_id", dormId) @@ -141,12 +142,12 @@ export const dormCommentsService = { content: string, dormVote: 1 | -1 | null, ): Promise { - const user = await authService.getCurrentUser() + const user = await getCurrentUser() if (!user) throw new Error("User not authenticated") const display_name = user.email?.split("@")[0] ?? "Anonymous" - const { data, error } = await supabase + const { data, error } = await getSupabase() .from("dorm_comments") .upsert( { @@ -174,10 +175,10 @@ export const dormCommentsService = { }, async deleteComment(commentId: string): Promise { - const user = await authService.getCurrentUser() + const user = await getCurrentUser() if (!user) throw new Error("User not authenticated") - const { error } = await supabase + const { error } = await getSupabase() .from("dorm_comments") .delete() .eq("id", commentId) @@ -194,10 +195,13 @@ export const dormCommentsService = { * but are withheld from every non-admin reader by RLS. */ async setCommentHidden(commentId: string, hidden: boolean): Promise { - const user = await authService.getCurrentUser() + const user = await getCurrentUser() if (!isAdminUser(user)) throw new Error("Admin privileges required") - const { error } = await supabase.from("dorm_comments").update({ hidden }).eq("id", commentId) + const { error } = await getSupabase() + .from("dorm_comments") + .update({ hidden }) + .eq("id", commentId) if (error) { console.error("Error updating dorm comment visibility:", error) @@ -209,11 +213,11 @@ export const dormCommentsService = { * Upsert a vote on a comment. Pass null to remove the vote. */ async voteOnComment(commentId: string, vote: 1 | -1 | null): Promise { - const user = await authService.getCurrentUser() + const user = await getCurrentUser() if (!user) throw new Error("User not authenticated") if (vote === null) { - const { error } = await supabase + const { error } = await getSupabase() .from("dorm_comment_votes") .delete() .eq("comment_id", commentId) @@ -224,7 +228,7 @@ export const dormCommentsService = { throw error } } else { - const { error } = await supabase + const { error } = await getSupabase() .from("dorm_comment_votes") .upsert( { comment_id: commentId, user_id: user.id, vote }, diff --git a/apps/web/src/services/dormFavoritesService.ts b/packages/dorm/src/services/dormFavoritesService.ts similarity index 76% rename from apps/web/src/services/dormFavoritesService.ts rename to packages/dorm/src/services/dormFavoritesService.ts index df2fe153..461a1a09 100644 --- a/apps/web/src/services/dormFavoritesService.ts +++ b/packages/dorm/src/services/dormFavoritesService.ts @@ -1,5 +1,4 @@ -import { authService } from "./authService" -import { supabase } from "./supabase" +import { getCurrentUser, getSupabase } from "./host" export interface DormFavorite { id: string @@ -20,10 +19,10 @@ export const dormFavoritesService = { dormName: string, dormNameZh?: string, ): Promise<{ added: boolean; favorite?: DormFavorite }> { - const user = await authService.getCurrentUser() + const user = await getCurrentUser() if (!user) throw new Error("User not authenticated") - const { data: existing } = await supabase + const { data: existing } = await getSupabase() .from(TABLE_NAME) .select("*") .eq("user_id", user.id) @@ -31,7 +30,7 @@ export const dormFavoritesService = { .maybeSingle() if (existing) { - const { error } = await supabase.from(TABLE_NAME).delete().eq("id", existing.id) + const { error } = await getSupabase().from(TABLE_NAME).delete().eq("id", existing.id) if (error) { console.error("Error removing favorite:", error) @@ -39,7 +38,7 @@ export const dormFavoritesService = { } return { added: false } } else { - const { data, error } = await supabase + const { data, error } = await getSupabase() .from(TABLE_NAME) .insert({ user_id: user.id, @@ -59,10 +58,10 @@ export const dormFavoritesService = { }, async getFavorites(): Promise { - const user = await authService.getCurrentUser() + const user = await getCurrentUser() if (!user) return [] - const { data, error } = await supabase + const { data, error } = await getSupabase() .from(TABLE_NAME) .select("*") .eq("user_id", user.id) @@ -77,10 +76,10 @@ export const dormFavoritesService = { }, async isFavorited(dormId: string): Promise { - const user = await authService.getCurrentUser() + const user = await getCurrentUser() if (!user) return false - const { data, error } = await supabase + const { data, error } = await getSupabase() .from(TABLE_NAME) .select("id") .eq("user_id", user.id) @@ -96,10 +95,10 @@ export const dormFavoritesService = { }, async updateNotes(favoriteId: string, notes: string): Promise { - const user = await authService.getCurrentUser() + const user = await getCurrentUser() if (!user) return - const { error } = await supabase + const { error } = await getSupabase() .from(TABLE_NAME) .update({ notes, updated_at: new Date().toISOString() }) .eq("id", favoriteId) @@ -112,10 +111,10 @@ export const dormFavoritesService = { }, async removeFavorite(favoriteId: string): Promise { - const user = await authService.getCurrentUser() + const user = await getCurrentUser() if (!user) return - const { error } = await supabase + const { error } = await getSupabase() .from(TABLE_NAME) .delete() .eq("id", favoriteId) @@ -128,10 +127,10 @@ export const dormFavoritesService = { }, async removeFavoriteByDormId(dormId: string): Promise { - const user = await authService.getCurrentUser() + const user = await getCurrentUser() if (!user) return - const { error } = await supabase + const { error } = await getSupabase() .from(TABLE_NAME) .delete() .eq("user_id", user.id) @@ -144,10 +143,10 @@ export const dormFavoritesService = { }, async clearFavorites(): Promise { - const user = await authService.getCurrentUser() + const user = await getCurrentUser() if (!user) return - const { error } = await supabase.from(TABLE_NAME).delete().eq("user_id", user.id) + const { error } = await getSupabase().from(TABLE_NAME).delete().eq("user_id", user.id) if (error) { console.error("Error clearing favorites:", error) diff --git a/apps/web/src/services/dormService.ts b/packages/dorm/src/services/dormService.ts similarity index 94% rename from apps/web/src/services/dormService.ts rename to packages/dorm/src/services/dormService.ts index 01ab71d4..a2b2f241 100644 --- a/apps/web/src/services/dormService.ts +++ b/packages/dorm/src/services/dormService.ts @@ -1,7 +1,7 @@ import { Dorm } from "../components/housing/types/index" import { finalizeDormRecord, sanitizeFloorPlansForStorage } from "../utils/dormData" import { normalizeDorm } from "../utils/roomOptions" -import { supabase } from "./supabase" +import { getSupabase } from "./host" const TABLE = "dorms" @@ -58,7 +58,7 @@ function rowToDorm(row: Record): Dorm { /** Fetch all dorms. Falls back to static data on failure. */ async function getAllDorms(): Promise { try { - const { data, error } = await supabase.from(TABLE).select("*") + const { data, error } = await getSupabase().from(TABLE).select("*") if (error) { console.error("[dormService] getAllDorms error:", error) return getStaticDorms() @@ -76,7 +76,7 @@ async function getAllDorms(): Promise { /** Fetch a single dorm by ID. Falls back to static data on failure. */ async function getDormById(id: string): Promise { try { - const { data, error } = await supabase.from(TABLE).select("*").eq("id", id).maybeSingle() + const { data, error } = await getSupabase().from(TABLE).select("*").eq("id", id).maybeSingle() if (error) { console.error("[dormService] getDormById error:", error) const all = await getStaticDorms() diff --git a/apps/web/src/services/dormViewingService.ts b/packages/dorm/src/services/dormViewingService.ts similarity index 62% rename from apps/web/src/services/dormViewingService.ts rename to packages/dorm/src/services/dormViewingService.ts index e0b7c88d..0f96d28c 100644 --- a/apps/web/src/services/dormViewingService.ts +++ b/packages/dorm/src/services/dormViewingService.ts @@ -1,5 +1,4 @@ -import { authService } from "./authService" -import { supabase } from "./supabase" +import { getCurrentUser, getSupabase } from "./host" export interface DormViewingHistory { id: string @@ -15,19 +14,21 @@ const TABLE_NAME = "dorm_viewing_history" export const dormViewingService = { async addToHistory(dormId: string, dormName: string, dormNameZh?: string): Promise { - const user = await authService.getCurrentUser() + const user = await getCurrentUser() if (!user) return - const { error } = await supabase.from(TABLE_NAME).upsert( - { - user_id: user.id, - dorm_id: dormId, - dorm_name: dormName, - dorm_name_zh: dormNameZh || null, - last_viewed_at: new Date().toISOString(), - }, - { onConflict: "user_id,dorm_id" }, - ) + const { error } = await getSupabase() + .from(TABLE_NAME) + .upsert( + { + user_id: user.id, + dorm_id: dormId, + dorm_name: dormName, + dorm_name_zh: dormNameZh || null, + last_viewed_at: new Date().toISOString(), + }, + { onConflict: "user_id,dorm_id" }, + ) if (error) { console.error("Error adding viewing history:", error) @@ -36,10 +37,10 @@ export const dormViewingService = { }, async getHistory(limit: number = 20): Promise { - const user = await authService.getCurrentUser() + const user = await getCurrentUser() if (!user) return [] - const { data, error } = await supabase + const { data, error } = await getSupabase() .from(TABLE_NAME) .select("*") .eq("user_id", user.id) @@ -55,10 +56,14 @@ export const dormViewingService = { }, async removeFromHistory(id: string): Promise { - const user = await authService.getCurrentUser() + const user = await getCurrentUser() if (!user) return - const { error } = await supabase.from(TABLE_NAME).delete().eq("id", id).eq("user_id", user.id) + const { error } = await getSupabase() + .from(TABLE_NAME) + .delete() + .eq("id", id) + .eq("user_id", user.id) if (error) { console.error("Error removing from history:", error) @@ -67,10 +72,10 @@ export const dormViewingService = { }, async removeFromHistoryByDormId(dormId: string): Promise { - const user = await authService.getCurrentUser() + const user = await getCurrentUser() if (!user) return - const { error } = await supabase + const { error } = await getSupabase() .from(TABLE_NAME) .delete() .eq("user_id", user.id) @@ -83,10 +88,10 @@ export const dormViewingService = { }, async clearHistory(): Promise { - const user = await authService.getCurrentUser() + const user = await getCurrentUser() if (!user) return - const { error } = await supabase.from(TABLE_NAME).delete().eq("user_id", user.id) + const { error } = await getSupabase().from(TABLE_NAME).delete().eq("user_id", user.id) if (error) { console.error("Error clearing history:", error) diff --git a/packages/dorm/src/services/host.ts b/packages/dorm/src/services/host.ts new file mode 100644 index 00000000..d513d8fc --- /dev/null +++ b/packages/dorm/src/services/host.ts @@ -0,0 +1,49 @@ +import type { SupabaseClient, User } from "@supabase/supabase-js" + +export interface ChatHistoryItem { + role: "user" | "model" + text: string +} + +export type StreamChatResponseFn = ( + history: ChatHistoryItem[], + newMessage: string, + lang?: string, +) => AsyncIterable<{ text: string }> + +/** + * What the host app lends the dorm services. The package never creates its own + * Supabase client: a second GoTrue client would race the host's for the same + * session in localStorage. + */ +export interface DormServices { + supabase: SupabaseClient + /** Streams the housing assistant's replies. */ + streamChatResponse: StreamChatResponseFn +} + +let services: DormServices | null = null + +/** Call once, before `DormRoutes` renders. */ +export const configureDormServices = (next: DormServices): void => { + services = next +} + +const requireServices = (): DormServices => { + if (!services) { + throw new Error("@iguide/dorm: call configureDormServices() before rendering DormRoutes") + } + return services +} + +export const getSupabase = (): SupabaseClient => requireServices().supabase + +export const getCurrentUser = async (): Promise => { + const { + data: { user }, + } = await getSupabase().auth.getUser() + return user +} + +export const streamChatResponse: StreamChatResponseFn = (history, newMessage, lang) => + requireServices().streamChatResponse(history, newMessage, lang) diff --git a/packages/dorm/src/types.ts b/packages/dorm/src/types.ts new file mode 100644 index 00000000..559e0fd6 --- /dev/null +++ b/packages/dorm/src/types.ts @@ -0,0 +1,2 @@ +/** Same union as the host app's `Language`; declared here so the package imports nothing from it. */ +export type Language = "en" | "zh" diff --git a/apps/web/src/utils/dormData.ts b/packages/dorm/src/utils/dormData.ts similarity index 100% rename from apps/web/src/utils/dormData.ts rename to packages/dorm/src/utils/dormData.ts diff --git a/apps/web/src/utils/housingLabels.ts b/packages/dorm/src/utils/housingLabels.ts similarity index 100% rename from apps/web/src/utils/housingLabels.ts rename to packages/dorm/src/utils/housingLabels.ts diff --git a/apps/web/src/utils/housingUtils.ts b/packages/dorm/src/utils/housingUtils.ts similarity index 100% rename from apps/web/src/utils/housingUtils.ts rename to packages/dorm/src/utils/housingUtils.ts diff --git a/apps/web/src/utils/roomOptions.ts b/packages/dorm/src/utils/roomOptions.ts similarity index 100% rename from apps/web/src/utils/roomOptions.ts rename to packages/dorm/src/utils/roomOptions.ts diff --git a/apps/web/src/utils/tagLabels.ts b/packages/dorm/src/utils/tagLabels.ts similarity index 100% rename from apps/web/src/utils/tagLabels.ts rename to packages/dorm/src/utils/tagLabels.ts diff --git a/packages/dorm/tsconfig.json b/packages/dorm/tsconfig.json new file mode 100644 index 00000000..287e7caf --- /dev/null +++ b/packages/dorm/tsconfig.json @@ -0,0 +1,18 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "skipLibCheck": true, + "moduleResolution": "bundler", + "isolatedModules": true, + "moduleDetection": "force", + "esModuleInterop": true, + "jsx": "react-jsx", + "allowImportingTsExtensions": true, + "noEmit": true, + "types": ["vite/client", "geojson", "node"] + }, + "include": ["src", "scripts"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 28e5d786..a93bf9d3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -193,9 +193,9 @@ importers: '@assistant-ui/react-markdown': specifier: 0.14.17 version: 0.14.17(@assistant-ui/react@0.15.22(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(use-sync-external-store@1.7.0(react@19.3.0)))(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(supports-color@10.2.2) - '@headlessui/react': - specifier: ^2.2.10 - version: 2.2.10(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + '@iguide/dorm': + specifier: workspace:* + version: link:../../packages/dorm '@iguide/ui': specifier: workspace:* version: link:../../packages/ui @@ -208,21 +208,12 @@ importers: lucide-react: specifier: ^1.48.0 version: 1.48.0(react@19.3.0) - mapbox-gl: - specifier: ^3.31.0 - version: 3.31.0 - rc-slider: - specifier: ^11.1.9 - version: 11.1.9(react-dom@19.3.0(react@19.3.0))(react@19.3.0) react: specifier: ^19.3.0 version: 19.3.0 react-dom: specifier: ^19.3.0 version: 19.3.0(react@19.3.0) - react-map-gl: - specifier: ^8.1.3 - version: 8.1.3(mapbox-gl@3.31.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) react-markdown: specifier: ^10.1.0 version: 10.1.0(@types/react@19.3.0)(react@19.3.0)(supports-color@10.2.2) @@ -245,9 +236,6 @@ importers: '@tailwindcss/vite': specifier: ^4.3.3 version: 4.3.3(@voidzero-dev/vite-plus-core@0.3.3(@types/node@26.6.3)(esbuild@0.28.1)(jiti@2.7.0)(typescript@7.0.2)) - '@types/geojson': - specifier: ^7946.0.16 - version: 7946.0.16 '@types/node': specifier: ^26.6.3 version: 26.6.3 @@ -285,6 +273,70 @@ importers: specifier: 'catalog:' version: 0.3.3(@types/node@26.6.3)(esbuild@0.28.1)(jiti@2.7.0)(typescript@7.0.2) + packages/dorm: + dependencies: + '@headlessui/react': + specifier: ^2.2.10 + version: 2.2.10(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + '@iguide/ui': + specifier: workspace:* + version: link:../ui + framer-motion: + specifier: ^13.4.4 + version: 13.4.4(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + lucide-react: + specifier: ^1.48.0 + version: 1.48.0(react@19.3.0) + mapbox-gl: + specifier: ^3.31.0 + version: 3.31.0 + rc-slider: + specifier: ^11.1.9 + version: 11.1.9(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + react-map-gl: + specifier: ^8.1.3 + version: 8.1.3(mapbox-gl@3.31.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + react-markdown: + specifier: ^10.1.0 + version: 10.1.0(@types/react@19.3.0)(react@19.3.0)(supports-color@10.2.2) + remark-gfm: + specifier: ^4.0.1 + version: 4.0.1(supports-color@10.2.2) + devDependencies: + '@supabase/supabase-js': + specifier: ^2.117.2 + version: 2.117.2 + '@types/geojson': + specifier: ^7946.0.16 + version: 7946.0.16 + '@types/node': + specifier: ^26.6.3 + version: 26.6.3 + '@types/react': + specifier: ^19.3.0 + version: 19.3.0 + '@types/react-dom': + specifier: ^19.3.0 + version: 19.3.0(@types/react@19.3.0) + react: + specifier: ^19.3.0 + version: 19.3.0 + react-dom: + specifier: ^19.3.0 + version: 19.3.0(react@19.3.0) + react-router-dom: + specifier: ^7.18.4 + version: 7.18.4(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + typescript: + specifier: ~7.0.2 + version: 7.0.2 + vite: + specifier: 'catalog:' + version: '@voidzero-dev/vite-plus-core@0.3.3(@types/node@26.6.3)(esbuild@0.28.1)(jiti@2.7.0)(typescript@7.0.2)' + vite-plus: + specifier: 'catalog:' + version: 0.3.3(@types/node@26.6.3)(esbuild@0.28.1)(jiti@2.7.0)(typescript@7.0.2) + packages/ui: dependencies: framer-motion: diff --git a/vite.config.ts b/vite.config.ts index 32428025..365c8e63 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -28,7 +28,7 @@ export default defineConfig({ ignorePatterns, overrides: [ { - files: ["apps/web/**", "packages/ui/**"], + files: ["apps/web/**", "packages/dorm/**", "packages/ui/**"], env: { browser: true }, }, { From ee1e36d9607e4d0649541e644e261a9c42774a5b Mon Sep 17 00:00:00 2001 From: a2751012962 Date: Fri, 2 Oct 2026 14:02:34 +0800 Subject: [PATCH 3/9] chore(dorm): move the review scrapers into packages/dorm They write the dorm package's googleReviews.ts, so they now live beside it. Their output paths and the Python env path pointed at directories that no longer exist (../web/src and the legacy app/); they now resolve to the package and apps/web/.env.local. --- {dorm_scripts => packages/dorm/scrapers}/README.md | 12 +++++++----- {dorm_scripts => packages/dorm/scrapers}/bun.lock | 0 .../dorm/scrapers}/fetchReviewsGPT.py | 4 ++-- .../dorm/scrapers}/package.json | 0 .../dorm/scrapers}/scrapeMissing2.cjs | 4 ++-- .../dorm/scrapers}/scrapePCHMaps.cjs | 4 ++-- vite.config.ts | 2 +- 7 files changed, 14 insertions(+), 12 deletions(-) rename {dorm_scripts => packages/dorm/scrapers}/README.md (69%) rename {dorm_scripts => packages/dorm/scrapers}/bun.lock (100%) rename {dorm_scripts => packages/dorm/scrapers}/fetchReviewsGPT.py (96%) rename {dorm_scripts => packages/dorm/scrapers}/package.json (100%) rename {dorm_scripts => packages/dorm/scrapers}/scrapeMissing2.cjs (98%) rename {dorm_scripts => packages/dorm/scrapers}/scrapePCHMaps.cjs (96%) diff --git a/dorm_scripts/README.md b/packages/dorm/scrapers/README.md similarity index 69% rename from dorm_scripts/README.md rename to packages/dorm/scrapers/README.md index 4a0bfc16..d76fa663 100644 --- a/dorm_scripts/README.md +++ b/packages/dorm/scrapers/README.md @@ -1,10 +1,12 @@ -# dorm_scripts +# scrapers -This directory keeps scraping and dorm-review generation code out of `apps/web/` so the app stays free of scraping-only dependencies like Puppeteer. +Scraping and dorm-review generation code for `@iguide/dorm`. It has its own +`package.json` and is not a workspace member, so scraping-only dependencies +like Puppeteer stay out of both the app and the package. All scripts write to: -`apps/web/src/components/housing/constants/googleReviews.ts` +`packages/dorm/src/components/housing/constants/googleReviews.ts` ## Included scripts @@ -17,7 +19,7 @@ All scripts write to: Run Bun from inside this directory: ```bash -cd dorm_scripts +cd packages/dorm/scrapers bun install ``` @@ -49,4 +51,4 @@ This requires `DEEPSEEK_API_KEY` or `VITE_DEEPSEEK_API_KEY` in `apps/web/.env.lo ## Important -`dorm_scripts/` is intentionally isolated. Don’t move these scripts back into `apps/web/`. +`scrapers/` is intentionally isolated. Don’t add it to the workspace or move these scripts into `src/`. diff --git a/dorm_scripts/bun.lock b/packages/dorm/scrapers/bun.lock similarity index 100% rename from dorm_scripts/bun.lock rename to packages/dorm/scrapers/bun.lock diff --git a/dorm_scripts/fetchReviewsGPT.py b/packages/dorm/scrapers/fetchReviewsGPT.py similarity index 96% rename from dorm_scripts/fetchReviewsGPT.py rename to packages/dorm/scrapers/fetchReviewsGPT.py index 5cd473e9..621028ac 100644 --- a/dorm_scripts/fetchReviewsGPT.py +++ b/packages/dorm/scrapers/fetchReviewsGPT.py @@ -6,7 +6,7 @@ from pathlib import Path # Load env safely -env_path = Path(__file__).resolve().parent.parent / 'app' / '.env.local' +env_path = Path(__file__).resolve().parents[3] / 'apps' / 'web' / '.env.local' with open(env_path, 'r', encoding='utf-8') as f: for line in f: line = line.strip() @@ -100,7 +100,7 @@ def fetch_real_reviews(dorm_id, dorm_name): print(f"Total reviews extracted: {len(all_collected)}") -target_file = Path(__file__).resolve().parent.parent / 'apps/web/src/components/housing/constants/googleReviews.ts' +target_file = Path(__file__).resolve().parent.parent / 'src/components/housing/constants/googleReviews.ts' with open(target_file, 'w', encoding='utf-8') as f: f.write('''import { DormComment } from '../../../services/dormCommentsService'; diff --git a/dorm_scripts/package.json b/packages/dorm/scrapers/package.json similarity index 100% rename from dorm_scripts/package.json rename to packages/dorm/scrapers/package.json diff --git a/dorm_scripts/scrapeMissing2.cjs b/packages/dorm/scrapers/scrapeMissing2.cjs similarity index 98% rename from dorm_scripts/scrapeMissing2.cjs rename to packages/dorm/scrapers/scrapeMissing2.cjs index 6362ffd8..c62832e1 100644 --- a/dorm_scripts/scrapeMissing2.cjs +++ b/packages/dorm/scrapers/scrapeMissing2.cjs @@ -288,7 +288,7 @@ async function main() { } let fileContent = fs.readFileSync( - path.resolve(__dirname, "../web/src/components/housing/constants/googleReviews.ts"), + path.resolve(__dirname, "../src/components/housing/constants/googleReviews.ts"), "utf8", ) @@ -307,7 +307,7 @@ async function main() { fileContent = before + (needsComma ? ",\n" : "\n") + lines.join(",\n") + "\n" + after fs.writeFileSync( - path.resolve(__dirname, "../web/src/components/housing/constants/googleReviews.ts"), + path.resolve(__dirname, "../src/components/housing/constants/googleReviews.ts"), fileContent, "utf8", ) diff --git a/dorm_scripts/scrapePCHMaps.cjs b/packages/dorm/scrapers/scrapePCHMaps.cjs similarity index 96% rename from dorm_scripts/scrapePCHMaps.cjs rename to packages/dorm/scrapers/scrapePCHMaps.cjs index c3468e87..3a9e0bac 100644 --- a/dorm_scripts/scrapePCHMaps.cjs +++ b/packages/dorm/scrapers/scrapePCHMaps.cjs @@ -169,7 +169,7 @@ async function main() { console.log(`Total PCH reviews pulled: ${allCollected.length}`) let fileContent = fs.readFileSync( - path.resolve(__dirname, "../web/src/components/housing/constants/googleReviews.ts"), + path.resolve(__dirname, "../src/components/housing/constants/googleReviews.ts"), "utf8", ) @@ -186,7 +186,7 @@ async function main() { } fs.writeFileSync( - path.resolve(__dirname, "../web/src/components/housing/constants/googleReviews.ts"), + path.resolve(__dirname, "../src/components/housing/constants/googleReviews.ts"), fileContent, "utf8", ) diff --git a/vite.config.ts b/vite.config.ts index 365c8e63..c6f9947e 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -39,7 +39,7 @@ export default defineConfig({ rules: { "no-console": "off" }, }, { - files: ["tools/**"], + files: ["tools/**", "packages/dorm/scrapers/**"], env: { node: true }, }, ], From af4d5302c3292c201c7071d8114b11f8626a73c3 Mon Sep 17 00:00:00 2001 From: a2751012962 Date: Fri, 2 Oct 2026 14:02:48 +0800 Subject: [PATCH 4/9] docs: move dorm setup docs into the @iguide/dorm package Dorm SQL, seed, and data-script docs now sit with the package that owns them, and the repo guides describe the boundary: the web app reaches dorm code only through its /dorms adapter. --- AGENTS.md | 13 ++-- README.md | 27 +++---- README_CN.md | 27 +++---- apps/web/AGENTS.md | 21 +++-- apps/web/README.md | 51 +++--------- apps/web/README_CN.md | 46 +++-------- packages/dorm/README.md | 77 +++++++++++++++++++ packages/dorm/README_CN.md | 68 ++++++++++++++++ .../src/components/housing/DORM_DATA_AUDIT.md | 2 +- 9 files changed, 219 insertions(+), 113 deletions(-) create mode 100644 packages/dorm/README.md create mode 100644 packages/dorm/README_CN.md diff --git a/AGENTS.md b/AGENTS.md index d9bb781b..453fb271 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,10 +9,11 @@ A UIUC knowledge platform with a React 19 frontend and Cloudflare Worker gateway Supabase provides auth and Postgres; DeepSeek handles inference and Tavily supplies web search. -| Path | Role | -| :-------------- | :----------------------------------------------------------------------- | -| `apps/web/` | Frontend and Worker: SPA, static assets, agent loop, tools, skills, MCP. | -| `dorm_scripts/` | Standalone Puppeteer/Bun review scrapers. | +| Path | Role | +| :--------------- | :-------------------------------------------------------------------------- | +| `apps/web/` | Frontend and Worker: SPA, static assets, agent loop, tools, skills, MCP. | +| `packages/dorm/` | Dorm feature (`@iguide/dorm`): UI, state, dorm SQL, data scripts, scrapers. | +| `packages/ui/` | Business-agnostic UI primitives shared by the app and feature packages. | @@ -105,8 +106,10 @@ Paths below are relative to `apps/web/`: - Enable RLS and grants in each new table's migration: `anon` and `authenticated` receive `select`; writes use the service key. -- Apply the dorm chain in `apps/web/scripts/migrations/`, starting with +- Apply the dorm chain in `packages/dorm/scripts/migrations/`, starting with `create_dorms_table.sql`, then `add_categorized_tags.sql`, then follow-ups. + Chat-owned SQL (`add_soul_and_memory.sql`) stays in + `apps/web/scripts/migrations/`. ## Deploy diff --git a/README.md b/README.md index b22af005..db9147b5 100644 --- a/README.md +++ b/README.md @@ -49,9 +49,10 @@ curl http://localhost:5173/api/health ## How it fits together -- [`apps/web/src`](apps/web/src) is the React 19 SPA: react-router 7, Tailwind CSS 4, assistant-ui for chat, Mapbox GL for the dorm map, and supabase-js for auth and user data. +- [`apps/web/src`](apps/web/src) is the React 19 SPA shell: react-router 7, Tailwind CSS 4, assistant-ui for chat, and supabase-js for auth and user data. +- [`packages/dorm`](packages/dorm) is the dorm feature as its own workspace package: list, Mapbox GL map, detail, compare, and reviews, plus the dorm SQL chain, data scripts, and review scrapers. The web app mounts it lazily at `/dorms/*` through one adapter, so no other page loads dorm code or queries dorm tables. Shared UI primitives live in [`packages/ui`](packages/ui). - [`apps/web/worker`](apps/web/worker) is the Cloudflare Worker (named `uiuc`). It routes `/api/*` and serves the SPA's static assets for every other path. It also hosts the tool-use [agent loop](apps/web/worker/agent), its [tools](apps/web/worker/tools) and [skills](apps/web/worker/skills), and an experimental [MCP client](apps/web/worker/mcp) for user-registered servers (in memory only, with no UI yet). -- [`apps/web/scripts/migrations`](apps/web/scripts/migrations) is the dorm SQL chain (dorms, edit history, the photo bucket, persona and memory tables) that you run by hand in the Supabase SQL editor, together with [`apps/web/scripts/create_dorm_user_features.sql`](apps/web/scripts/create_dorm_user_features.sql) for dorm favorites and viewing history. +- SQL runs by hand in the Supabase SQL editor: the dorm chain in [`packages/dorm/scripts`](packages/dorm/README.md#dorm-database) (dorms, edit history, the photo bucket, favorites and viewing history), then the persona and memory tables in [`apps/web/scripts/migrations`](apps/web/scripts/migrations). - [`tools/vite-bin`](tools/vite-bin) gives `cf build` a `vite` bin that forwards to the pinned Vite+, so builds don't download an unpinned Vite. ```text @@ -83,15 +84,15 @@ Nothing needs loading for retrieval: the agent's only source is a Tavily search ## Documentation -| Goal | Start here | -| ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Learn the repo rules, commands, and data model | [AGENTS.md](AGENTS.md) | -| Work on the React app or the Worker | [apps/web/AGENTS.md](apps/web/AGENTS.md) | -| Change the agent's prompt or loop | [apps/web/worker/routes/agent-prompts](apps/web/worker/routes/agent-prompts) · [apps/web/worker/agent](apps/web/worker/agent) | -| Add an agent tool or skill | [apps/web/worker/tools](apps/web/worker/tools) · [apps/web/worker/skills](apps/web/worker/skills) | -| Configure secrets and the Worker | [apps/web/.dev.vars.example](apps/web/.dev.vars.example) · [apps/web/.env.local.example](apps/web/.env.local.example) · [apps/web/cloudflare.config.ts](apps/web/cloudflare.config.ts) | -| Set up dorm tables and seed data | [apps/web/scripts/migrations](apps/web/scripts/migrations) · [apps/web/scripts/create_dorm_user_features.sql](apps/web/scripts/create_dorm_user_features.sql) · [apps/web/scripts/seed-dorms-table.ts](apps/web/scripts/seed-dorms-table.ts) | -| See what runs on pull requests | [.github/workflows/react-doctor.yml](.github/workflows/react-doctor.yml) | +| Goal | Start here | +| ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Learn the repo rules, commands, and data model | [AGENTS.md](AGENTS.md) | +| Work on the React app or the Worker | [apps/web/AGENTS.md](apps/web/AGENTS.md) | +| Change the agent's prompt or loop | [apps/web/worker/routes/agent-prompts](apps/web/worker/routes/agent-prompts) · [apps/web/worker/agent](apps/web/worker/agent) | +| Add an agent tool or skill | [apps/web/worker/tools](apps/web/worker/tools) · [apps/web/worker/skills](apps/web/worker/skills) | +| Configure secrets and the Worker | [apps/web/.dev.vars.example](apps/web/.dev.vars.example) · [apps/web/.env.local.example](apps/web/.env.local.example) · [apps/web/cloudflare.config.ts](apps/web/cloudflare.config.ts) | +| Work on dorm pages, SQL, or seed data | [packages/dorm](packages/dorm/README.md) | +| See what runs on pull requests | [.github/workflows/react-doctor.yml](.github/workflows/react-doctor.yml) | ## Development @@ -141,11 +142,11 @@ Alternatively, `pnpm exec cf previews deploy` (without `--prebuilt`) builds with Roll out in this order: -1. Create the `conversations`, `messages`, `reading_history`, `user_profiles`, and `mailing_list` tables yourself: the tracked SQL doesn't create them, and the dorm chain's `add_soul_and_memory.sql` references `conversations`. Then run the dorm chain in `apps/web/scripts/migrations/`, starting with `create_dorms_table.sql`, and `apps/web/scripts/create_dorm_user_features.sql` (favorites and viewing history). On a fresh project, delete the last line of `create_dorms_table.sql` first: it comments on a `dorm_overrides` table that no tracked SQL creates, and that error rolls back the whole file in the SQL editor. +1. Create the `conversations`, `messages`, `reading_history`, `user_profiles`, and `mailing_list` tables yourself: the tracked SQL doesn't create them, and `apps/web/scripts/migrations/add_soul_and_memory.sql` references `conversations`. Run the dorm chain in `packages/dorm/scripts/migrations/`, starting with `create_dorms_table.sql`, and `packages/dorm/scripts/create_dorm_user_features.sql` (favorites and viewing history), then `add_soul_and_memory.sql`. On a fresh project, delete the last line of `create_dorms_table.sql` first: it comments on a `dorm_overrides` table that no tracked SQL creates, and that error rolls back the whole file in the SQL editor. 2. Seed the dorms table. The script reads `SUPABASE_URL` and `SUPABASE_SERVICE_KEY` from the shell, not from `.env` files. ```bash - cd apps/web && pnpm dlx tsx scripts/seed-dorms-table.ts + cd packages/dorm && pnpm run seed ``` On a database built only from the tracked SQL, the seed fails: `add_categorized_tags.sql` adds `chk_bathroom_type`, which allows only `communal`, `semi-private`, and `private`, but the seed writes `individual-use` for four dorms, and one rejected row fails the whole upsert. Widen the constraint before you seed: diff --git a/README_CN.md b/README_CN.md index ce959b65..29e3e48b 100644 --- a/README_CN.md +++ b/README_CN.md @@ -49,9 +49,10 @@ curl http://localhost:5173/api/health ## 整体架构 -- [`apps/web/src`](apps/web/src) 是 React 19 SPA:react-router 7、Tailwind CSS 4、负责聊天的 assistant-ui、负责宿舍地图的 Mapbox GL,以及负责鉴权和用户数据的 supabase-js。 +- [`apps/web/src`](apps/web/src) 是 React 19 SPA 外壳:react-router 7、Tailwind CSS 4、负责聊天的 assistant-ui,以及负责鉴权和用户数据的 supabase-js。 +- [`packages/dorm`](packages/dorm) 是独立成 workspace 包的宿舍功能:列表、Mapbox GL 地图、详情、对比和评论,以及宿舍 SQL 迁移链、数据脚本和评论爬虫。Web 应用通过一个适配文件在 `/dorms/*` 懒加载它,其他页面不会加载宿舍代码,也不会查询宿舍表。共享的 UI 基础组件在 [`packages/ui`](packages/ui) 中。 - [`apps/web/worker`](apps/web/worker) 是 Cloudflare Worker(名为 `uiuc`)。它负责路由 `/api/*`,其他所有路径都返回 SPA 的静态资源。它还承载 tool-use [agent 循环](apps/web/worker/agent)、配套的[工具](apps/web/worker/tools)和[技能](apps/web/worker/skills),以及一个面向用户自行注册服务器的实验性 [MCP 客户端](apps/web/worker/mcp)(仅存于内存,暂无 UI)。 -- [`apps/web/scripts/migrations`](apps/web/scripts/migrations) 是宿舍 SQL 迁移链(宿舍、编辑历史、照片 bucket、人设和记忆表),需要在 Supabase SQL 编辑器中手动执行,并配合 [`apps/web/scripts/create_dorm_user_features.sql`](apps/web/scripts/create_dorm_user_features.sql) 实现宿舍收藏和浏览历史。 +- SQL 需要在 Supabase SQL 编辑器中手动执行:先执行 [`packages/dorm/scripts`](packages/dorm/README_CN.md#宿舍数据库) 中的宿舍迁移链(宿舍、编辑历史、照片 bucket、收藏和浏览历史),再执行 [`apps/web/scripts/migrations`](apps/web/scripts/migrations) 中的人设和记忆表。 - [`tools/vite-bin`](tools/vite-bin) 为 `cf build` 提供一个转发到已锁定版本 Vite+ 的 `vite` bin,这样构建时就不会下载未锁定版本的 Vite。 ```text @@ -83,15 +84,15 @@ Browser ──same origin──> Worker "uiuc" (apps/web/worker) ## 文档 -| 目标 | 从这里开始 | -| ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| 了解仓库规则、命令和数据模型 | [AGENTS.md](AGENTS.md) | -| 开发 React 应用或 Worker | [apps/web/AGENTS.md](apps/web/AGENTS.md) | -| 修改 agent 的提示词或循环 | [apps/web/worker/routes/agent-prompts](apps/web/worker/routes/agent-prompts) · [apps/web/worker/agent](apps/web/worker/agent) | -| 添加 agent 工具或技能 | [apps/web/worker/tools](apps/web/worker/tools) · [apps/web/worker/skills](apps/web/worker/skills) | -| 配置 secrets 和 Worker | [apps/web/.dev.vars.example](apps/web/.dev.vars.example) · [apps/web/.env.local.example](apps/web/.env.local.example) · [apps/web/cloudflare.config.ts](apps/web/cloudflare.config.ts) | -| 创建宿舍表并导入种子数据 | [apps/web/scripts/migrations](apps/web/scripts/migrations) · [apps/web/scripts/create_dorm_user_features.sql](apps/web/scripts/create_dorm_user_features.sql) · [apps/web/scripts/seed-dorms-table.ts](apps/web/scripts/seed-dorms-table.ts) | -| 查看 pull request 上会运行什么 | [.github/workflows/react-doctor.yml](.github/workflows/react-doctor.yml) | +| 目标 | 从这里开始 | +| ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 了解仓库规则、命令和数据模型 | [AGENTS.md](AGENTS.md) | +| 开发 React 应用或 Worker | [apps/web/AGENTS.md](apps/web/AGENTS.md) | +| 修改 agent 的提示词或循环 | [apps/web/worker/routes/agent-prompts](apps/web/worker/routes/agent-prompts) · [apps/web/worker/agent](apps/web/worker/agent) | +| 添加 agent 工具或技能 | [apps/web/worker/tools](apps/web/worker/tools) · [apps/web/worker/skills](apps/web/worker/skills) | +| 配置 secrets 和 Worker | [apps/web/.dev.vars.example](apps/web/.dev.vars.example) · [apps/web/.env.local.example](apps/web/.env.local.example) · [apps/web/cloudflare.config.ts](apps/web/cloudflare.config.ts) | +| 修改宿舍页面、SQL 或种子数据 | [packages/dorm](packages/dorm/README_CN.md) | +| 查看 pull request 上会运行什么 | [.github/workflows/react-doctor.yml](.github/workflows/react-doctor.yml) | ## 开发 @@ -141,11 +142,11 @@ pnpm run deploy:preview # cf previews deploy --pr 按以下顺序上线: -1. 自己创建 `conversations`、`messages`、`reading_history`、`user_profiles` 和 `mailing_list` 表:仓库中的 SQL 不会创建它们,而宿舍迁移链中的 `add_soul_and_memory.sql` 会引用 `conversations`。然后从 `create_dorms_table.sql` 开始执行 `apps/web/scripts/migrations/` 中的宿舍迁移链,并执行 `apps/web/scripts/create_dorm_user_features.sql`(收藏和浏览历史)。在全新项目上,请先删掉 `create_dorms_table.sql` 的最后一行:它给一张仓库里没有任何 SQL 创建的 `dorm_overrides` 表加注释,这个错误会让 SQL 编辑器回滚整个文件。 +1. 自己创建 `conversations`、`messages`、`reading_history`、`user_profiles` 和 `mailing_list` 表:仓库中的 SQL 不会创建它们,而 `apps/web/scripts/migrations/add_soul_and_memory.sql` 会引用 `conversations`。从 `create_dorms_table.sql` 开始执行 `packages/dorm/scripts/migrations/` 中的宿舍迁移链,并执行 `packages/dorm/scripts/create_dorm_user_features.sql`(收藏和浏览历史),然后执行 `add_soul_and_memory.sql`。在全新项目上,请先删掉 `create_dorms_table.sql` 的最后一行:它给一张仓库里没有任何 SQL 创建的 `dorm_overrides` 表加注释,这个错误会让 SQL 编辑器回滚整个文件。 2. 为宿舍表导入种子数据。该脚本从 shell 读取 `SUPABASE_URL` 和 `SUPABASE_SERVICE_KEY`,而不是从 `.env` 文件读取。 ```bash - cd apps/web && pnpm dlx tsx scripts/seed-dorms-table.ts + cd packages/dorm && pnpm run seed ``` 如果数据库只由仓库中的 SQL 建成,导入种子数据会失败:`add_categorized_tags.sql` 添加的 `chk_bathroom_type` 只允许 `communal`、`semi-private` 和 `private`,但种子脚本会为四栋宿舍写入 `individual-use`,而只要有一行被拒绝,整个 upsert 就会失败。导入前请先放宽这个约束: diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md index c07fab8c..4be6073c 100644 --- a/apps/web/AGENTS.md +++ b/apps/web/AGENTS.md @@ -63,8 +63,15 @@ For repo-wide rules (secrets, CI, Worker retrieval, data model), see the root - Route-only composition belongs in `src/pages/**`. - Feature-local UI belongs next to that feature under `src/components/**`. - Shared layout belongs in `src/components/layout/**`. -- Shared dumb UI belongs in `src/components/ui/**`. +- Shared dumb UI belongs in `src/components/ui/**`; primitives that a feature + package also needs belong in `packages/ui` (`@iguide/ui`). - Shared persistence and external integrations belong in `src/services/**`. +- Dorm (housing) code belongs in `packages/dorm`, not `src/`. This app reaches + it only through `src/pages/dorms/DormRoute.tsx`, which imports from + `@iguide/dorm` and never from the package's internal paths. Shell code + (`App.tsx`, `src/components/layout/**`) must not import dorm code; a feature + that needs shell space fills `useLayout().setSidebarSlot` or + `setMobileHeaderSlot` from inside its own route. ## Verification @@ -72,9 +79,10 @@ For structure-affecting changes: 1. Run `npm run typecheck` when TypeScript boundaries moved. 2. Run `npm run build` for renamed imports, route changes, or moved modules. -3. Run `npm run validate:dorm-data` when changing dorm data contracts. -4. Run `npm run audit:dorm-media` when changing dorm media sourcing or media - validation. +3. Run `pnpm run validate:data` in `packages/dorm/` when changing dorm data + contracts. +4. Run `pnpm run audit:media` in `packages/dorm/` when changing dorm media + sourcing or media validation. 5. Only require `npm run verify:architecture` if the script exists in `package.json`. @@ -101,11 +109,12 @@ Key patterns: - Conversation management with persistent IDs - Route: `/chat` -### Housing Chat (`src/components/housing/AIChat.tsx`) +### Housing Chat (`packages/dorm/src/components/housing/AIChat.tsx`) - Housing/dorm-specific floating chat widget - Dorm mention detection and highlighting - Shows dorm cards with navigation to dorm details -- Uses housing-specific i18n and streamChatResponse +- Uses housing-specific i18n and this app's streamChatResponse, lent through + `configureDormServices` in `src/pages/dorms/DormRoute.tsx` - Embedded in DormDetailPage and DormListPage - Domain-specific to housing module per Colocation Principle diff --git a/apps/web/README.md b/apps/web/README.md index db6c9867..9a5e6df0 100644 --- a/apps/web/README.md +++ b/apps/web/README.md @@ -13,8 +13,11 @@ overall architecture, see the root [README](../../README.md). For where code bel - `worker/`: the Worker, entry `worker/index.ts`, configured in `cloudflare.config.ts`. It serves `/api/chat` (the tool-use agent; Tavily web search is its only retrieval source), the provider proxies, `/api/health` and `/api/integrations*`. -- `scripts/`: the dorm database SQL (`scripts/migrations/*.sql`, `scripts/*.sql`) and the dorm data - scripts below. Two unused leftovers from the removed QMD knowledge base are also still here: +- `src/pages/dorms/DormRoute.tsx`: the only file that touches the dorm feature. The feature itself + (UI, state, dorm SQL, data scripts) lives in [`packages/dorm`](../../packages/dorm) and is + lazy-loaded at `/dorms/*`. +- `scripts/`: the chat persona and memory SQL (`scripts/migrations/add_soul_and_memory.sql`) and the + RLS fixes `scripts/optimize_rls_policies.sql` and `scripts/fix_function_security.sql`. Two unused leftovers from the removed QMD knowledge base are also still here: `scripts/qmd-server.mjs` (the search server behind the old `/api/search` route) and `scripts/generate-handbook-ocr.py` (an OCR generator for QMD content). Nothing references them. @@ -52,43 +55,13 @@ Lint with `pnpm run lint` and check formatting with `pnpm exec vp fmt --check` ( rewrites files). From the repo root, `pnpm exec vp check` runs format, lint and type checks (`pnpm run check` does the same and applies fixes). -## Dorm database +## Database -Run the SQL by hand in the Supabase SQL editor. Core dorm schema, in this order: - -1. `scripts/migrations/create_dorms_table.sql`. On a fresh project, delete its last line first: it - comments on a `dorm_overrides` table that no tracked SQL creates, and the SQL editor then rolls back - the whole file. -2. `scripts/migrations/add_categorized_tags.sql` (safe to rerun) -3. `scripts/migrations/add_dorm_address.sql` and `scripts/migrations/add_dorm_website.sql`, which add - the `address`, `address_zh` and `website` columns the seed writes - -Feature SQL, after the core schema: - -- `scripts/migrations/create_storage_bucket.sql`: the `dorm-images` storage bucket. -- `add_dorm_edit_history.sql`, then `fix_dorm_edit_history_rls.sql`; `add_dorm_comments.sql`, then - `add_dorm_comment_hidden.sql`; `add_floor_plan_bed_size.sql`; `add_soul_and_memory.sql` (all in - `scripts/migrations/`). -- `scripts/create_dorm_user_features.sql`: dorm favorites and viewing history. +Run the SQL by hand in the Supabase SQL editor. Dorm tables, storage and seed data are set up from +[`packages/dorm`](../../packages/dorm/README.md#dorm-database); run that chain first. The tracked SQL does not create every table the app uses. Create `conversations`, `messages`, -`reading_history`, `user_profiles` and `mailing_list` yourself. `scripts/optimize_rls_policies.sql` and -`scripts/fix_function_security.sql` assume some of them already exist. Known conflict: -`add_categorized_tags.sql` limits `bathroom_type` to `communal`, `semi-private` and `private`, but the -seed writes `individual-use` for four dorms. Until that constraint changes, the seed fails on a -database built only from this SQL. - -## Dorm data scripts - -`tsx` is not a dependency, so run the scripts with `pnpm dlx tsx`, from `apps/web/`: - -```sh -pnpm dlx tsx scripts/validate-dorm-data.ts # offline check of the bundled dataset -pnpm dlx tsx scripts/audit-dorm-media.ts # sends HEAD requests to suspicious media URLs -SUPABASE_URL= SUPABASE_SERVICE_KEY= pnpm dlx tsx scripts/seed-dorms-table.ts -``` - -The seed reads both variables from the shell, not from env files (in PowerShell, set them first with -`$env:NAME = "..."`). `SUPABASE_SERVICE_KEY` is a service-role key that bypasses RLS. The seed upserts -the bundled `UIUC_DORMS` into `dorms` by `id`. It keeps stored images, gallery and floor-plan media, -merges tags with stored ones, and never deletes rows. It does not read the archived `dorm_overrides`. +`reading_history`, `user_profiles` and `mailing_list` yourself. Then run +`scripts/migrations/add_soul_and_memory.sql`, which references `conversations`. +`scripts/optimize_rls_policies.sql` and `scripts/fix_function_security.sql` assume some of those +tables already exist. diff --git a/apps/web/README_CN.md b/apps/web/README_CN.md index 4aa68a07..818eca25 100644 --- a/apps/web/README_CN.md +++ b/apps/web/README_CN.md @@ -13,7 +13,10 @@ Worker,Worker 负责托管 SPA,并在同源下处理所有 `/api/*` 路由 - `worker/`:Worker,入口 `worker/index.ts`,配置在 `cloudflare.config.ts`。它提供 `/api/chat` (tool-use 智能体,唯一的检索来源是 Tavily 网页搜索)、各模型服务代理、`/api/health` 和 `/api/integrations*`。 -- `scripts/`:宿舍数据库 SQL(`scripts/migrations/*.sql`、`scripts/*.sql`)以及下文的宿舍数据脚本。 +- `src/pages/dorms/DormRoute.tsx`:唯一接触宿舍功能的文件。功能本身(UI、状态、宿舍 SQL、数据脚本)在 + [`packages/dorm`](../../packages/dorm) 中,在 `/dorms/*` 懒加载。 +- `scripts/`:聊天人设和记忆的 SQL(`scripts/migrations/add_soul_and_memory.sql`),以及 RLS 修复脚本 + `scripts/optimize_rls_policies.sql` 和 `scripts/fix_function_security.sql`。 这里还留着两个已移除的 QMD 知识库的遗留文件,均未被使用:`scripts/qmd-server.mjs`(原 `/api/search` 路由背后的搜索服务)和 `scripts/generate-handbook-ocr.py`(为 QMD 内容生成 OCR 文本的脚本)。没有任何地方引用它们。 @@ -50,41 +53,12 @@ by a Preview build"。所以请运行 `CLOUDFLARE_PREVIEW_BUILD=true pnpm run bu 用 `pnpm run lint` 做 lint,用 `pnpm exec vp fmt --check` 只检查格式(`fmt` 脚本会直接改写文件)。 在仓库根目录,`pnpm exec vp check` 会运行格式、lint 和类型检查(`pnpm run check` 做同样的检查并自动修复)。 -## 宿舍数据库 +## 数据库 -在 Supabase SQL 编辑器中手动执行 SQL。宿舍核心表结构,按以下顺序: - -1. `scripts/migrations/create_dorms_table.sql`。在全新项目上,请先删掉它的最后一行:它给一张仓库里没有任何 - SQL 创建的 `dorm_overrides` 表加注释,SQL 编辑器会因此回滚整个文件。 -2. `scripts/migrations/add_categorized_tags.sql`(可重复执行) -3. `scripts/migrations/add_dorm_address.sql` 和 `scripts/migrations/add_dorm_website.sql`,它们添加 - seed 脚本会写入的 `address`、`address_zh` 和 `website` 列 - -功能相关 SQL,在核心表结构之后执行: - -- `scripts/migrations/create_storage_bucket.sql`:`dorm-images` 存储桶。 -- `add_dorm_edit_history.sql`,然后 `fix_dorm_edit_history_rls.sql`;`add_dorm_comments.sql`,然后 - `add_dorm_comment_hidden.sql`;`add_floor_plan_bed_size.sql`;`add_soul_and_memory.sql`(都在 - `scripts/migrations/` 下)。 -- `scripts/create_dorm_user_features.sql`:宿舍收藏和浏览记录。 +在 Supabase SQL 编辑器中手动执行 SQL。宿舍表、存储桶和种子数据按 +[`packages/dorm`](../../packages/dorm/README_CN.md#宿舍数据库) 中的步骤设置,请先执行那条迁移链。 仓库里的 SQL 并不会创建应用用到的所有表。`conversations`、`messages`、`reading_history`、 -`user_profiles` 和 `mailing_list` 需要自行创建。`scripts/optimize_rls_policies.sql` 和 -`scripts/fix_function_security.sql` 假定其中部分表已存在。已知冲突:`add_categorized_tags.sql` 把 -`bathroom_type` 限定为 `communal`、`semi-private` 和 `private`,但 seed 脚本会为四栋宿舍写入 -`individual-use`。在该约束修改之前,只用这些 SQL 建出的数据库会导致 seed 失败。 - -## 宿舍数据脚本 - -`tsx` 不是依赖项,所以在 `apps/web/` 中用 `pnpm dlx tsx` 运行这些脚本: - -```sh -pnpm dlx tsx scripts/validate-dorm-data.ts # 离线校验内置数据集 -pnpm dlx tsx scripts/audit-dorm-media.ts # 对可疑的媒体 URL 发送 HEAD 请求 -SUPABASE_URL= SUPABASE_SERVICE_KEY= pnpm dlx tsx scripts/seed-dorms-table.ts -``` - -seed 脚本从 shell 环境读取这两个变量,不读取 env 文件(PowerShell 中先用 `$env:NAME = "..."` -设置)。`SUPABASE_SERVICE_KEY` 是会绕过 RLS 的 service-role 密钥。seed 脚本按 `id` 把内置的 -`UIUC_DORMS` upsert 到 `dorms` 表。它保留已存储的图片、图集和户型图媒体,把标签与已存储的标签合并, -且从不删除行。它不会读取已归档的 `dorm_overrides`。 +`user_profiles` 和 `mailing_list` 需要自行创建。然后执行引用了 `conversations` 的 +`scripts/migrations/add_soul_and_memory.sql`。`scripts/optimize_rls_policies.sql` 和 +`scripts/fix_function_security.sql` 假定其中部分表已存在。 diff --git a/packages/dorm/README.md b/packages/dorm/README.md new file mode 100644 index 00000000..81a7983a --- /dev/null +++ b/packages/dorm/README.md @@ -0,0 +1,77 @@ +# @iguide/dorm + +[中文](README_CN.md) + +The dorm (housing) feature: list, map, detail, compare, reviews, favorites, and admin editing, plus its +database SQL, data scripts, and review scrapers. It is a workspace package so dorm code, dependencies +(Mapbox GL, rc-slider, Headless UI), and state stay out of the rest of the app. + +## Boundary + +The host app imports only what `src/index.ts` exports, and the package imports nothing from the host. + +```tsx +import { configureDormServices, DormRoutes } from "@iguide/dorm" + +configureDormServices({ supabase, streamChatResponse }) // once, before DormRoutes renders + +} /> +``` + +- `configureDormServices` lends the host's Supabase client (so dorm queries share its session) and the + chat stream used by the housing assistant. +- `DormRoutes` owns everything under `/dorms`. Dorm data, filters, compare, and favorites are mounted + inside it, so other pages never load dorm code or query dorm tables. +- `layout` is the slice of the host shell the dorm UI drives: the flying-heart target refs and two + slot setters. The dorm sidebar and the dorm list's mobile header portal into those slots, so they + keep dorm context while rendering in the shell. + +In `apps/web` the only file that touches this package is `src/pages/dorms/DormRoute.tsx`, lazy-loaded +by the `/dorms/*` route. + +The host must also compile Tailwind over this package's sources (`@source` in `apps/web/src/index.css`) +and define the `illini-*` theme colors the components use. + +## Layout + +- `src/`: the feature. Its folders mirror where the code lived in `apps/web/src`, so moved files kept + their relative imports and history. +- `scripts/`: dorm database SQL and data scripts. +- `scrapers/`: standalone Puppeteer/Bun review scrapers, outside the workspace (see its README). + +## Dorm database + +Run the SQL by hand in the Supabase SQL editor. Core dorm schema, in this order: + +1. `scripts/migrations/create_dorms_table.sql`. On a fresh project, delete its last line first: it + comments on a `dorm_overrides` table that no tracked SQL creates, and the SQL editor then rolls back + the whole file. +2. `scripts/migrations/add_categorized_tags.sql` (safe to rerun) +3. `scripts/migrations/add_dorm_address.sql` and `scripts/migrations/add_dorm_website.sql`, which add + the `address`, `address_zh` and `website` columns the seed writes + +Feature SQL, after the core schema: + +- `scripts/migrations/create_storage_bucket.sql`: the `dorm-images` storage bucket. +- `add_dorm_edit_history.sql`, then `fix_dorm_edit_history_rls.sql`; `add_dorm_comments.sql`, then + `add_dorm_comment_hidden.sql`; `add_floor_plan_bed_size.sql` (all in `scripts/migrations/`). +- `scripts/create_dorm_user_features.sql`: dorm favorites and viewing history. + +Known conflict: `add_categorized_tags.sql` limits `bathroom_type` to `communal`, `semi-private` and +`private`, but the seed writes `individual-use` for four dorms. Until that constraint changes, the seed +fails on a database built only from this SQL. + +## Dorm data scripts + +`tsx` is not a dependency, so the scripts run through `pnpm dlx tsx`. Run them from this directory: + +```sh +pnpm run validate:data # offline check of the bundled dataset +pnpm run audit:media # sends HEAD requests to suspicious media URLs +SUPABASE_URL= SUPABASE_SERVICE_KEY= pnpm run seed +``` + +The seed reads both variables from the shell, not from env files (in PowerShell, set them first with +`$env:NAME = "..."`). `SUPABASE_SERVICE_KEY` is a service-role key that bypasses RLS. The seed upserts +the bundled `UIUC_DORMS` into `dorms` by `id`. It keeps stored images, gallery and floor-plan media, +merges tags with stored ones, and never deletes rows. It does not read the archived `dorm_overrides`. diff --git a/packages/dorm/README_CN.md b/packages/dorm/README_CN.md new file mode 100644 index 00000000..8b9bd4f5 --- /dev/null +++ b/packages/dorm/README_CN.md @@ -0,0 +1,68 @@ +# @iguide/dorm + +[English](README.md) + +宿舍(住房)功能:列表、地图、详情、对比、评论、收藏和管理员编辑,以及它的数据库 SQL、数据脚本和评论爬虫。 +它是一个 workspace 包,宿舍代码、依赖(Mapbox GL、rc-slider、Headless UI)和状态都不会进入应用的其他部分。 + +## 边界 + +宿主应用只导入 `src/index.ts` 导出的内容,本包不从宿主导入任何东西。 + +```tsx +import { configureDormServices, DormRoutes } from "@iguide/dorm" + +configureDormServices({ supabase, streamChatResponse }) // 在 DormRoutes 渲染前调用一次 + +} /> +``` + +- `configureDormServices` 借用宿主的 Supabase 客户端(宿舍查询因此共用同一个登录会话),以及住房助手使用的聊天流。 +- `DormRoutes` 负责 `/dorms` 下的一切。宿舍数据、筛选、对比和收藏都挂在它内部,其他页面不会加载宿舍代码,也不会查询宿舍表。 +- `layout` 是宿舍 UI 需要操作的那部分宿主外壳:飞心动画的目标 ref 和两个插槽 setter。宿舍侧边栏和宿舍列表的移动端头部通过 + portal 渲染进这些插槽,因此在外壳中渲染时仍能拿到宿舍的 context。 + +在 `apps/web` 中,唯一接触本包的文件是 `src/pages/dorms/DormRoute.tsx`,由 `/dorms/*` 路由懒加载。 + +宿主还必须让 Tailwind 扫描本包的源码(`apps/web/src/index.css` 中的 `@source`),并定义组件用到的 `illini-*` 主题色。 + +## 目录 + +- `src/`:功能代码。目录结构与它在 `apps/web/src` 时一致,所以移动过来的文件保留了相对导入和 git 历史。 +- `scripts/`:宿舍数据库 SQL 和数据脚本。 +- `scrapers/`:独立的 Puppeteer/Bun 评论爬虫,不属于 workspace(见其 README)。 + +## 宿舍数据库 + +在 Supabase SQL 编辑器中手动执行 SQL。宿舍核心表结构,按以下顺序: + +1. `scripts/migrations/create_dorms_table.sql`。在全新项目上,请先删掉它的最后一行:它给一张仓库里没有任何 + SQL 创建的 `dorm_overrides` 表加注释,SQL 编辑器会因此回滚整个文件。 +2. `scripts/migrations/add_categorized_tags.sql`(可重复执行) +3. `scripts/migrations/add_dorm_address.sql` 和 `scripts/migrations/add_dorm_website.sql`,它们添加 + seed 脚本会写入的 `address`、`address_zh` 和 `website` 列 + +功能相关 SQL,在核心表结构之后执行: + +- `scripts/migrations/create_storage_bucket.sql`:`dorm-images` 存储桶。 +- `add_dorm_edit_history.sql`,然后 `fix_dorm_edit_history_rls.sql`;`add_dorm_comments.sql`,然后 + `add_dorm_comment_hidden.sql`;`add_floor_plan_bed_size.sql`(都在 `scripts/migrations/` 下)。 +- `scripts/create_dorm_user_features.sql`:宿舍收藏和浏览记录。 + +已知冲突:`add_categorized_tags.sql` 把 `bathroom_type` 限定为 `communal`、`semi-private` 和 `private`, +但 seed 脚本会为四栋宿舍写入 `individual-use`。在该约束修改之前,只用这些 SQL 建出的数据库会导致 seed 失败。 + +## 宿舍数据脚本 + +`tsx` 不是依赖项,所以这些脚本通过 `pnpm dlx tsx` 运行。在本目录下执行: + +```sh +pnpm run validate:data # 离线校验内置数据集 +pnpm run audit:media # 对可疑的媒体 URL 发送 HEAD 请求 +SUPABASE_URL= SUPABASE_SERVICE_KEY= pnpm run seed +``` + +seed 脚本从 shell 环境读取这两个变量,不读取 env 文件(PowerShell 中先用 `$env:NAME = "..."` +设置)。`SUPABASE_SERVICE_KEY` 是会绕过 RLS 的 service-role 密钥。seed 脚本按 `id` 把内置的 +`UIUC_DORMS` upsert 到 `dorms` 表。它保留已存储的图片、图集和户型图媒体,把标签与已存储的标签合并, +且从不删除行。它不会读取已归档的 `dorm_overrides`。 diff --git a/packages/dorm/src/components/housing/DORM_DATA_AUDIT.md b/packages/dorm/src/components/housing/DORM_DATA_AUDIT.md index 1d4e8ec1..69bf96d0 100644 --- a/packages/dorm/src/components/housing/DORM_DATA_AUDIT.md +++ b/packages/dorm/src/components/housing/DORM_DATA_AUDIT.md @@ -20,7 +20,7 @@ Rules: - Never fill a gap with a plausible guess. Leave the field empty and log it here. - Prefer official sources: housing.illinois.edu, the Office of Housing, the University Housing directory, and the dorm's own published materials. -- Google Maps review scrapers (`dorm_scripts/`) are not authoritative for dorm +- Google Maps review scrapers (`packages/dorm/scrapers/`) are not authoritative for dorm facts; they only supply review text. - When a fact is later resolved or corrected, keep the old entry and append the resolution — the history is the point. From 48575ebf61d887a9dc436921e549c96111c62a3a Mon Sep 17 00:00:00 2001 From: a2751012962 Date: Fri, 2 Oct 2026 14:02:55 +0800 Subject: [PATCH 5/9] ci: run React Doctor on changes to the dorm and ui packages --- .github/workflows/react-doctor.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/react-doctor.yml b/.github/workflows/react-doctor.yml index a55b4a2f..d94c5a5e 100644 --- a/.github/workflows/react-doctor.yml +++ b/.github/workflows/react-doctor.yml @@ -11,12 +11,16 @@ on: pull_request: paths: - "apps/web/**" + - "packages/dorm/**" + - "packages/ui/**" types: [opened, synchronize, reopened, ready_for_review] # Scans `main` on every push to track the health-score trend and catch regressions that slipped past PR review. push: branches: ["main"] paths: - "apps/web/**" + - "packages/dorm/**" + - "packages/ui/**" permissions: contents: read From d68bf88cf6f89fefd0baec9904eacff28cd8d2f5 Mon Sep 17 00:00:00 2001 From: a2751012962 Date: Fri, 2 Oct 2026 14:18:30 +0800 Subject: [PATCH 6/9] fix(dorm): keep dorm filters and compare list when leaving /dorms Moving the providers under the /dorms route made them unmount on every visit elsewhere, resetting filters, search, the compare list, and the loaded dorms. Their state now outlives the route for the page session, as it did when the providers wrapped the whole app; a reload still clears it. --- .../housing/store/CompareContext.tsx | 3 +- .../housing/store/DormDataContext.tsx | 11 +++- .../housing/store/HousingContext.tsx | 65 ++++++++++++++----- .../components/housing/store/retainedState.ts | 22 +++++++ 4 files changed, 81 insertions(+), 20 deletions(-) create mode 100644 packages/dorm/src/components/housing/store/retainedState.ts diff --git a/packages/dorm/src/components/housing/store/CompareContext.tsx b/packages/dorm/src/components/housing/store/CompareContext.tsx index 784c5642..c8c1668d 100644 --- a/packages/dorm/src/components/housing/store/CompareContext.tsx +++ b/packages/dorm/src/components/housing/store/CompareContext.tsx @@ -2,6 +2,7 @@ import React, { createContext, useCallback, useContext, useMemo, useState, React import { Dorm } from "../types/index" import { useDormData } from "./DormDataContext" +import { useRetainedState } from "./retainedState" const MAX_COMPARE = 4 @@ -19,7 +20,7 @@ const CompareContext = createContext(undefined) export const CompareProvider: React.FC<{ children: ReactNode }> = ({ children }) => { const { getDormById } = useDormData() - const [compareIds, setCompareIds] = useState([]) + const [compareIds, setCompareIds] = useRetainedState("compare.ids", []) const [isCompareOpen, setIsCompareOpen] = useState(false) const toggleCompare = useCallback((dormId: string) => { diff --git a/packages/dorm/src/components/housing/store/DormDataContext.tsx b/packages/dorm/src/components/housing/store/DormDataContext.tsx index 294c58db..b2fa8bf0 100644 --- a/packages/dorm/src/components/housing/store/DormDataContext.tsx +++ b/packages/dorm/src/components/housing/store/DormDataContext.tsx @@ -5,11 +5,13 @@ import React, { useEffect, useCallback, useMemo, + useRef, ReactNode, } from "react" import { dormService } from "../../../services/dormService" import { Dorm } from "../types/index" +import { useRetainedState } from "./retainedState" interface DormDataContextType { dorms: Dorm[] @@ -21,8 +23,11 @@ interface DormDataContextType { const DormDataContext = createContext(undefined) export const DormDataProvider: React.FC<{ children: ReactNode }> = ({ children }) => { - const [dorms, setDorms] = useState([]) - const [isLoading, setIsLoading] = useState(true) + // null until the first load finishes, so a later visit to /dorms reuses the list instead of refetching. + const [loadedDorms, setDorms] = useRetainedState("dorms", null) + const dorms = useMemo(() => loadedDorms ?? [], [loadedDorms]) + const [isLoading, setIsLoading] = useState(loadedDorms === null) + const needsInitialLoad = useRef(loadedDorms === null) const loadDorms = useCallback(async () => { setIsLoading(true) @@ -43,6 +48,8 @@ export const DormDataProvider: React.FC<{ children: ReactNode }> = ({ children } }, []) useEffect(() => { + if (!needsInitialLoad.current) return + needsInitialLoad.current = false void loadDorms() }, [loadDorms]) diff --git a/packages/dorm/src/components/housing/store/HousingContext.tsx b/packages/dorm/src/components/housing/store/HousingContext.tsx index 375d6a04..846df977 100644 --- a/packages/dorm/src/components/housing/store/HousingContext.tsx +++ b/packages/dorm/src/components/housing/store/HousingContext.tsx @@ -9,6 +9,7 @@ import { FilterOption, } from "../types/index" import { useDormData } from "./DormDataContext" +import { useRetainedState } from "./retainedState" interface HousingFiltersContextType { searchTerm: string @@ -60,24 +61,54 @@ const HousingMapUiContext = createContext(u export const HousingProvider: React.FC<{ children: ReactNode }> = ({ children }) => { const { dorms } = useDormData() - const [searchTerm, setSearchTerm] = useState("") + const [searchTerm, setSearchTerm] = useRetainedState("housing.searchTerm", "") const [isFilterModalOpen, setIsFilterModalOpen] = useState(false) - const [activeFilters, setActiveFilters] = useState([]) - const [priceRange, setPriceRange] = useState<[number, number]>(getPriceRangeFromData(dorms)) - const [locationFilters, setLocationFilters] = useState([]) - const [bedCountFilters, setBedCountFilters] = useState([]) - const [bathroomCountFilters, setBathroomCountFilters] = useState([]) - const [housingTypeDetails, setHousingTypeDetails] = useState<"ALL" | "URH" | "PCH">("ALL") - const [viewMode, setViewMode] = useState<"list" | "map">("map") - const [sortBy, setSortBy] = useState("name-asc") - const [showZones, setShowZones] = useState(true) - const [showZoneLabels, setShowZoneLabels] = useState(true) - const [showLandmarks, setShowLandmarks] = useState(true) - const [livingConditionFilters, setLivingConditionFilters] = useState([]) - const [facilityFilters, setFacilityFilters] = useState([]) - const [lifestyleFilters, setLifestyleFilters] = useState([]) - const [requireAc, setRequireAc] = useState(false) - const [bathroomTypeFilters, setBathroomTypeFilters] = useState([]) + const [activeFilters, setActiveFilters] = useRetainedState( + "housing.activeFilters", + [], + ) + const [priceRange, setPriceRange] = useRetainedState<[number, number]>( + "housing.priceRange", + getPriceRangeFromData(dorms), + ) + const [locationFilters, setLocationFilters] = useRetainedState( + "housing.locationFilters", + [], + ) + const [bedCountFilters, setBedCountFilters] = useRetainedState( + "housing.bedCountFilters", + [], + ) + const [bathroomCountFilters, setBathroomCountFilters] = useRetainedState( + "housing.bathroomCountFilters", + [], + ) + const [housingTypeDetails, setHousingTypeDetails] = useRetainedState<"ALL" | "URH" | "PCH">( + "housing.housingTypeDetails", + "ALL", + ) + const [viewMode, setViewMode] = useRetainedState<"list" | "map">("housing.viewMode", "map") + const [sortBy, setSortBy] = useRetainedState("housing.sortBy", "name-asc") + const [showZones, setShowZones] = useRetainedState("housing.showZones", true) + const [showZoneLabels, setShowZoneLabels] = useRetainedState("housing.showZoneLabels", true) + const [showLandmarks, setShowLandmarks] = useRetainedState("housing.showLandmarks", true) + const [livingConditionFilters, setLivingConditionFilters] = useRetainedState( + "housing.livingConditionFilters", + [], + ) + const [facilityFilters, setFacilityFilters] = useRetainedState( + "housing.facilityFilters", + [], + ) + const [lifestyleFilters, setLifestyleFilters] = useRetainedState( + "housing.lifestyleFilters", + [], + ) + const [requireAc, setRequireAc] = useRetainedState("housing.requireAc", false) + const [bathroomTypeFilters, setBathroomTypeFilters] = useRetainedState( + "housing.bathroomTypeFilters", + [], + ) const clearAllFilters = useCallback(() => { setSearchTerm("") diff --git a/packages/dorm/src/components/housing/store/retainedState.ts b/packages/dorm/src/components/housing/store/retainedState.ts new file mode 100644 index 00000000..e868cd66 --- /dev/null +++ b/packages/dorm/src/components/housing/store/retainedState.ts @@ -0,0 +1,22 @@ +import { Dispatch, SetStateAction, useEffect, useState } from "react" + +// Lives as long as the page: dorm providers unmount when the user leaves +// /dorms, and this is what brings their state back on return. A reload clears it. +const retained = new Map() + +/** `useState` whose latest value is restored the next time a component with the same key mounts. */ +export const useRetainedState = ( + key: string, + initial: T | (() => T), +): [T, Dispatch>] => { + const [value, setValue] = useState(() => { + if (retained.has(key)) return retained.get(key) as T + return typeof initial === "function" ? (initial as () => T)() : initial + }) + + useEffect(() => { + retained.set(key, value) + }, [key, value]) + + return [value, setValue] +} From c80aef3f3fa6ac3b9f5652819900928b19c534a8 Mon Sep 17 00:00:00 2001 From: a2751012962 Date: Fri, 2 Oct 2026 14:25:51 +0800 Subject: [PATCH 7/9] refactor(dorm): declare retained-state setters as hook dependencies React Doctor's exhaustive-deps cannot tell that useRetainedState returns React's stable setter, so it flagged every callback and memo using one. Listing them changes nothing at runtime and clears those warnings. --- .../housing/store/CompareContext.tsx | 23 +++++++------ .../housing/store/DormDataContext.tsx | 2 +- .../housing/store/HousingContext.tsx | 32 +++++++++++++++++-- 3 files changed, 44 insertions(+), 13 deletions(-) diff --git a/packages/dorm/src/components/housing/store/CompareContext.tsx b/packages/dorm/src/components/housing/store/CompareContext.tsx index c8c1668d..1aa901de 100644 --- a/packages/dorm/src/components/housing/store/CompareContext.tsx +++ b/packages/dorm/src/components/housing/store/CompareContext.tsx @@ -23,20 +23,23 @@ export const CompareProvider: React.FC<{ children: ReactNode }> = ({ children }) const [compareIds, setCompareIds] = useRetainedState("compare.ids", []) const [isCompareOpen, setIsCompareOpen] = useState(false) - const toggleCompare = useCallback((dormId: string) => { - setCompareIds((prev) => { - if (prev.includes(dormId)) { - return prev.filter((id) => id !== dormId) - } - if (prev.length >= MAX_COMPARE) return prev - return [...prev, dormId] - }) - }, []) + const toggleCompare = useCallback( + (dormId: string) => { + setCompareIds((prev) => { + if (prev.includes(dormId)) { + return prev.filter((id) => id !== dormId) + } + if (prev.length >= MAX_COMPARE) return prev + return [...prev, dormId] + }) + }, + [setCompareIds], + ) const clearCompare = useCallback(() => { setCompareIds([]) setIsCompareOpen(false) - }, []) + }, [setCompareIds]) const openCompare = useCallback(() => setIsCompareOpen(true), []) const closeCompare = useCallback(() => setIsCompareOpen(false), []) diff --git a/packages/dorm/src/components/housing/store/DormDataContext.tsx b/packages/dorm/src/components/housing/store/DormDataContext.tsx index b2fa8bf0..91a53cf0 100644 --- a/packages/dorm/src/components/housing/store/DormDataContext.tsx +++ b/packages/dorm/src/components/housing/store/DormDataContext.tsx @@ -45,7 +45,7 @@ export const DormDataProvider: React.FC<{ children: ReactNode }> = ({ children } } finally { setIsLoading(false) } - }, []) + }, [setDorms]) useEffect(() => { if (!needsInitialLoad.current) return diff --git a/packages/dorm/src/components/housing/store/HousingContext.tsx b/packages/dorm/src/components/housing/store/HousingContext.tsx index 846df977..4983e912 100644 --- a/packages/dorm/src/components/housing/store/HousingContext.tsx +++ b/packages/dorm/src/components/housing/store/HousingContext.tsx @@ -123,7 +123,21 @@ export const HousingProvider: React.FC<{ children: ReactNode }> = ({ children }) setLifestyleFilters([]) setRequireAc(false) setBathroomTypeFilters([]) - }, [dorms]) + }, [ + dorms, + setSearchTerm, + setActiveFilters, + setPriceRange, + setLocationFilters, + setBedCountFilters, + setBathroomCountFilters, + setHousingTypeDetails, + setLivingConditionFilters, + setFacilityFilters, + setLifestyleFilters, + setRequireAc, + setBathroomTypeFilters, + ]) const filtersValue = useMemo( () => ({ @@ -176,6 +190,20 @@ export const HousingProvider: React.FC<{ children: ReactNode }> = ({ children }) requireAc, bathroomTypeFilters, clearAllFilters, + setSearchTerm, + setActiveFilters, + setPriceRange, + setLocationFilters, + setBedCountFilters, + setBathroomCountFilters, + setHousingTypeDetails, + setViewMode, + setSortBy, + setLivingConditionFilters, + setFacilityFilters, + setLifestyleFilters, + setRequireAc, + setBathroomTypeFilters, ], ) @@ -188,7 +216,7 @@ export const HousingProvider: React.FC<{ children: ReactNode }> = ({ children }) showLandmarks, setShowLandmarks, }), - [showZones, showZoneLabels, showLandmarks], + [showZones, showZoneLabels, showLandmarks, setShowZones, setShowZoneLabels, setShowLandmarks], ) return ( From 1d6055d7e5e3997a5a2e06ff993c8931a3b25050 Mon Sep 17 00:00:00 2001 From: a2751012962 Date: Fri, 2 Oct 2026 14:28:40 +0800 Subject: [PATCH 8/9] perf(web): memoize the LayoutContext value The provider built a new value object on every Layout render, re-rendering every useLayout consumer, including the dorm route, even when nothing they read had changed. --- apps/web/src/contexts/LayoutContext.tsx | 38 +++++++++++++++---------- 1 file changed, 23 insertions(+), 15 deletions(-) diff --git a/apps/web/src/contexts/LayoutContext.tsx b/apps/web/src/contexts/LayoutContext.tsx index 0c4d502e..49fe36e2 100644 --- a/apps/web/src/contexts/LayoutContext.tsx +++ b/apps/web/src/contexts/LayoutContext.tsx @@ -5,6 +5,7 @@ import React, { RefObject, useState, useCallback, + useMemo, } from "react" interface LayoutContextType { @@ -45,22 +46,29 @@ export const LayoutProvider: React.FC<{ ) const [sidebarSlot, setSidebarSlotState] = useState(null) const setSidebarSlot = useCallback((node: ReactNode | null) => setSidebarSlotState(node), []) - return ( - - {children} - + const value = useMemo( + () => ({ + isSidebarOpen, + favoritesIconRef, + sidebarToggleButtonRef, + mobileSidebarButtonRef, + mobileHeaderSlot, + setMobileHeaderSlot, + sidebarSlot, + setSidebarSlot, + }), + [ + isSidebarOpen, + favoritesIconRef, + sidebarToggleButtonRef, + mobileSidebarButtonRef, + mobileHeaderSlot, + setMobileHeaderSlot, + sidebarSlot, + setSidebarSlot, + ], ) + return {children} } export const useLayout = (): LayoutContextType => { From 5482948f9ca65bb5409c3617a6d801585f1b22f6 Mon Sep 17 00:00:00 2001 From: a2751012962 Date: Fri, 2 Oct 2026 14:28:44 +0800 Subject: [PATCH 9/9] fix(dorm): label the mobile sort button for screen readers --- .../housing/dorm-list/DormListMobileHeader.tsx | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/packages/dorm/src/components/housing/dorm-list/DormListMobileHeader.tsx b/packages/dorm/src/components/housing/dorm-list/DormListMobileHeader.tsx index 3079c325..698271c0 100644 --- a/packages/dorm/src/components/housing/dorm-list/DormListMobileHeader.tsx +++ b/packages/dorm/src/components/housing/dorm-list/DormListMobileHeader.tsx @@ -18,7 +18,8 @@ const SORT_OPTIONS = [ const SortDropdownMobile: React.FC<{ sortBy: string onSortChange: (v: string) => void -}> = ({ sortBy, onSortChange }) => { + label: string +}> = ({ sortBy, onSortChange, label }) => { const [open, setOpen] = React.useState(false) const ref = React.useRef(null) @@ -34,6 +35,8 @@ const SortDropdownMobile: React.FC<{
)}
- +