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 diff --git a/AGENTS.md b/AGENTS.md index 59275697..69f0787e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,7 +1,7 @@ # IlliniGuide agent guide These rules apply repository-wide. `apps/web/AGENTS.md` takes precedence within -`apps/web/**`. +`apps/web/**`, and `packages/dorm/AGENTS.md` within `packages/dorm/**`. ## Project @@ -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. | @@ -84,9 +85,14 @@ Run checks before delivery; `package.json` defines no validation scripts, so ## Architecture -- `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` 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` (`@iguide/dorm`) is the dorm feature: list, Mapbox GL map, + detail, compare, and reviews, plus the dorm SQL, data scripts, and review + scrapers. The SPA mounts it lazily at `/dorms/*` through + `apps/web/src/pages/dorms/DormRoute.tsx`, so no other page loads dorm code or + queries dorm tables. `packages/ui` (`@iguide/ui`) holds UI primitives both + use. - `apps/web/worker` is the Cloudflare Worker named `uiuc`. It routes `/api/*` and serves the SPA's static assets for every other path, so the app and the whole API share one origin. It also hosts the streaming tool-use agent @@ -181,10 +187,11 @@ 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. - `apps/web/AGENTS.md` owns the dorm schema order, the tables the tracked SQL - never creates, the seed scripts, and their known conflicts. + `packages/dorm/AGENTS.md` owns the dorm schema order, the seed scripts, and + their known conflicts. `apps/web/AGENTS.md` owns the tables the tracked SQL + never creates and the chat-owned `add_soul_and_memory.sql`. ## Deploy @@ -218,8 +225,8 @@ the current Git branch. Roll out in this order: -1. Create the tables the tracked SQL omits and run the dorm chain, then seed the - dorms table. Both steps are spelled out in `apps/web/AGENTS.md`. +1. Create the tables the tracked SQL omits (`apps/web/AGENTS.md`), run the dorm + chain, then seed the dorms table (`packages/dorm/AGENTS.md`). 2. Set the Worker secrets: `SUPABASE_URL` and `SUPABASE_ANON_KEY` are what `Env` requires (Cloudflare binds `ASSETS`), but chat needs `DEEPSEEK_API_KEY` and search needs `TAVILY_API_KEY`. diff --git a/README.md b/README.md index 0ba3b1be..7493c5ae 100644 --- a/README.md +++ b/README.md @@ -49,17 +49,18 @@ curl http://localhost:5173/api/health ## Documentation -| Goal | Start here | -| ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Learn the repo rules, commands, and data model | [AGENTS.md](AGENTS.md) | -| Understand the runtime, endpoints, and access | [AGENTS.md](AGENTS.md#architecture) · [AGENTS.md](AGENTS.md#endpoint-access) | -| 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/AGENTS.md](apps/web/AGENTS.md#dorm-database) · [apps/web/scripts/migrations](apps/web/scripts/migrations) · [apps/web/scripts/seed-dorms-table.ts](apps/web/scripts/seed-dorms-table.ts) | -| Deploy and roll back | [AGENTS.md](AGENTS.md#deploy) | -| 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) | +| Understand the runtime, endpoints, and access | [AGENTS.md](AGENTS.md#architecture) · [AGENTS.md](AGENTS.md#endpoint-access) | +| 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 the dorm feature | [packages/dorm/AGENTS.md](packages/dorm/AGENTS.md) · [packages/dorm/README.md](packages/dorm/README.md) | +| Set up dorm tables and seed data | [packages/dorm/AGENTS.md](packages/dorm/AGENTS.md#dorm-database) · [packages/dorm/scripts/migrations](packages/dorm/scripts/migrations) · [packages/dorm/scripts/seed-dorms-table.ts](packages/dorm/scripts/seed-dorms-table.ts) | +| Deploy and roll back | [AGENTS.md](AGENTS.md#deploy) | +| See what runs on pull requests | [.github/workflows/react-doctor.yml](.github/workflows/react-doctor.yml) | ## Development diff --git a/README_CN.md b/README_CN.md index 26d66cd5..4465b337 100644 --- a/README_CN.md +++ b/README_CN.md @@ -49,17 +49,18 @@ curl http://localhost:5173/api/health ## 文档 -| 目标 | 从这里开始 | -| ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| 了解仓库规则、命令和数据模型 | [AGENTS.md](AGENTS.md) | -| 了解运行时、接口和访问模型 | [AGENTS.md](AGENTS.md#architecture) · [AGENTS.md](AGENTS.md#endpoint-access) | -| 在 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/AGENTS.md](apps/web/AGENTS.md#dorm-database) · [apps/web/scripts/migrations](apps/web/scripts/migrations) · [apps/web/scripts/seed-dorms-table.ts](apps/web/scripts/seed-dorms-table.ts) | -| 部署与回滚 | [AGENTS.md](AGENTS.md#deploy) | -| 查看 pull request 上会运行什么 | [.github/workflows/react-doctor.yml](.github/workflows/react-doctor.yml) | +| 目标 | 从这里开始 | +| ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 了解仓库规则、命令和数据模型 | [AGENTS.md](AGENTS.md) | +| 了解运行时、接口和访问模型 | [AGENTS.md](AGENTS.md#architecture) · [AGENTS.md](AGENTS.md#endpoint-access) | +| 在 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) | +| 开发宿舍功能 | [packages/dorm/AGENTS.md](packages/dorm/AGENTS.md) · [packages/dorm/README_CN.md](packages/dorm/README_CN.md) | +| 创建宿舍表并导入种子数据 | [packages/dorm/AGENTS.md](packages/dorm/AGENTS.md#dorm-database) · [packages/dorm/scripts/migrations](packages/dorm/scripts/migrations) · [packages/dorm/scripts/seed-dorms-table.ts](packages/dorm/scripts/seed-dorms-table.ts) | +| 部署与回滚 | [AGENTS.md](AGENTS.md#deploy) | +| 查看 pull request 上会运行什么 | [.github/workflows/react-doctor.yml](.github/workflows/react-doctor.yml) | ## 开发 diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md index f1726180..87ee9cb6 100644 --- a/apps/web/AGENTS.md +++ b/apps/web/AGENTS.md @@ -28,8 +28,10 @@ For repo-wide rules (secrets, CI, Worker retrieval, data model), see the root - Two build outputs exist on purpose. `vp build` produces the SPA in `dist/` (what CI's bundle scan reads); `cf build` produces the Worker plus its static assets under `.cloudflare/output/`. `cf deploy` runs the latter. -- `scripts/` holds the dorm database SQL (`scripts/migrations/*.sql`, - `scripts/*.sql`) and the dorm data scripts. Two unused leftovers from the +- `scripts/` holds the chat persona and memory SQL + (`scripts/migrations/add_soul_and_memory.sql`) and the RLS fixes + (`scripts/optimize_rls_policies.sql`, `scripts/fix_function_security.sql`). + Dorm SQL and data scripts live in `packages/dorm`. 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). @@ -69,8 +71,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 @@ -79,10 +88,10 @@ For structure-affecting changes: 1. Run `vp check` when TypeScript boundaries moved: it type-checks, lints, and formats in one pass (`vp check --fix` to apply fixes). 2. Run `vp build` for renamed imports, route changes, or moved modules. -3. Run `vp dlx tsx scripts/validate-dorm-data.ts` when changing dorm data - contracts. -4. Run `vp dlx tsx scripts/audit-dorm-media.ts` when changing dorm media - sourcing or media validation. +3. Run `vp dlx tsx scripts/validate-dorm-data.ts` from `packages/dorm/` when + changing dorm data contracts. +4. Run `vp dlx tsx scripts/audit-dorm-media.ts` from `packages/dorm/` when + changing dorm media sourcing or media validation. 5. Run the Worker and SPA suites from `apps/web` with `node --test "worker/**/*.test.ts" "src/**/*.test.ts"`. They are `node:test` files, and `vp test` (Vitest) cannot start in this app: the Cloudflare Vite @@ -101,59 +110,16 @@ For structure-affecting changes: `apps/web/` with `vp exec cf workers secrets update --worker uiuc`. - Install the workspace once from the repo root with `vp install`. -## Dorm database +## Database -Run the SQL by hand in the Supabase SQL editor. Core dorm schema, in this order: +Run the SQL by hand in the Supabase SQL editor, starting with the dorm chain in +[`packages/dorm/AGENTS.md`](../../packages/dorm/AGENTS.md#dorm-database). -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. - -The tracked SQL does not create every table the app uses. Create `conversations` -(referenced by `add_soul_and_memory.sql`), `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, and one rejected row fails the whole upsert. Widen the constraint before -seeding: - -```sql -ALTER TABLE public.dorms DROP CONSTRAINT chk_bathroom_type; -ALTER TABLE public.dorms ADD CONSTRAINT chk_bathroom_type - CHECK (bathroom_type IN ('communal', 'individual-use', 'semi-private', 'private')); -``` - -## Dorm data scripts - -`tsx` is not a dependency, so run the scripts with `vp dlx tsx`, from `apps/web/`: - -```sh -vp dlx tsx scripts/validate-dorm-data.ts # offline check of the bundled dataset -vp dlx tsx scripts/audit-dorm-media.ts # sends HEAD requests to suspicious media URLs -SUPABASE_URL= SUPABASE_SERVICE_KEY= vp 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`. +The tracked SQL does not create every table the app uses. Create `conversations`, +`messages`, `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. ## assistant-ui @@ -178,11 +144,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 0b7937f8..1540ffd6 100644 --- a/apps/web/README.md +++ b/apps/web/README.md @@ -13,10 +13,12 @@ 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 and the dorm data scripts. +- `src/pages/dorms/DormRoute.tsx`: the only file that touches the dorm feature, which lives in + [`packages/dorm`](../../packages/dorm) and is lazy-loaded at `/dorms/*`. +- `scripts/`: the chat persona and memory SQL and the RLS fixes. -[AGENTS.md](AGENTS.md) owns where code belongs, which env variables matter, and the dorm database -and seed scripts. +[AGENTS.md](AGENTS.md) owns where code belongs, which env variables matter, and the database setup. +Dorm SQL and seed scripts are in [`packages/dorm/AGENTS.md`](../../packages/dorm/AGENTS.md). ## Setup diff --git a/apps/web/README_CN.md b/apps/web/README_CN.md index 01e61a11..d19c55ad 100644 --- a/apps/web/README_CN.md +++ b/apps/web/README_CN.md @@ -13,9 +13,12 @@ Worker,Worker 负责托管 SPA,并在同源下处理所有 `/api/*` 路由 - `worker/`:Worker,入口 `worker/index.ts`,配置在 `cloudflare.config.ts`。它提供 `/api/chat` (tool-use 智能体,唯一的检索来源是 Tavily 网页搜索)、各模型服务代理、`/api/health` 和 `/api/integrations*`。 -- `scripts/`:宿舍数据库 SQL 和宿舍数据脚本。 +- `src/pages/dorms/DormRoute.tsx`:唯一接触宿舍功能的文件;宿舍功能本身在 + [`packages/dorm`](../../packages/dorm) 中,在 `/dorms/*` 懒加载。 +- `scripts/`:聊天人设和记忆的 SQL 以及 RLS 修复脚本。 -代码放置规则、重要的环境变量,以及宿舍数据库和 seed 脚本都写在 [AGENTS.md](AGENTS.md) 中。 +代码放置规则、重要的环境变量和数据库设置都写在 [AGENTS.md](AGENTS.md) 中。宿舍 SQL 和 seed 脚本见 +[`packages/dorm/AGENTS.md`](../../packages/dorm/AGENTS.md)。 ## 环境配置 diff --git a/apps/web/package.json b/apps/web/package.json index 68ab5525..8d4a3a16 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -9,15 +9,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" @@ -27,7 +25,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/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/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..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 { @@ -18,6 +19,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,20 +44,31 @@ export const LayoutProvider: React.FC<{ (node: ReactNode | null) => setMobileHeaderSlotState(node), [], ) - return ( - - {children} - + const [sidebarSlot, setSidebarSlotState] = useState(null) + const setSidebarSlot = useCallback((node: ReactNode | null) => setSidebarSlotState(node), []) + 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 => { @@ -72,6 +87,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 97078e85..71880656 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -2,6 +2,10 @@ /* [根组件] 全局样式和 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/dorm/src"; +@source "../../../packages/ui/src"; + @theme { --color-illini-blue: #13294b; --color-illini-orange: #ff5f05; @@ -109,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/AGENTS.md b/packages/dorm/AGENTS.md new file mode 100644 index 00000000..cfaec1ec --- /dev/null +++ b/packages/dorm/AGENTS.md @@ -0,0 +1,80 @@ +# AGENTS.md + +Rules for agents working in `packages/dorm/` (`@iguide/dorm`). Repo-wide rules +are in the root [AGENTS.md](../../AGENTS.md). + +## Boundary + +- Hosts import only what `src/index.ts` exports, and this package imports nothing + from any app. What it needs from the host (Supabase client, chat stream, + session, shell slots) comes in through `configureDormServices` and the + `DormRoutes` props. +- Everything under `/dorms` renders inside `DormRoutes`, and dorm providers stay + inside it. State that must survive leaving `/dorms` uses `useRetainedState` + (`src/components/housing/store/retainedState.ts`). +- To draw in the shell (sidebar, mobile header), portal into a slot with + `useShellSlot`; a plain slot node renders outside the dorm providers. +- `src/` mirrors where the code lived in `apps/web/src`. Keep feature UI under + `src/components/housing/`. +- The host compiles Tailwind over `src/` (`@source` in + `apps/web/src/index.css`) and defines the `illini-*` theme colors. + +## Verification + +1. Run `vp check` from the repo root; it type-checks, lints, and formats this + package with the rest. +2. Run `vp build` in `apps/web/` when exports, routes, or Tailwind classes + change, since the host bundles these sources. +3. Run the data scripts below when dorm data contracts or media rules change. + +## 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. + +The app tables this SQL does not create, and the chat-owned +`add_soul_and_memory.sql`, are in +[`apps/web/AGENTS.md`](../../apps/web/AGENTS.md#database). + +Known conflict: `add_categorized_tags.sql` limits `bathroom_type` to `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 +seeding: + +```sql +ALTER TABLE public.dorms DROP CONSTRAINT chk_bathroom_type; +ALTER TABLE public.dorms ADD CONSTRAINT chk_bathroom_type + CHECK (bathroom_type IN ('communal', 'individual-use', 'semi-private', 'private')); +``` + +## Dorm data scripts + +`tsx` is not a dependency, so run the scripts with `vp dlx tsx`, from `packages/dorm/`: + +```sh +vp dlx tsx scripts/validate-dorm-data.ts # offline check of the bundled dataset +vp dlx tsx scripts/audit-dorm-media.ts # sends HEAD requests to suspicious media URLs +SUPABASE_URL= SUPABASE_SERVICE_KEY= vp 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`. diff --git a/packages/dorm/README.md b/packages/dorm/README.md new file mode 100644 index 00000000..14e86121 --- /dev/null +++ b/packages/dorm/README.md @@ -0,0 +1,45 @@ +# @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). + +## Database and data scripts + +The SQL order, the seed and data scripts, and their known conflicts are in +[AGENTS.md](AGENTS.md#dorm-database). diff --git a/packages/dorm/README_CN.md b/packages/dorm/README_CN.md new file mode 100644 index 00000000..92318520 --- /dev/null +++ b/packages/dorm/README_CN.md @@ -0,0 +1,37 @@ +# @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)。 + +## 数据库和数据脚本 + +SQL 执行顺序、seed 与数据脚本以及已知冲突见 [AGENTS.md](AGENTS.md#dorm-database)。 diff --git a/packages/dorm/package.json b/packages/dorm/package.json new file mode 100644 index 00000000..9216947c --- /dev/null +++ b/packages/dorm/package.json @@ -0,0 +1,40 @@ +{ + "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" + }, + "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/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/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 eaf691b5..5f1ce2c2 100644 --- a/apps/web/src/components/housing/AIChat.tsx +++ b/packages/dorm/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" @@ -5,10 +6,9 @@ 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 { Typewriter } from "../ui/Typewriter" import { aiChatTexts } from "./i18n/dormTexts" import { ChatMessage } from "./types/index" diff --git a/apps/web/src/components/housing/DORM_DATA_AUDIT.md b/packages/dorm/src/components/housing/DORM_DATA_AUDIT.md similarity index 91% rename from apps/web/src/components/housing/DORM_DATA_AUDIT.md rename to packages/dorm/src/components/housing/DORM_DATA_AUDIT.md index 1d4e8ec1..69bf96d0 100644 --- a/apps/web/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. 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 98% rename from apps/web/src/components/housing/README.md rename to packages/dorm/src/components/housing/README.md index aa5a6301..cbc5a222 100644 --- a/apps/web/src/components/housing/README.md +++ b/packages/dorm/src/components/housing/README.md @@ -160,7 +160,7 @@ Do not change only the static JSON shape and assume admin or seed will keep up. ## Validation and Checks -When you change housing data or contracts, run, from `apps/web/` +When you change housing data or contracts, run, from `packages/dorm/` (`tsx` is not a dependency, so it is fetched on demand): ```bash 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..698271c0 --- /dev/null +++ b/packages/dorm/src/components/housing/dorm-list/DormListMobileHeader.tsx @@ -0,0 +1,151 @@ +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 + label: string +}> = ({ sortBy, onSortChange, label }) => { + 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 78% rename from apps/web/src/components/housing/store/CompareContext.tsx rename to packages/dorm/src/components/housing/store/CompareContext.tsx index 784c5642..1aa901de 100644 --- a/apps/web/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,23 +20,26 @@ 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) => { - 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/apps/web/src/components/housing/store/DormDataContext.tsx b/packages/dorm/src/components/housing/store/DormDataContext.tsx similarity index 76% rename from apps/web/src/components/housing/store/DormDataContext.tsx rename to packages/dorm/src/components/housing/store/DormDataContext.tsx index 294c58db..91a53cf0 100644 --- a/apps/web/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) @@ -40,9 +45,11 @@ export const DormDataProvider: React.FC<{ children: ReactNode }> = ({ children } } finally { setIsLoading(false) } - }, []) + }, [setDorms]) useEffect(() => { + if (!needsInitialLoad.current) return + needsInitialLoad.current = false void loadDorms() }, [loadDorms]) 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 67% rename from apps/web/src/components/housing/store/HousingContext.tsx rename to packages/dorm/src/components/housing/store/HousingContext.tsx index 375d6a04..4983e912 100644 --- a/apps/web/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("") @@ -92,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( () => ({ @@ -145,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, ], ) @@ -157,7 +216,7 @@ export const HousingProvider: React.FC<{ children: ReactNode }> = ({ children }) showLandmarks, setShowLandmarks, }), - [showZones, showZoneLabels, showLandmarks], + [showZones, showZoneLabels, showLandmarks, setShowZones, setShowZoneLabels, setShowLandmarks], ) return ( 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] +} 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 99% rename from apps/web/src/components/layout/DormSidebar.tsx rename to packages/dorm/src/components/layout/DormSidebar.tsx index d939bcd3..602eb28b 100644 --- a/apps/web/src/components/layout/DormSidebar.tsx +++ b/packages/dorm/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/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/packages/ui/package.json b/packages/ui/package.json new file mode 100644 index 00000000..88a29eef --- /dev/null +++ b/packages/ui/package.json @@ -0,0 +1,23 @@ +{ + "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" + }, + "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..a93bf9d3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -193,9 +193,12 @@ 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 '@supabase/supabase-js': specifier: ^2.117.2 version: 2.117.2 @@ -205,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) @@ -242,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 @@ -282,6 +273,92 @@ 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: + 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..c6f9947e 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/dorm/**", "packages/ui/**"], env: { browser: true }, }, { @@ -39,7 +39,7 @@ export default defineConfig({ rules: { "no-console": "off" }, }, { - files: ["tools/**"], + files: ["tools/**", "packages/dorm/scrapers/**"], env: { node: true }, }, ],