mirror of
https://github.com/temetro/temetro.git
synced 2026-07-26 20:08:14 +00:00
Compare commits
35 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 07cfd5d335 | |||
| c5812511b5 | |||
| 196a22bffd | |||
| 531cbbad7f | |||
| 65975177cf | |||
| 75502ceb60 | |||
| b285158fec | |||
| 0754ce96a4 | |||
| bac3e7a1d0 | |||
| b9d4d4f458 | |||
| aa535f08c4 | |||
| 000591f87f | |||
| 7312d15d67 | |||
| e8f3ed9ffe | |||
| 7c92c03eed | |||
| 5961d969b1 | |||
| fa566ced86 | |||
| 62a5f39683 | |||
| 6127a0ac42 | |||
| 352ca65838 | |||
| 44d653ffbd | |||
| 76da310766 | |||
| c326e9f794 | |||
| b299501ab2 | |||
| 17209a2cf1 | |||
| bd8fdfadda | |||
| 7846dacd42 | |||
| 2c239fbd27 | |||
| bffed5525d | |||
| 591b2f9170 | |||
| b557139752 | |||
| 2d7df1bec0 | |||
| feffce6cbf | |||
| 35f07c508d | |||
| 143ffc39f1 |
@@ -0,0 +1,199 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to the Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by the Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding any notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. Please also get an approval
|
||||
from the project maintainers before using the Apache License.
|
||||
|
||||
Copyright 2025 NextUI Inc.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,140 @@
|
||||
---
|
||||
name: heroui-migration
|
||||
description: "HeroUI v2 to v3 migration guide for agents. Use when migrating HeroUI v2 apps to v3, upgrading components, or accessing migration documentation. Keywords: HeroUI migration, v2 to v3, migration guide, upgrade HeroUI."
|
||||
metadata:
|
||||
author: heroui
|
||||
version: "2.0.0"
|
||||
status: preview
|
||||
---
|
||||
|
||||
# HeroUI v2 to v3 Migration Guide
|
||||
|
||||
This skill helps agents migrate HeroUI v2 applications to v3. HeroUI v3 introduces breaking changes: compound components, no Provider, Tailwind v4, and removed hooks.
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
curl -fsSL https://heroui.com/install | bash -s heroui-migration
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## CRITICAL: Always Fetch Migration Docs Before Applying
|
||||
|
||||
**Do NOT assume v2 patterns work in v3.** Always fetch migration guides before implementing changes.
|
||||
|
||||
### Key v2 → v3 Changes
|
||||
|
||||
| Feature | v2 (Migrate From) | v3 (Migrate To) |
|
||||
| ------------- | -------------------------- | -------------------------------------- |
|
||||
| Provider | `<HeroUIProvider>` required | **No Provider needed** |
|
||||
| Component API | Flat props: `<Card title="x">` | Compound: `<Card><Card.Header>` |
|
||||
| Event handlers | `onClick` | `onPress` |
|
||||
| Styling | `classNames` prop | `className` prop |
|
||||
| Hooks | `useSwitch`, `useDisclosure`, etc. | Compound components, `useOverlayState` |
|
||||
| Packages | `@heroui/system`, `@heroui/theme` | `@heroui/react`, `@heroui/styles` |
|
||||
|
||||
---
|
||||
|
||||
## Accessing Migration Documentation
|
||||
|
||||
**For migration details, examples, and step-by-step guides, always fetch documentation:**
|
||||
|
||||
### Using Scripts
|
||||
|
||||
```bash
|
||||
# List all available component migration guides
|
||||
node scripts/list_migration_guides.mjs
|
||||
|
||||
# Get main migration workflow (full or incremental)
|
||||
node scripts/get_migration_guide.mjs full
|
||||
node scripts/get_migration_guide.mjs incremental
|
||||
|
||||
# Get component-specific migration guides
|
||||
node scripts/get_component_migration_guides.mjs button
|
||||
node scripts/get_component_migration_guides.mjs button card modal
|
||||
|
||||
# Get styling migration guide
|
||||
node scripts/get_styling_migration_guide.mjs
|
||||
|
||||
# Get hooks migration guide
|
||||
node scripts/get_hooks_migration_guide.mjs
|
||||
```
|
||||
|
||||
### Direct URLs
|
||||
|
||||
Migration docs (preview): `https://heroui-git-docs-migration-heroui.vercel.app/docs/react/migration/{filename}`
|
||||
|
||||
Examples:
|
||||
|
||||
- Full migration: `.../agent-guide-full.mdx`
|
||||
- Incremental: `.../agent-guide-incremental.mdx`
|
||||
- Button: `.../button.mdx`
|
||||
- Styling: `.../styling.mdx`
|
||||
- Hooks: `.../hooks.mdx`
|
||||
|
||||
Override base URL with `HEROUI_MIGRATION_DOCS_BASE` when docs are merged to production.
|
||||
|
||||
### MCP Alternative
|
||||
|
||||
When using Cursor or other MCP clients, configure the Migration MCP server for tool-based access:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"heroui-migration": {
|
||||
"url": "https://migration-mcp.heroui.com"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Migration Strategies
|
||||
|
||||
### Full Migration
|
||||
|
||||
- Best for: Projects that can dedicate focused time; teams comfortable with temporarily broken code
|
||||
- Migrate all component code first (project broken during migration)
|
||||
- Switch dependencies to v3
|
||||
- Complete styling migration
|
||||
|
||||
### Incremental Migration
|
||||
|
||||
- Best for: Projects that must stay functional; large codebases migrating gradually
|
||||
- Set up coexistence (pnpm aliases or component packages)
|
||||
- Migrate components one-by-one
|
||||
- Both v2 and v3 coexist during migration
|
||||
|
||||
**Always fetch the agent guide before starting:** `node scripts/get_migration_guide.mjs full` or `incremental`
|
||||
|
||||
---
|
||||
|
||||
## Core Principles
|
||||
|
||||
1. **Fetch first**: Use scripts to get migration guides before applying changes
|
||||
2. **Compound components**: v3 uses `Card.Header`, `Card.Title`, `Button` with children—not flat props
|
||||
3. **No Provider**: Remove `HeroUIProvider` when migrating
|
||||
4. **onPress not onClick**: All interactive components use `onPress`
|
||||
5. **Workflow**: Analyze → Migrate components → Switch deps → Styling migration
|
||||
|
||||
---
|
||||
|
||||
## Migration Workflow Summary
|
||||
|
||||
1. Create migration branch
|
||||
2. Analyze project (HeroUI imports, component usage)
|
||||
3. Fetch main guide: `node scripts/get_migration_guide.mjs full`
|
||||
4. Migrate components in batches (fetch component guides per batch)
|
||||
5. Switch dependencies to v3
|
||||
6. Fetch styling guide: `node scripts/get_styling_migration_guide.mjs`
|
||||
7. Apply styling updates
|
||||
|
||||
---
|
||||
|
||||
## Preview Mode
|
||||
|
||||
This skill targets the staging deployment of the `docs/migration` branch. Once docs are merged to main and live on heroui.com, set `HEROUI_MIGRATION_DOCS_BASE=https://heroui.com/docs/react/migration` or update the default in scripts.
|
||||
@@ -0,0 +1,110 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Get migration guides for HeroUI components (v2 to v3).
|
||||
*
|
||||
* Usage:
|
||||
* node get_component_migration_guides.mjs button
|
||||
* node get_component_migration_guides.mjs button card modal
|
||||
*
|
||||
* Output:
|
||||
* MDX migration guide content for each component
|
||||
*/
|
||||
|
||||
const DOCS_BASE =
|
||||
process.env.HEROUI_MIGRATION_DOCS_BASE ||
|
||||
"https://heroui-git-docs-migration-heroui.vercel.app/docs/react/migration";
|
||||
const APP_PARAM = "app=migration-skills";
|
||||
|
||||
/**
|
||||
* Convert PascalCase or mixed case to kebab-case.
|
||||
*/
|
||||
function toKebabCase(name) {
|
||||
return name
|
||||
.replace(/([a-z])([A-Z])/g, "$1-$2")
|
||||
.replace(/([A-Z])([A-Z][a-z])/g, "$1-$2")
|
||||
.toLowerCase()
|
||||
.trim();
|
||||
}
|
||||
|
||||
async function fetchDoc(filename) {
|
||||
const url = `${DOCS_BASE}/${filename}?${APP_PARAM}`;
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
headers: {"User-Agent": "HeroUI-Migration-Skill/1.0"},
|
||||
signal: AbortSignal.timeout(30000),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
|
||||
return await response.text();
|
||||
} catch (error) {
|
||||
throw new Error(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const args = process.argv.slice(2);
|
||||
|
||||
if (args.length === 0) {
|
||||
console.error("Usage: node get_component_migration_guides.mjs <Component1> [Component2] ...");
|
||||
console.error("Example: node get_component_migration_guides.mjs button card modal");
|
||||
console.error("\nUse list_migration_guides.mjs to see all available components.");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const components = args.map((c) => toKebabCase(c));
|
||||
|
||||
console.error(`# Fetching migration guides for: ${components.join(", ")}...`);
|
||||
|
||||
const results = [];
|
||||
|
||||
for (const component of components) {
|
||||
const filename = `${component}.mdx`;
|
||||
|
||||
try {
|
||||
const content = await fetchDoc(filename);
|
||||
const title = component.charAt(0).toUpperCase() + component.slice(1).replace(/-/g, " ");
|
||||
|
||||
results.push({
|
||||
component,
|
||||
content: `# ${title} Migration Guide\n\n**Component:** ${component}\n**Source:** ${DOCS_BASE}/${filename}\n\n---\n\n${content}`,
|
||||
});
|
||||
} catch (error) {
|
||||
results.push({
|
||||
component,
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const failed = results.filter((r) => r.error);
|
||||
|
||||
if (failed.length > 0) {
|
||||
failed.forEach((r) => console.error(`# Error for ${r.component}: ${r.error}`));
|
||||
}
|
||||
|
||||
if (results.length === 1) {
|
||||
const r = results[0];
|
||||
|
||||
if (r.content) {
|
||||
console.log(r.content);
|
||||
} else {
|
||||
console.log(JSON.stringify(r, null, 2));
|
||||
process.exit(1);
|
||||
}
|
||||
} else {
|
||||
const output = results
|
||||
.map((r) => (r.content ? r.content : `# ${r.component} Migration Guide\n\nError: ${r.error}`))
|
||||
.join("\n\n---\n\n");
|
||||
|
||||
console.log(output);
|
||||
if (failed.length === results.length) {
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Get the hooks migration guide for HeroUI v2 to v3.
|
||||
*
|
||||
* Usage:
|
||||
* node get_hooks_migration_guide.mjs
|
||||
*
|
||||
* Output:
|
||||
* MDX hooks migration guide content
|
||||
*/
|
||||
|
||||
const DOCS_BASE =
|
||||
process.env.HEROUI_MIGRATION_DOCS_BASE ||
|
||||
"https://heroui-git-docs-migration-heroui.vercel.app/docs/react/migration";
|
||||
const APP_PARAM = "app=migration-skills";
|
||||
|
||||
async function fetchDoc(filename) {
|
||||
const url = `${DOCS_BASE}/${filename}?${APP_PARAM}`;
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
headers: {"User-Agent": "HeroUI-Migration-Skill/1.0"},
|
||||
signal: AbortSignal.timeout(30000),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
|
||||
return await response.text();
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to fetch ${filename}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const filename = "hooks.mdx";
|
||||
|
||||
console.error("# Fetching hooks migration guide...");
|
||||
|
||||
try {
|
||||
const content = await fetchDoc(filename);
|
||||
|
||||
console.log(
|
||||
`# HeroUI v2 to v3 Hooks Migration Guide\n\n**Source:** ${DOCS_BASE}/${filename}\n\n---\n\n${content}`,
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(`# Error: ${error.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Get the main migration workflow guide (full or incremental) for HeroUI v2 to v3.
|
||||
*
|
||||
* Usage:
|
||||
* node get_migration_guide.mjs [full|incremental]
|
||||
*
|
||||
* Default: full
|
||||
*
|
||||
* Output:
|
||||
* MDX migration guide content
|
||||
*/
|
||||
|
||||
const DOCS_BASE =
|
||||
process.env.HEROUI_MIGRATION_DOCS_BASE ||
|
||||
"https://heroui-git-docs-migration-heroui.vercel.app/docs/react/migration";
|
||||
const APP_PARAM = "app=migration-skills";
|
||||
|
||||
async function fetchDoc(filename) {
|
||||
const url = `${DOCS_BASE}/${filename}?${APP_PARAM}`;
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
headers: {"User-Agent": "HeroUI-Migration-Skill/1.0"},
|
||||
signal: AbortSignal.timeout(30000),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
|
||||
return await response.text();
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to fetch ${filename}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const arg = (process.argv[2] || "full").toLowerCase();
|
||||
const migrationType = arg === "incremental" ? "incremental" : "full";
|
||||
const filename =
|
||||
migrationType === "incremental" ? "agent-guide-incremental.mdx" : "agent-guide-full.mdx";
|
||||
|
||||
console.error(`# Fetching ${migrationType} migration guide...`);
|
||||
|
||||
try {
|
||||
const content = await fetchDoc(filename);
|
||||
const title =
|
||||
migrationType === "incremental"
|
||||
? "HeroUI v2 to v3 Agent Migration Guide - Incremental Migration"
|
||||
: "HeroUI v2 to v3 Agent Migration Guide - Full Migration";
|
||||
|
||||
console.log(`# ${title}\n\n**Source:** ${DOCS_BASE}/${filename}\n\n---\n\n${content}`);
|
||||
} catch (error) {
|
||||
console.error(`# Error: ${error.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Get the styling migration guide for HeroUI v2 to v3.
|
||||
*
|
||||
* Usage:
|
||||
* node get_styling_migration_guide.mjs
|
||||
*
|
||||
* Output:
|
||||
* MDX styling migration guide content
|
||||
*/
|
||||
|
||||
const DOCS_BASE =
|
||||
process.env.HEROUI_MIGRATION_DOCS_BASE ||
|
||||
"https://heroui-git-docs-migration-heroui.vercel.app/docs/react/migration";
|
||||
const APP_PARAM = "app=migration-skills";
|
||||
|
||||
async function fetchDoc(filename) {
|
||||
const url = `${DOCS_BASE}/${filename}?${APP_PARAM}`;
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
headers: {"User-Agent": "HeroUI-Migration-Skill/1.0"},
|
||||
signal: AbortSignal.timeout(30000),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
|
||||
return await response.text();
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to fetch ${filename}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const filename = "styling.mdx";
|
||||
|
||||
console.error("# Fetching styling migration guide...");
|
||||
|
||||
try {
|
||||
const content = await fetchDoc(filename);
|
||||
|
||||
console.log(
|
||||
`# HeroUI v2 to v3 Styling Migration Guide\n\n**Source:** ${DOCS_BASE}/${filename}\n\n---\n\n${content}`,
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(`# Error: ${error.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* List all available HeroUI v2 to v3 component migration guides.
|
||||
*
|
||||
* Usage:
|
||||
* node list_migration_guides.mjs
|
||||
*
|
||||
* Output:
|
||||
* List of component names that have migration guides
|
||||
*
|
||||
* Note: Keep in sync with migration-mcp list-migration-guides.ts when adding components.
|
||||
*/
|
||||
|
||||
// Component migration guides available - must match migration-mcp list-migration-guides.ts
|
||||
const AVAILABLE_COMPONENTS = [
|
||||
"accordion",
|
||||
"alert",
|
||||
"autocomplete",
|
||||
"avatar",
|
||||
"breadcrumbs",
|
||||
"button",
|
||||
"button-group",
|
||||
"card",
|
||||
"checkbox",
|
||||
"checkbox-group",
|
||||
"chip",
|
||||
"code",
|
||||
"divider",
|
||||
"dropdown",
|
||||
"form",
|
||||
"image",
|
||||
"input",
|
||||
"input-otp",
|
||||
"kbd",
|
||||
"link",
|
||||
"listbox",
|
||||
"modal",
|
||||
"navbar",
|
||||
"numberinput",
|
||||
"popover",
|
||||
"radio",
|
||||
"radio-group",
|
||||
"scroll-shadow",
|
||||
"select",
|
||||
"skeleton",
|
||||
"slider",
|
||||
"snippet",
|
||||
"spacer",
|
||||
"spinner",
|
||||
"switch",
|
||||
"tabs",
|
||||
"toast",
|
||||
"tooltip",
|
||||
"user",
|
||||
];
|
||||
|
||||
function main() {
|
||||
const componentsList = AVAILABLE_COMPONENTS.map((name) => ` - ${name}`).join("\n");
|
||||
|
||||
console.log(
|
||||
`# Available Component Migration Guides\n\nFound ${AVAILABLE_COMPONENTS.length} component migration guides:\n\n${componentsList}\n\nUse get_component_migration_guides.mjs with component names to fetch specific guides.\nExample: node get_component_migration_guides.mjs button card modal`,
|
||||
);
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,199 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to the Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by the Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding any notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. Please also get an approval
|
||||
from the project maintainers before using the Apache License.
|
||||
|
||||
Copyright 2025 NextUI Inc.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,229 @@
|
||||
---
|
||||
name: heroui-native
|
||||
description: "HeroUI Native component library for React Native (Tailwind v4 via Uniwind). Use when building mobile UIs with HeroUI Native — creating Buttons, Cards, TextFields, Dialogs; installing heroui-native; configuring dark/light themes; or fetching component docs. Keywords: HeroUI Native, heroui-native, React Native UI, Uniwind, mobile components."
|
||||
metadata:
|
||||
author: heroui
|
||||
version: "2.0.1"
|
||||
---
|
||||
|
||||
# HeroUI Native Development Guide
|
||||
|
||||
HeroUI Native is a component library built on **Uniwind (Tailwind CSS for React Native)** and **React Native**, providing accessible, customizable UI components for mobile applications.
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
curl -fsSL https://heroui.com/install | bash -s heroui-native
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## CRITICAL: Native Only - Do Not Use Web Patterns
|
||||
|
||||
**This guide is for HeroUI Native ONLY.** Do NOT apply HeroUI React (web) patterns — the package, styling engine, and color format all differ:
|
||||
|
||||
| Feature | React (Web) | Native (Mobile) |
|
||||
| ------------ | -------------------- | ----------------------------------- |
|
||||
| **Styling** | Tailwind CSS v4 | Uniwind (Tailwind for React Native) |
|
||||
| **Colors** | oklch format | HSL format |
|
||||
| **Package** | `@heroui/react` | `heroui-native` |
|
||||
| **Platform** | Web browsers | iOS & Android |
|
||||
|
||||
```tsx
|
||||
// CORRECT — Native pattern
|
||||
import { Button } from "heroui-native";
|
||||
|
||||
<Button variant="primary" onPress={() => console.log("Pressed!")}>
|
||||
Click me
|
||||
</Button>;
|
||||
```
|
||||
|
||||
**Always fetch Native docs before implementing.**
|
||||
|
||||
---
|
||||
|
||||
## Core Principles
|
||||
|
||||
- Semantic variants (`primary`, `secondary`, `tertiary`) over visual descriptions
|
||||
- Composition over configuration (compound components)
|
||||
- Theme variables with HSL color format
|
||||
- React Native StyleSheet patterns with Uniwind utilities
|
||||
|
||||
---
|
||||
|
||||
## Accessing Documentation & Component Information
|
||||
|
||||
**For component details, examples, props, and implementation patterns, always fetch documentation:**
|
||||
|
||||
### Using Scripts
|
||||
|
||||
```bash
|
||||
# List all available components
|
||||
node scripts/list_components.mjs
|
||||
|
||||
# Get component documentation (MDX)
|
||||
node scripts/get_component_docs.mjs Button
|
||||
node scripts/get_component_docs.mjs Button Card TextField
|
||||
|
||||
# Get theme variables
|
||||
node scripts/get_theme.mjs
|
||||
|
||||
# Get non-component docs (guides, releases)
|
||||
node scripts/get_docs.mjs /docs/native/getting-started/theming
|
||||
```
|
||||
|
||||
### Direct MDX URLs
|
||||
|
||||
Component docs: `https://heroui.com/docs/native/components/{component-name}.mdx`
|
||||
|
||||
Examples:
|
||||
|
||||
- Button: `https://heroui.com/docs/native/components/button.mdx`
|
||||
- Dialog: `https://heroui.com/docs/native/components/dialog.mdx`
|
||||
- TextField: `https://heroui.com/docs/native/components/text-field.mdx`
|
||||
|
||||
Getting started guides: `https://heroui.com/docs/native/getting-started/{topic}.mdx`
|
||||
|
||||
**Important:** Always fetch component docs before implementing. The MDX docs include complete examples, props, anatomy, and API references.
|
||||
|
||||
---
|
||||
|
||||
## Installation Essentials
|
||||
|
||||
### Quick Install
|
||||
|
||||
```bash
|
||||
npm i heroui-native react-native-reanimated react-native-gesture-handler react-native-safe-area-context @gorhom/bottom-sheet react-native-svg react-native-worklets tailwind-merge tailwind-variants
|
||||
```
|
||||
|
||||
### Framework Setup (Expo - Recommended)
|
||||
|
||||
1. **Install dependencies:**
|
||||
|
||||
```bash
|
||||
npx create-expo-app MyApp
|
||||
cd MyApp
|
||||
npm i heroui-native uniwind tailwindcss
|
||||
npm i react-native-reanimated react-native-gesture-handler react-native-safe-area-context @gorhom/bottom-sheet react-native-svg react-native-worklets tailwind-merge tailwind-variants
|
||||
```
|
||||
|
||||
2. **Create `global.css`:**
|
||||
|
||||
```css
|
||||
@import "tailwindcss";
|
||||
@import "uniwind";
|
||||
@import "heroui-native/styles";
|
||||
|
||||
@source "./node_modules/heroui-native/lib";
|
||||
```
|
||||
|
||||
3. **Wrap app with providers:**
|
||||
|
||||
```tsx
|
||||
import { GestureHandlerRootView } from "react-native-gesture-handler";
|
||||
import { HeroUINativeProvider } from "heroui-native";
|
||||
import "./global.css";
|
||||
|
||||
export default function Layout() {
|
||||
return (
|
||||
<GestureHandlerRootView style={{ flex: 1 }}>
|
||||
<HeroUINativeProvider>
|
||||
<App />
|
||||
</HeroUINativeProvider>
|
||||
</GestureHandlerRootView>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Critical Setup Requirements
|
||||
|
||||
1. **Uniwind is Required** - HeroUI Native uses Uniwind (Tailwind CSS for React Native)
|
||||
2. **HeroUINativeProvider Required** - Wrap your app with `HeroUINativeProvider`
|
||||
3. **GestureHandlerRootView Required** - Wrap with `GestureHandlerRootView` from react-native-gesture-handler
|
||||
4. **Use Compound Components** - Components use compound structure (e.g., `Card.Header`, `Card.Body`)
|
||||
5. **Use onPress, not onClick** - React Native uses `onPress` event handlers
|
||||
6. **Platform-Specific Code** - Use `Platform.OS` for iOS/Android differences
|
||||
|
||||
---
|
||||
|
||||
## Component Patterns
|
||||
|
||||
HeroUI Native uses **compound component patterns**. Each component has subcomponents accessed via dot notation.
|
||||
|
||||
**Example - Card:**
|
||||
|
||||
```tsx
|
||||
<Card>
|
||||
<Card.Header>{/* Icons, badges */}</Card.Header>
|
||||
<Card.Body>
|
||||
<Card.Title>Title</Card.Title>
|
||||
<Card.Description>Description</Card.Description>
|
||||
</Card.Body>
|
||||
<Card.Footer>{/* Actions */}</Card.Footer>
|
||||
</Card>
|
||||
```
|
||||
|
||||
**Key Points:**
|
||||
|
||||
- Always use compound structure - don't flatten to props
|
||||
- Subcomponents are accessed via dot notation (e.g., `Card.Header`)
|
||||
- Native Card uses `Card.Body` (not `Card.Content`); Title and Description go inside Body
|
||||
- **Fetch component docs for complete anatomy and examples**
|
||||
|
||||
---
|
||||
|
||||
## Semantic Variants
|
||||
|
||||
HeroUI uses semantic naming to communicate functional intent:
|
||||
|
||||
| Variant | Purpose | Usage |
|
||||
| ------------- | --------------------------------- | -------------- |
|
||||
| `primary` | Main action to move forward | 1 per context |
|
||||
| `secondary` | Alternative actions | Multiple |
|
||||
| `tertiary` | Dismissive actions (cancel, skip) | Sparingly |
|
||||
| `danger` | Destructive actions | When needed |
|
||||
| `danger-soft` | Soft destructive actions | Less prominent |
|
||||
| `ghost` | Low-emphasis actions | Minimal weight |
|
||||
| `outline` | Secondary actions | Bordered style |
|
||||
|
||||
**Don't use raw colors** - semantic variants adapt to themes and accessibility.
|
||||
|
||||
---
|
||||
|
||||
## Theming
|
||||
|
||||
HeroUI Native uses CSS variables via Tailwind/Uniwind for theming. Theme colors are defined in `global.css`:
|
||||
|
||||
```css
|
||||
@theme {
|
||||
--color-accent: hsl(260, 100%, 70%);
|
||||
--color-accent-foreground: hsl(0, 0%, 100%);
|
||||
}
|
||||
```
|
||||
|
||||
**Get current theme variables:**
|
||||
|
||||
```bash
|
||||
node scripts/get_theme.mjs
|
||||
```
|
||||
|
||||
**Access theme colors programmatically:**
|
||||
|
||||
```tsx
|
||||
import { useThemeColor } from "heroui-native";
|
||||
|
||||
const accentColor = useThemeColor("accent");
|
||||
```
|
||||
|
||||
**Theme switching (Light/Dark Mode):**
|
||||
|
||||
```tsx
|
||||
import { Uniwind, useUniwind } from "uniwind";
|
||||
|
||||
const { theme } = useUniwind();
|
||||
Uniwind.setTheme(theme === "light" ? "dark" : "light");
|
||||
```
|
||||
|
||||
For detailed theming, fetch: `https://heroui.com/docs/native/getting-started/theming.mdx`
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Get complete component documentation (MDX) for HeroUI Native components.
|
||||
*
|
||||
* Usage:
|
||||
* node get_component_docs.mjs Button
|
||||
* node get_component_docs.mjs Button Card TextField
|
||||
*
|
||||
* Output:
|
||||
* MDX documentation including imports, usage, variants, props, examples
|
||||
*/
|
||||
|
||||
const API_BASE = process.env.HEROUI_NATIVE_API_BASE || "https://native-mcp-api.heroui.com";
|
||||
const FALLBACK_BASE = "https://heroui.com";
|
||||
const APP_PARAM = "app=native-skills";
|
||||
|
||||
/**
|
||||
* Convert PascalCase to kebab-case.
|
||||
*/
|
||||
function toKebabCase(name) {
|
||||
return name
|
||||
.replace(/([a-z])([A-Z])/g, "$1-$2")
|
||||
.replace(/([A-Z])([A-Z][a-z])/g, "$1-$2")
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch data from HeroUI Native API with app parameter for analytics.
|
||||
*/
|
||||
async function fetchApi(endpoint, method = "GET", body = null) {
|
||||
const separator = endpoint.includes("?") ? "&" : "?";
|
||||
const url = `${API_BASE}${endpoint}${separator}${APP_PARAM}`;
|
||||
|
||||
try {
|
||||
const options = {
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"User-Agent": "HeroUI-Native-Skill/1.0",
|
||||
},
|
||||
method,
|
||||
signal: AbortSignal.timeout(30000),
|
||||
};
|
||||
|
||||
if (body) {
|
||||
options.body = JSON.stringify(body);
|
||||
}
|
||||
|
||||
const response = await fetch(url, options);
|
||||
|
||||
if (!response.ok) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch MDX directly from v3.heroui.com as fallback.
|
||||
*/
|
||||
async function fetchFallback(component) {
|
||||
const kebabName = toKebabCase(component);
|
||||
const url = `${FALLBACK_BASE}/docs/native/components/${kebabName}.mdx`;
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
headers: {"User-Agent": "HeroUI-Native-Skill/1.0"},
|
||||
signal: AbortSignal.timeout(30000),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return {component, error: `Failed to fetch docs for ${component}`};
|
||||
}
|
||||
|
||||
const content = await response.text();
|
||||
|
||||
return {
|
||||
component,
|
||||
content,
|
||||
contentType: "mdx",
|
||||
source: "fallback",
|
||||
url,
|
||||
};
|
||||
} catch {
|
||||
return {component, error: `Failed to fetch docs for ${component}`};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Main function to get component documentation.
|
||||
*/
|
||||
async function main() {
|
||||
const args = process.argv.slice(2);
|
||||
|
||||
if (args.length === 0) {
|
||||
console.error("Usage: node get_component_docs.mjs <Component1> [Component2] ...");
|
||||
console.error("Example: node get_component_docs.mjs Button Card");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const components = args;
|
||||
|
||||
// Try API first - use POST /v1/components/docs for batch requests
|
||||
console.error(`# Fetching Native docs for: ${components.join(", ")}...`);
|
||||
const data = await fetchApi("/v1/components/docs", "POST", {components});
|
||||
|
||||
if (data && data.results) {
|
||||
// Output results
|
||||
if (data.results.length === 1) {
|
||||
// Single component - output content directly for easier reading
|
||||
const result = data.results[0];
|
||||
|
||||
if (result.content) {
|
||||
console.log(result.content);
|
||||
} else if (result.error) {
|
||||
console.error(`# Error for ${result.component}: ${result.error}`);
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
} else {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
}
|
||||
} else {
|
||||
// Multiple components - output as JSON array
|
||||
console.log(JSON.stringify(data, null, 2));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Fallback to individual component fetches
|
||||
console.error("# API failed, using fallback...");
|
||||
const results = [];
|
||||
|
||||
for (const component of components) {
|
||||
const result = await fetchFallback(component);
|
||||
|
||||
results.push(result);
|
||||
}
|
||||
|
||||
// Output results
|
||||
if (results.length === 1) {
|
||||
// Single component - output content directly for easier reading
|
||||
const result = results[0];
|
||||
|
||||
if (result.content) {
|
||||
console.log(result.content);
|
||||
} else {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
}
|
||||
} else {
|
||||
// Multiple components - output as JSON array
|
||||
console.log(JSON.stringify(results, null, 2));
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Get non-component HeroUI Native documentation (guides, theming, releases).
|
||||
*
|
||||
* Usage:
|
||||
* node get_docs.mjs /docs/native/getting-started/theming
|
||||
* node get_docs.mjs /docs/native/releases/beta-12
|
||||
*
|
||||
* Output:
|
||||
* MDX documentation content
|
||||
*
|
||||
* Note: For component docs, use get_component_docs.mjs instead.
|
||||
*/
|
||||
|
||||
const API_BASE = process.env.HEROUI_NATIVE_API_BASE || "https://native-mcp-api.heroui.com";
|
||||
const FALLBACK_BASE = "https://heroui.com";
|
||||
const APP_PARAM = "app=native-skills";
|
||||
|
||||
/**
|
||||
* Fetch documentation from HeroUI Native API.
|
||||
* Uses v1 endpoint pattern: /v1/docs/:path
|
||||
*/
|
||||
async function fetchApi(path) {
|
||||
// The v1 API expects path without /docs/ prefix
|
||||
// Input: /docs/native/getting-started/theming
|
||||
// API expects: native/getting-started/theming (route is /v1/docs/:path(*))
|
||||
let apiPath = path.startsWith("/docs/")
|
||||
? path.slice(6) // Remove /docs/ prefix
|
||||
: path.startsWith("/")
|
||||
? path.slice(1) // Remove leading /
|
||||
: path;
|
||||
|
||||
const separator = "?";
|
||||
const url = `${API_BASE}/v1/docs/${apiPath}${separator}${APP_PARAM}`;
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
headers: {"User-Agent": "HeroUI-Native-Skill/1.0"},
|
||||
signal: AbortSignal.timeout(30000),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(`# API Error: HTTP ${response.status}`);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error(`# API Error: ${error.message}`);
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch MDX directly from v3.heroui.com as fallback.
|
||||
*/
|
||||
async function fetchFallback(path) {
|
||||
// Ensure path starts with /docs and ends with .mdx
|
||||
let cleanPath = path.replace(/^\//, "");
|
||||
|
||||
if (!cleanPath.endsWith(".mdx")) {
|
||||
cleanPath = `${cleanPath}.mdx`;
|
||||
}
|
||||
|
||||
const url = `${FALLBACK_BASE}/${cleanPath}`;
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
headers: {"User-Agent": "HeroUI-Native-Skill/1.0"},
|
||||
signal: AbortSignal.timeout(30000),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return {error: `HTTP ${response.status}: ${response.statusText}`, path};
|
||||
}
|
||||
|
||||
const content = await response.text();
|
||||
|
||||
return {
|
||||
content,
|
||||
contentType: "mdx",
|
||||
path,
|
||||
source: "fallback",
|
||||
url,
|
||||
};
|
||||
} catch (error) {
|
||||
return {error: `Fetch Error: ${error.message}`, path};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Main function to get documentation for specified path.
|
||||
*/
|
||||
async function main() {
|
||||
const args = process.argv.slice(2);
|
||||
|
||||
if (args.length === 0) {
|
||||
console.error("Usage: node get_docs.mjs <path>");
|
||||
console.error("Example: node get_docs.mjs /docs/native/getting-started/theming");
|
||||
console.error();
|
||||
console.error("Available paths include:");
|
||||
console.error(" /docs/native/getting-started/theming");
|
||||
console.error(" /docs/native/getting-started/colors");
|
||||
console.error(" /docs/native/getting-started/styling");
|
||||
console.error(" /docs/native/releases/beta-12");
|
||||
console.error();
|
||||
console.error("Note: For component docs, use get_component_docs.mjs instead.");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const path = args[0];
|
||||
|
||||
// Check if user is trying to get component docs
|
||||
if (path.includes("/components/")) {
|
||||
console.error("# Warning: Use get_component_docs.mjs for component documentation.");
|
||||
const componentName = path.split("/").pop().replace(".mdx", "");
|
||||
const titleCase = componentName.charAt(0).toUpperCase() + componentName.slice(1);
|
||||
|
||||
console.error(`# Example: node get_component_docs.mjs ${titleCase}`);
|
||||
}
|
||||
|
||||
// Validate Native path
|
||||
if (!path.startsWith("/docs/native/")) {
|
||||
console.error("# Warning: Native documentation paths should start with /docs/native/");
|
||||
console.error(`# Provided path: ${path}`);
|
||||
}
|
||||
|
||||
console.error(`# Fetching Native documentation for ${path}...`);
|
||||
|
||||
// Try API first
|
||||
const data = await fetchApi(path);
|
||||
|
||||
if (data && data.content) {
|
||||
data.source = "api";
|
||||
console.log(data.content);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Fallback to direct fetch
|
||||
console.error("# API failed, using fallback...");
|
||||
const fallbackData = await fetchFallback(path);
|
||||
|
||||
if (fallbackData.content) {
|
||||
console.log(fallbackData.content);
|
||||
} else {
|
||||
console.log(JSON.stringify(fallbackData, null, 2));
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Get theme variables and design tokens for HeroUI Native.
|
||||
*
|
||||
* Usage:
|
||||
* node get_theme.mjs
|
||||
*
|
||||
* Output:
|
||||
* Theme variables organized by light/dark with HSL color format
|
||||
*/
|
||||
|
||||
const API_BASE = process.env.HEROUI_NATIVE_API_BASE || "https://native-mcp-api.heroui.com";
|
||||
const APP_PARAM = "app=native-skills";
|
||||
|
||||
// Fallback theme reference when API is unavailable
|
||||
const FALLBACK_THEME = {
|
||||
borderRadius: {
|
||||
full: 9999,
|
||||
lg: 12,
|
||||
md: 8,
|
||||
sm: 6,
|
||||
},
|
||||
dark: {
|
||||
colors: [
|
||||
{
|
||||
category: "base",
|
||||
name: "--color-background",
|
||||
value: "hsl(0, 0%, 14.5%)",
|
||||
},
|
||||
{
|
||||
category: "semantic",
|
||||
name: "--color-foreground",
|
||||
value: "hsl(0, 0%, 98.4%)",
|
||||
},
|
||||
{
|
||||
category: "semantic",
|
||||
name: "--color-accent",
|
||||
value: "hsl(264.1, 100%, 55.1%)",
|
||||
},
|
||||
{
|
||||
category: "status",
|
||||
name: "--color-danger",
|
||||
value: "hsl(25.3, 100%, 63.7%)",
|
||||
},
|
||||
{
|
||||
category: "status",
|
||||
name: "--color-success",
|
||||
value: "hsl(163.2, 100%, 76.5%)",
|
||||
},
|
||||
{
|
||||
category: "status",
|
||||
name: "--color-warning",
|
||||
value: "hsl(86.0, 100%, 79.5%)",
|
||||
},
|
||||
],
|
||||
},
|
||||
latestVersion: "beta",
|
||||
light: {
|
||||
colors: [
|
||||
{
|
||||
category: "base",
|
||||
name: "--color-background",
|
||||
value: "hsl(0, 0%, 100%)",
|
||||
},
|
||||
{
|
||||
category: "semantic",
|
||||
name: "--color-foreground",
|
||||
value: "hsl(285.89, 5.9%, 21.03%)",
|
||||
},
|
||||
{
|
||||
category: "semantic",
|
||||
name: "--color-accent",
|
||||
value: "hsl(253.83, 100%, 62.04%)",
|
||||
},
|
||||
{
|
||||
category: "status",
|
||||
name: "--color-danger",
|
||||
value: "hsl(25.74, 100%, 65.32%)",
|
||||
},
|
||||
{
|
||||
category: "status",
|
||||
name: "--color-success",
|
||||
value: "hsl(150.81, 100%, 73.29%)",
|
||||
},
|
||||
{
|
||||
category: "status",
|
||||
name: "--color-warning",
|
||||
value: "hsl(72.33, 100%, 78.19%)",
|
||||
},
|
||||
],
|
||||
},
|
||||
note: "This is a fallback. For complete theme variables, ensure the API is accessible.",
|
||||
opacity: {
|
||||
disabled: 0.4,
|
||||
hover: 0.8,
|
||||
pressed: 0.6,
|
||||
},
|
||||
source: "fallback",
|
||||
theme: "default",
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetch data from HeroUI Native API with app parameter for analytics.
|
||||
*/
|
||||
async function fetchApi(endpoint) {
|
||||
const separator = endpoint.includes("?") ? "&" : "?";
|
||||
const url = `${API_BASE}${endpoint}${separator}${APP_PARAM}`;
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
headers: {"User-Agent": "HeroUI-Native-Skill/1.0"},
|
||||
signal: AbortSignal.timeout(30000),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(`# API Error: HTTP ${response.status}`);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error(`# API Error: ${error.message}`);
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Format colors grouped by category.
|
||||
*/
|
||||
function formatColors(colors) {
|
||||
const grouped = {};
|
||||
|
||||
for (const color of colors) {
|
||||
const category = color.category || "semantic";
|
||||
|
||||
if (!grouped[category]) {
|
||||
grouped[category] = [];
|
||||
}
|
||||
grouped[category].push(color);
|
||||
}
|
||||
|
||||
const lines = [];
|
||||
|
||||
for (const [category, tokens] of Object.entries(grouped)) {
|
||||
lines.push(` /* ${category.charAt(0).toUpperCase() + category.slice(1)} Colors */`);
|
||||
for (const token of tokens) {
|
||||
const name = token.name || "";
|
||||
const value = token.value || "";
|
||||
|
||||
lines.push(` ${name}: ${value};`);
|
||||
}
|
||||
lines.push("");
|
||||
}
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Main function to get theme variables.
|
||||
*/
|
||||
async function main() {
|
||||
console.error("# Fetching Native theme variables...");
|
||||
|
||||
const rawData = await fetchApi("/v1/themes/variables?theme=default");
|
||||
|
||||
let data;
|
||||
let version;
|
||||
|
||||
if (!rawData) {
|
||||
console.error("# API failed, using fallback theme reference...");
|
||||
data = FALLBACK_THEME;
|
||||
version = FALLBACK_THEME.latestVersion || "unknown";
|
||||
} else {
|
||||
// Handle API response format
|
||||
data = rawData;
|
||||
version = rawData.latestVersion || "unknown";
|
||||
}
|
||||
|
||||
// Output as formatted structure for readability
|
||||
console.log("/* HeroUI Native Theme Variables */");
|
||||
console.log(`/* Theme: ${data.theme || "default"} */`);
|
||||
console.log(`/* Version: ${version} */`);
|
||||
console.log();
|
||||
|
||||
// Light mode colors
|
||||
if (data.light && data.light.colors) {
|
||||
console.log("/* Light Mode Colors */");
|
||||
console.log(formatColors(data.light.colors));
|
||||
}
|
||||
|
||||
// Dark mode colors
|
||||
if (data.dark && data.dark.colors) {
|
||||
console.log("/* Dark Mode Colors */");
|
||||
console.log(formatColors(data.dark.colors));
|
||||
}
|
||||
|
||||
// Border radius
|
||||
if (data.borderRadius) {
|
||||
console.log("/* Border Radius */");
|
||||
for (const [key, value] of Object.entries(data.borderRadius)) {
|
||||
console.log(` --radius-${key}: ${value};`);
|
||||
}
|
||||
console.log();
|
||||
}
|
||||
|
||||
// Opacity
|
||||
if (data.opacity) {
|
||||
console.log("/* Opacity */");
|
||||
for (const [key, value] of Object.entries(data.opacity)) {
|
||||
console.log(` --opacity-${key}: ${value};`);
|
||||
}
|
||||
console.log();
|
||||
}
|
||||
|
||||
// Also output raw JSON to stderr for programmatic use
|
||||
console.error("\n# Raw JSON output:");
|
||||
console.error(JSON.stringify(rawData || data, null, 2));
|
||||
}
|
||||
|
||||
main();
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* List all available HeroUI Native components.
|
||||
*
|
||||
* Usage:
|
||||
* node list_components.mjs
|
||||
*
|
||||
* Output:
|
||||
* JSON with components array, latestVersion, and count
|
||||
*/
|
||||
|
||||
const API_BASE = process.env.HEROUI_NATIVE_API_BASE || "https://native-mcp-api.heroui.com";
|
||||
const APP_PARAM = "app=native-skills";
|
||||
const LLMS_TXT_URL = "https://heroui.com/native/llms.txt";
|
||||
|
||||
/**
|
||||
* Fetch data from HeroUI Native API with app parameter for analytics.
|
||||
*/
|
||||
async function fetchApi(endpoint) {
|
||||
const separator = endpoint.includes("?") ? "&" : "?";
|
||||
const url = `${API_BASE}${endpoint}${separator}${APP_PARAM}`;
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
headers: {"User-Agent": "HeroUI-Native-Skill/1.0"},
|
||||
signal: AbortSignal.timeout(30000),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(`HTTP Error ${response.status}: ${response.statusText}`);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error(`API Error: ${error.message}`);
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch component list from llms.txt fallback URL.
|
||||
*/
|
||||
async function fetchFallback() {
|
||||
try {
|
||||
const response = await fetch(LLMS_TXT_URL, {
|
||||
headers: {"User-Agent": "HeroUI-Native-Skill/1.0"},
|
||||
signal: AbortSignal.timeout(30000),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const content = await response.text();
|
||||
|
||||
// Parse markdown to extract component names from pattern: - [ComponentName](url)
|
||||
// Look for links under the Components section (### Components)
|
||||
const components = [];
|
||||
let inComponentsSection = false;
|
||||
|
||||
for (const line of content.split("\n")) {
|
||||
// Check if we're entering the Components section (uses ### header)
|
||||
if (line.trim() === "### Components") {
|
||||
inComponentsSection = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check if we're leaving the Components section (another ### header)
|
||||
if (inComponentsSection && line.trim().startsWith("### ")) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Extract component name from markdown link pattern
|
||||
// Match: - [ComponentName](https://www.heroui.com/docs/native/components/component-name)
|
||||
// Skip "All Components" which links to /components without a specific component
|
||||
if (inComponentsSection) {
|
||||
const match = line.match(
|
||||
/^\s*-\s*\[([^\]]+)\]\(https:\/\/www\.heroui\.com\/docs\/native\/components\/[a-z]/,
|
||||
);
|
||||
|
||||
if (match) {
|
||||
components.push(match[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (components.length > 0) {
|
||||
console.error(`# Using fallback: ${LLMS_TXT_URL}`);
|
||||
|
||||
return {
|
||||
components: components.sort(),
|
||||
count: components.length,
|
||||
latestVersion: "unknown",
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error(`Fallback Error: ${error.message}`);
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Main function to list all available HeroUI Native components.
|
||||
*/
|
||||
async function main() {
|
||||
let data = await fetchApi("/v1/components");
|
||||
|
||||
// Check if API returned valid data with components
|
||||
if (!data || !data.components || data.components.length === 0) {
|
||||
console.error("# API returned no components, trying fallback...");
|
||||
data = await fetchFallback();
|
||||
}
|
||||
|
||||
if (!data || !data.components || data.components.length === 0) {
|
||||
console.error("Error: Failed to fetch component list from API and fallback");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Output formatted JSON
|
||||
console.log(JSON.stringify(data, null, 2));
|
||||
|
||||
// Print summary to stderr for human readability
|
||||
console.error(
|
||||
`\n# Found ${data.components.length} Native components (${data.latestVersion || "unknown"})`,
|
||||
);
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,199 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to the Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by the Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding any notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. Please also get an approval
|
||||
from the project maintainers before using the Apache License.
|
||||
|
||||
Copyright 2025 NextUI Inc.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,234 @@
|
||||
---
|
||||
name: heroui-react
|
||||
description: "HeroUI v3 React component library (Tailwind CSS v4 + React Aria). Use when building UIs with HeroUI — creating Buttons, Modals, Forms, Cards; installing @heroui/react; configuring dark/light themes with oklch variables; or fetching component docs. Keywords: HeroUI, Hero UI, heroui, @heroui/react, @heroui/styles."
|
||||
metadata:
|
||||
author: heroui
|
||||
version: "3.0.1"
|
||||
---
|
||||
|
||||
# HeroUI v3 React Development Guide
|
||||
|
||||
HeroUI v3 is a component library built on **Tailwind CSS v4** and **React Aria Components**, providing accessible, customizable UI components for React applications.
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
curl -fsSL https://heroui.com/install | bash -s heroui-react
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## CRITICAL: v3 Only - Ignore v2 Knowledge
|
||||
|
||||
**This guide is for HeroUI v3 ONLY.** Do NOT apply v2 patterns — the provider, styling, and component API all changed:
|
||||
|
||||
| Feature | v2 (DO NOT USE) | v3 (USE THIS) |
|
||||
| ------------- | --------------------------------- | ------------------------------------------- |
|
||||
| Provider | `<HeroUIProvider>` required | **No Provider needed** |
|
||||
| Animations | `framer-motion` package | CSS-based, no extra deps |
|
||||
| Component API | Flat props: `<Card title="x">` | Compound: `<Card><Card.Header>` |
|
||||
| Styling | Tailwind v3 + `@heroui/theme` | Tailwind v4 + `@heroui/styles` |
|
||||
| Packages | `@heroui/system`, `@heroui/theme` | `@heroui/react`, `@heroui/styles` |
|
||||
|
||||
```tsx
|
||||
// DO NOT DO THIS - v2 pattern
|
||||
import { HeroUIProvider } from "@heroui/react";
|
||||
import { motion } from "framer-motion";
|
||||
|
||||
<HeroUIProvider>
|
||||
<Card title="Product" description="A great product" />
|
||||
</HeroUIProvider>;
|
||||
```
|
||||
|
||||
### CORRECT (v3 patterns)
|
||||
|
||||
```tsx
|
||||
// DO THIS - v3 pattern (no provider, compound components)
|
||||
import { Card } from "@heroui/react";
|
||||
|
||||
<Card>
|
||||
<Card.Header>
|
||||
<Card.Title>Product</Card.Title>
|
||||
<Card.Description>A great product</Card.Description>
|
||||
</Card.Header>
|
||||
</Card>;
|
||||
```
|
||||
|
||||
**Always fetch v3 docs before implementing.**
|
||||
|
||||
---
|
||||
|
||||
## Core Principles
|
||||
|
||||
- Semantic variants (`primary`, `secondary`, `tertiary`) over visual descriptions
|
||||
- Composition over configuration (compound components)
|
||||
- CSS variable-based theming with `oklch` color space
|
||||
- BEM naming convention for predictable styling
|
||||
|
||||
---
|
||||
|
||||
## Accessing Documentation & Component Information
|
||||
|
||||
**For component details, examples, props, and implementation patterns, always fetch documentation:**
|
||||
|
||||
### Using Scripts
|
||||
|
||||
```bash
|
||||
# List all available components
|
||||
node scripts/list_components.mjs
|
||||
|
||||
# Get component documentation (MDX)
|
||||
node scripts/get_component_docs.mjs Button
|
||||
node scripts/get_component_docs.mjs Button Card TextField
|
||||
|
||||
# Get component source code
|
||||
node scripts/get_source.mjs Button
|
||||
|
||||
# Get component CSS styles (BEM classes)
|
||||
node scripts/get_styles.mjs Button
|
||||
|
||||
# Get theme variables
|
||||
node scripts/get_theme.mjs
|
||||
|
||||
# Get non-component docs (guides, releases)
|
||||
node scripts/get_docs.mjs /docs/react/getting-started/theming
|
||||
```
|
||||
|
||||
### Direct MDX URLs
|
||||
|
||||
Component docs: `https://heroui.com/docs/react/components/{component-name}.mdx`
|
||||
|
||||
Examples:
|
||||
|
||||
- Button: `https://heroui.com/docs/react/components/button.mdx`
|
||||
- Modal: `https://heroui.com/docs/react/components/modal.mdx`
|
||||
- Form: `https://heroui.com/docs/react/components/form.mdx`
|
||||
|
||||
Getting started guides: `https://heroui.com/docs/react/getting-started/{topic}.mdx`
|
||||
|
||||
**Important:** Always fetch component docs before implementing. The MDX docs include complete examples, props, anatomy, and API references.
|
||||
|
||||
---
|
||||
|
||||
## Installation Essentials
|
||||
|
||||
### Quick Install
|
||||
|
||||
```bash
|
||||
npm i @heroui/styles @heroui/react tailwind-variants
|
||||
```
|
||||
|
||||
### Framework Setup (Next.js App Router - Recommended)
|
||||
|
||||
1. **Install dependencies:**
|
||||
|
||||
```bash
|
||||
npm i @heroui/styles @heroui/react tailwind-variants tailwindcss @tailwindcss/postcss postcss
|
||||
```
|
||||
|
||||
2. **Create/update `app/globals.css`:**
|
||||
|
||||
```css
|
||||
/* Tailwind CSS v4 - Must be first */
|
||||
@import "tailwindcss";
|
||||
|
||||
/* HeroUI v3 styles - Must be after Tailwind */
|
||||
@import "@heroui/styles";
|
||||
```
|
||||
|
||||
3. **Import in `app/layout.tsx`:**
|
||||
|
||||
```tsx
|
||||
import "./globals.css";
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<html lang="en" suppressHydrationWarning>
|
||||
<body>
|
||||
{/* No Provider needed in HeroUI v3! */}
|
||||
{children}
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
4. **Configure PostCSS (`postcss.config.mjs`):**
|
||||
|
||||
```js
|
||||
export default {
|
||||
plugins: {
|
||||
"@tailwindcss/postcss": {},
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
### Critical Setup Requirements
|
||||
|
||||
1. **Tailwind CSS v4 is MANDATORY** - HeroUI v3 will NOT work with Tailwind CSS v3
|
||||
2. **Use Compound Components** - Components use compound structure (e.g., `Card.Header`, `Card.Content`)
|
||||
3. **Use onPress, not onClick** - For better accessibility, use `onPress` event handlers
|
||||
4. **Import Order Matters** - Always import Tailwind CSS before HeroUI styles
|
||||
|
||||
---
|
||||
|
||||
## Component Patterns
|
||||
|
||||
All components use the **compound pattern** shown above (dot-notation subcomponents like `Card.Header`, `Card.Content`). Don't flatten to props — always compose with subcomponents. Fetch component docs for complete anatomy and examples.
|
||||
|
||||
---
|
||||
|
||||
## Semantic Variants
|
||||
|
||||
HeroUI uses semantic naming to communicate functional intent:
|
||||
|
||||
| Variant | Purpose | Usage |
|
||||
| ----------- | --------------------------------- | -------------- |
|
||||
| `primary` | Main action to move forward | 1 per context |
|
||||
| `secondary` | Alternative actions | Multiple |
|
||||
| `tertiary` | Dismissive actions (cancel, skip) | Sparingly |
|
||||
| `danger` | Destructive actions | When needed |
|
||||
| `ghost` | Low-emphasis actions | Minimal weight |
|
||||
| `outline` | Secondary actions | Bordered style |
|
||||
|
||||
**Don't use raw colors** - semantic variants adapt to themes and accessibility.
|
||||
|
||||
---
|
||||
|
||||
## Theming
|
||||
|
||||
HeroUI v3 uses CSS variables with `oklch` color space:
|
||||
|
||||
```css
|
||||
:root {
|
||||
--accent: oklch(0.6204 0.195 253.83);
|
||||
--accent-foreground: var(--snow);
|
||||
--background: oklch(0.9702 0 0);
|
||||
--foreground: var(--eclipse);
|
||||
}
|
||||
```
|
||||
|
||||
**Get current theme variables:**
|
||||
|
||||
```bash
|
||||
node scripts/get_theme.mjs
|
||||
```
|
||||
|
||||
**Color naming:**
|
||||
|
||||
- Without suffix = background (e.g., `--accent`)
|
||||
- With `-foreground` = text color (e.g., `--accent-foreground`)
|
||||
|
||||
**Theme switching:**
|
||||
|
||||
```html
|
||||
<html class="dark" data-theme="dark"></html>
|
||||
```
|
||||
|
||||
For detailed theming, fetch: `https://heroui.com/docs/react/getting-started/theming.mdx`
|
||||
@@ -0,0 +1,157 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Get complete component documentation (MDX) for HeroUI v3 components.
|
||||
*
|
||||
* Usage:
|
||||
* node get_component_docs.mjs Button
|
||||
* node get_component_docs.mjs Button Card TextField
|
||||
*
|
||||
* Output:
|
||||
* MDX documentation including imports, usage, variants, props, examples
|
||||
*/
|
||||
|
||||
const API_BASE = process.env.HEROUI_API_BASE || "https://mcp-api.heroui.com";
|
||||
const FALLBACK_BASE = "https://heroui.com";
|
||||
const APP_PARAM = "app=react-skills";
|
||||
|
||||
/**
|
||||
* Convert PascalCase to kebab-case.
|
||||
*/
|
||||
function toKebabCase(name) {
|
||||
return name
|
||||
.replace(/([a-z])([A-Z])/g, "$1-$2")
|
||||
.replace(/([A-Z])([A-Z][a-z])/g, "$1-$2")
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch data from HeroUI API with app parameter for analytics.
|
||||
*/
|
||||
async function fetchApi(endpoint, method = "GET", body = null) {
|
||||
const separator = endpoint.includes("?") ? "&" : "?";
|
||||
const url = `${API_BASE}${endpoint}${separator}${APP_PARAM}`;
|
||||
|
||||
try {
|
||||
const options = {
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"User-Agent": "HeroUI-Skill/1.0",
|
||||
},
|
||||
method,
|
||||
signal: AbortSignal.timeout(30000),
|
||||
};
|
||||
|
||||
if (body) {
|
||||
options.body = JSON.stringify(body);
|
||||
}
|
||||
|
||||
const response = await fetch(url, options);
|
||||
|
||||
if (!response.ok) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch MDX directly from v3.heroui.com as fallback.
|
||||
*/
|
||||
async function fetchFallback(component) {
|
||||
const kebabName = toKebabCase(component);
|
||||
const url = `${FALLBACK_BASE}/docs/react/components/${kebabName}.mdx`;
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
headers: {"User-Agent": "HeroUI-Skill/1.0"},
|
||||
signal: AbortSignal.timeout(30000),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return {component, error: `Failed to fetch docs for ${component}`};
|
||||
}
|
||||
|
||||
const content = await response.text();
|
||||
|
||||
return {
|
||||
component,
|
||||
content,
|
||||
contentType: "mdx",
|
||||
source: "fallback",
|
||||
url,
|
||||
};
|
||||
} catch {
|
||||
return {component, error: `Failed to fetch docs for ${component}`};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Main function to get component documentation.
|
||||
*/
|
||||
async function main() {
|
||||
const args = process.argv.slice(2);
|
||||
|
||||
if (args.length === 0) {
|
||||
console.error("Usage: node get_component_docs.mjs <Component1> [Component2] ...");
|
||||
console.error("Example: node get_component_docs.mjs Button Card");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const components = args;
|
||||
|
||||
// Try API first - use POST /v1/components/docs for batch requests
|
||||
console.error(`# Fetching docs for: ${components.join(", ")}...`);
|
||||
const data = await fetchApi("/v1/components/docs", "POST", {components});
|
||||
|
||||
if (data && data.results) {
|
||||
// Output results
|
||||
if (data.results.length === 1) {
|
||||
// Single component - output content directly for easier reading
|
||||
const result = data.results[0];
|
||||
|
||||
if (result.content) {
|
||||
console.log(result.content);
|
||||
} else if (result.error) {
|
||||
console.error(`# Error for ${result.component}: ${result.error}`);
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
} else {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
}
|
||||
} else {
|
||||
// Multiple components - output as JSON array
|
||||
console.log(JSON.stringify(data, null, 2));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Fallback to individual component fetches
|
||||
console.error("# API failed, using fallback...");
|
||||
const results = [];
|
||||
|
||||
for (const component of components) {
|
||||
const result = await fetchFallback(component);
|
||||
|
||||
results.push(result);
|
||||
}
|
||||
|
||||
// Output results
|
||||
if (results.length === 1) {
|
||||
// Single component - output content directly for easier reading
|
||||
const result = results[0];
|
||||
|
||||
if (result.content) {
|
||||
console.log(result.content);
|
||||
} else {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
}
|
||||
} else {
|
||||
// Multiple components - output as JSON array
|
||||
console.log(JSON.stringify(results, null, 2));
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,148 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Get non-component HeroUI documentation (guides, theming, releases).
|
||||
*
|
||||
* Usage:
|
||||
* node get_docs.mjs /docs/react/getting-started/theming
|
||||
* node get_docs.mjs /docs/react/releases/v3-0-0-beta-3
|
||||
*
|
||||
* Output:
|
||||
* MDX documentation content
|
||||
*
|
||||
* Note: For component docs, use get_component_docs.mjs instead.
|
||||
*/
|
||||
|
||||
const API_BASE = process.env.HEROUI_API_BASE || "https://mcp-api.heroui.com";
|
||||
const FALLBACK_BASE = "https://heroui.com";
|
||||
const APP_PARAM = "app=react-skills";
|
||||
|
||||
/**
|
||||
* Fetch documentation from HeroUI API.
|
||||
* Uses v1 endpoint pattern: /v1/docs/:path
|
||||
*/
|
||||
async function fetchApi(path) {
|
||||
// The v1 API expects path without /docs/ prefix
|
||||
// Input: /docs/react/getting-started/theming
|
||||
// API expects: react/getting-started/theming (route is /v1/docs/:path(*))
|
||||
let apiPath = path.startsWith("/docs/")
|
||||
? path.slice(6) // Remove /docs/ prefix
|
||||
: path.startsWith("/")
|
||||
? path.slice(1) // Remove leading /
|
||||
: path;
|
||||
|
||||
const separator = "?";
|
||||
const url = `${API_BASE}/v1/docs/${apiPath}${separator}${APP_PARAM}`;
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
headers: {"User-Agent": "HeroUI-Skill/1.0"},
|
||||
signal: AbortSignal.timeout(30000),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(`# API Error: HTTP ${response.status}`);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error(`# API Error: ${error.message}`);
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch MDX directly from v3.heroui.com as fallback.
|
||||
*/
|
||||
async function fetchFallback(path) {
|
||||
// Ensure path starts with /docs and ends with .mdx
|
||||
let cleanPath = path.replace(/^\//, "");
|
||||
|
||||
if (!cleanPath.endsWith(".mdx")) {
|
||||
cleanPath = `${cleanPath}.mdx`;
|
||||
}
|
||||
|
||||
const url = `${FALLBACK_BASE}/${cleanPath}`;
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
headers: {"User-Agent": "HeroUI-Skill/1.0"},
|
||||
signal: AbortSignal.timeout(30000),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return {error: `HTTP ${response.status}: ${response.statusText}`, path};
|
||||
}
|
||||
|
||||
const content = await response.text();
|
||||
|
||||
return {
|
||||
content,
|
||||
contentType: "mdx",
|
||||
path,
|
||||
source: "fallback",
|
||||
url,
|
||||
};
|
||||
} catch (error) {
|
||||
return {error: `Fetch Error: ${error.message}`, path};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Main function to get documentation for specified path.
|
||||
*/
|
||||
async function main() {
|
||||
const args = process.argv.slice(2);
|
||||
|
||||
if (args.length === 0) {
|
||||
console.error("Usage: node get_docs.mjs <path>");
|
||||
console.error("Example: node get_docs.mjs /docs/react/getting-started/theming");
|
||||
console.error();
|
||||
console.error("Available paths include:");
|
||||
console.error(" /docs/react/getting-started/theming");
|
||||
console.error(" /docs/react/getting-started/colors");
|
||||
console.error(" /docs/react/getting-started/animations");
|
||||
console.error(" /docs/react/releases/v3-0-0-beta-3");
|
||||
console.error();
|
||||
console.error("Note: For component docs, use get_component_docs.mjs instead.");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const path = args[0];
|
||||
|
||||
// Check if user is trying to get component docs
|
||||
if (path.includes("/components/")) {
|
||||
console.error("# Warning: Use get_component_docs.mjs for component documentation.");
|
||||
const componentName = path.split("/").pop().replace(".mdx", "");
|
||||
const titleCase = componentName.charAt(0).toUpperCase() + componentName.slice(1);
|
||||
|
||||
console.error(`# Example: node get_component_docs.mjs ${titleCase}`);
|
||||
}
|
||||
|
||||
console.error(`# Fetching documentation for ${path}...`);
|
||||
|
||||
// Try API first
|
||||
const data = await fetchApi(path);
|
||||
|
||||
if (data && data.content) {
|
||||
data.source = "api";
|
||||
console.log(data.content);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Fallback to direct fetch
|
||||
console.error("# API failed, using fallback...");
|
||||
const fallbackData = await fetchFallback(path);
|
||||
|
||||
if (fallbackData.content) {
|
||||
console.log(fallbackData.content);
|
||||
} else {
|
||||
console.log(JSON.stringify(fallbackData, null, 2));
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,160 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Get React/TypeScript source code implementation for HeroUI v3 components.
|
||||
*
|
||||
* Usage:
|
||||
* node get_source.mjs Button
|
||||
* node get_source.mjs Button Accordion Card
|
||||
*
|
||||
* Output:
|
||||
* Full TSX source code with GitHub URL for each component
|
||||
*/
|
||||
|
||||
const API_BASE = process.env.HEROUI_API_BASE || "https://mcp-api.heroui.com";
|
||||
const GITHUB_RAW_BASE = "https://raw.githubusercontent.com/heroui-inc/heroui/refs/heads/v3";
|
||||
const APP_PARAM = "app=react-skills";
|
||||
|
||||
/**
|
||||
* Fetch data from HeroUI API with app parameter for analytics.
|
||||
*/
|
||||
async function fetchApi(endpoint, method = "GET", body = null) {
|
||||
const separator = endpoint.includes("?") ? "&" : "?";
|
||||
const url = `${API_BASE}${endpoint}${separator}${APP_PARAM}`;
|
||||
|
||||
try {
|
||||
const options = {
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"User-Agent": "HeroUI-Skill/1.0",
|
||||
},
|
||||
method,
|
||||
signal: AbortSignal.timeout(30000),
|
||||
};
|
||||
|
||||
if (body) {
|
||||
options.body = JSON.stringify(body);
|
||||
}
|
||||
|
||||
const response = await fetch(url, options);
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(`# API Error: HTTP ${response.status}`);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error(`# API Error: ${error.message}`);
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch source code directly from GitHub as fallback.
|
||||
*/
|
||||
async function fetchGithubFallback(component) {
|
||||
// Try common patterns for component paths
|
||||
const patterns = [
|
||||
`packages/react/src/components/${component.toLowerCase()}/${component.toLowerCase()}.tsx`,
|
||||
`packages/react/src/components/${component.toLowerCase()}/index.tsx`,
|
||||
];
|
||||
|
||||
for (const path of patterns) {
|
||||
const url = `${GITHUB_RAW_BASE}/${path}`;
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
headers: {"User-Agent": "HeroUI-Skill/1.0"},
|
||||
signal: AbortSignal.timeout(30000),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const content = await response.text();
|
||||
|
||||
return {
|
||||
component,
|
||||
filePath: path,
|
||||
githubUrl: `https://github.com/heroui-inc/heroui/blob/v3/${path}`,
|
||||
source: "fallback",
|
||||
sourceCode: content,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return {component, error: `Failed to fetch source for ${component}`};
|
||||
}
|
||||
|
||||
/**
|
||||
* Main function to get source code for specified components.
|
||||
*/
|
||||
async function main() {
|
||||
const args = process.argv.slice(2);
|
||||
|
||||
if (args.length === 0) {
|
||||
console.error("Usage: node get_source.mjs <Component1> [Component2] ...");
|
||||
console.error("Example: node get_source.mjs Button Accordion");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const components = args;
|
||||
|
||||
// Try API first
|
||||
console.error(`# Fetching source code for: ${components.join(", ")}...`);
|
||||
const data = await fetchApi("/v1/components/source", "POST", {components});
|
||||
|
||||
if (data && data.results) {
|
||||
for (const result of data.results) {
|
||||
result.source = "api";
|
||||
}
|
||||
|
||||
// Output results
|
||||
if (data.results.length === 1) {
|
||||
const result = data.results[0];
|
||||
|
||||
if (result.sourceCode) {
|
||||
console.log(`// File: ${result.filePath || "unknown"}`);
|
||||
console.log(`// GitHub: ${result.githubUrl || "unknown"}`);
|
||||
console.log();
|
||||
console.log(result.sourceCode);
|
||||
} else {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
}
|
||||
} else {
|
||||
console.log(JSON.stringify(data, null, 2));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Fallback to GitHub direct fetch
|
||||
console.error("# API failed, using GitHub fallback...");
|
||||
const results = [];
|
||||
|
||||
for (const component of components) {
|
||||
const result = await fetchGithubFallback(component);
|
||||
|
||||
results.push(result);
|
||||
}
|
||||
|
||||
if (results.length === 1) {
|
||||
const result = results[0];
|
||||
|
||||
if (result.sourceCode) {
|
||||
console.log(`// File: ${result.filePath || "unknown"}`);
|
||||
console.log(`// GitHub: ${result.githubUrl || "unknown"}`);
|
||||
console.log();
|
||||
console.log(result.sourceCode);
|
||||
} else {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
}
|
||||
} else {
|
||||
console.log(JSON.stringify({results}, null, 2));
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,160 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Get CSS styles (BEM classes) for HeroUI v3 components.
|
||||
*
|
||||
* Usage:
|
||||
* node get_styles.mjs Button
|
||||
* node get_styles.mjs Button Card Chip
|
||||
*
|
||||
* Output:
|
||||
* CSS file content with BEM classes and GitHub URL for each component
|
||||
*/
|
||||
|
||||
const API_BASE = process.env.HEROUI_API_BASE || "https://mcp-api.heroui.com";
|
||||
const GITHUB_RAW_BASE = "https://raw.githubusercontent.com/heroui-inc/heroui/refs/heads/v3";
|
||||
const APP_PARAM = "app=react-skills";
|
||||
|
||||
/**
|
||||
* Fetch data from HeroUI API with app parameter for analytics.
|
||||
*/
|
||||
async function fetchApi(endpoint, method = "GET", body = null) {
|
||||
const separator = endpoint.includes("?") ? "&" : "?";
|
||||
const url = `${API_BASE}${endpoint}${separator}${APP_PARAM}`;
|
||||
|
||||
try {
|
||||
const options = {
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"User-Agent": "HeroUI-Skill/1.0",
|
||||
},
|
||||
method,
|
||||
signal: AbortSignal.timeout(30000),
|
||||
};
|
||||
|
||||
if (body) {
|
||||
options.body = JSON.stringify(body);
|
||||
}
|
||||
|
||||
const response = await fetch(url, options);
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(`# API Error: HTTP ${response.status}`);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error(`# API Error: ${error.message}`);
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch CSS styles directly from GitHub as fallback.
|
||||
*/
|
||||
async function fetchGithubFallback(component) {
|
||||
// Try common patterns for style paths
|
||||
const patterns = [
|
||||
`packages/styles/src/components/${component.toLowerCase()}.css`,
|
||||
`packages/styles/components/${component.toLowerCase()}.css`,
|
||||
];
|
||||
|
||||
for (const path of patterns) {
|
||||
const url = `${GITHUB_RAW_BASE}/${path}`;
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
headers: {"User-Agent": "HeroUI-Skill/1.0"},
|
||||
signal: AbortSignal.timeout(30000),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const content = await response.text();
|
||||
|
||||
return {
|
||||
component,
|
||||
filePath: path,
|
||||
githubUrl: `https://github.com/heroui-inc/heroui/blob/v3/${path}`,
|
||||
source: "fallback",
|
||||
stylesCode: content,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return {component, error: `Failed to fetch styles for ${component}`};
|
||||
}
|
||||
|
||||
/**
|
||||
* Main function to get CSS styles for specified components.
|
||||
*/
|
||||
async function main() {
|
||||
const args = process.argv.slice(2);
|
||||
|
||||
if (args.length === 0) {
|
||||
console.error("Usage: node get_styles.mjs <Component1> [Component2] ...");
|
||||
console.error("Example: node get_styles.mjs Button Card");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const components = args;
|
||||
|
||||
// Try API first
|
||||
console.error(`# Fetching styles for: ${components.join(", ")}...`);
|
||||
const data = await fetchApi("/v1/components/styles", "POST", {components});
|
||||
|
||||
if (data && data.results) {
|
||||
for (const result of data.results) {
|
||||
result.source = "api";
|
||||
}
|
||||
|
||||
// Output results
|
||||
if (data.results.length === 1) {
|
||||
const result = data.results[0];
|
||||
|
||||
if (result.stylesCode) {
|
||||
console.log(`/* File: ${result.filePath || "unknown"} */`);
|
||||
console.log(`/* GitHub: ${result.githubUrl || "unknown"} */`);
|
||||
console.log();
|
||||
console.log(result.stylesCode);
|
||||
} else {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
}
|
||||
} else {
|
||||
console.log(JSON.stringify(data, null, 2));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Fallback to GitHub direct fetch
|
||||
console.error("# API failed, using GitHub fallback...");
|
||||
const results = [];
|
||||
|
||||
for (const component of components) {
|
||||
const result = await fetchGithubFallback(component);
|
||||
|
||||
results.push(result);
|
||||
}
|
||||
|
||||
if (results.length === 1) {
|
||||
const result = results[0];
|
||||
|
||||
if (result.stylesCode) {
|
||||
console.log(`/* File: ${result.filePath || "unknown"} */`);
|
||||
console.log(`/* GitHub: ${result.githubUrl || "unknown"} */`);
|
||||
console.log();
|
||||
console.log(result.stylesCode);
|
||||
} else {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
}
|
||||
} else {
|
||||
console.log(JSON.stringify({results}, null, 2));
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,177 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Get theme variables and design tokens for HeroUI v3.
|
||||
*
|
||||
* Usage:
|
||||
* node get_theme.mjs
|
||||
*
|
||||
* Output:
|
||||
* Theme variables organized by common/light/dark with oklch color format
|
||||
*/
|
||||
|
||||
const API_BASE = process.env.HEROUI_API_BASE || "https://mcp-api.heroui.com";
|
||||
const APP_PARAM = "app=react-skills";
|
||||
|
||||
// Fallback theme reference when API is unavailable
|
||||
const FALLBACK_THEME = {
|
||||
common: {
|
||||
base: [
|
||||
{name: "--font-sans", value: "ui-sans-serif, system-ui, sans-serif"},
|
||||
{name: "--font-mono", value: "ui-monospace, monospace"},
|
||||
{name: "--radius-sm", value: "0.375rem"},
|
||||
{name: "--radius-md", value: "0.5rem"},
|
||||
{name: "--radius-lg", value: "0.75rem"},
|
||||
{name: "--radius-full", value: "9999px"},
|
||||
],
|
||||
calculated: [{name: "--spacing-unit", value: "0.25rem"}],
|
||||
},
|
||||
dark: {
|
||||
semantic: [
|
||||
{name: "--color-background", value: "oklch(14.5% 0 0)"},
|
||||
{name: "--color-foreground", value: "oklch(98.4% 0 0)"},
|
||||
{name: "--color-accent", value: "oklch(55.1% 0.228 264.1)"},
|
||||
{name: "--color-danger", value: "oklch(63.7% 0.237 25.3)"},
|
||||
{name: "--color-success", value: "oklch(76.5% 0.177 163.2)"},
|
||||
{name: "--color-warning", value: "oklch(79.5% 0.184 86.0)"},
|
||||
],
|
||||
},
|
||||
latestVersion: "3.0.0-beta",
|
||||
light: {
|
||||
semantic: [
|
||||
{name: "--color-background", value: "oklch(100% 0 0)"},
|
||||
{name: "--color-foreground", value: "oklch(14.5% 0 0)"},
|
||||
{name: "--color-accent", value: "oklch(55.1% 0.228 264.1)"},
|
||||
{name: "--color-danger", value: "oklch(63.7% 0.237 25.3)"},
|
||||
{name: "--color-success", value: "oklch(76.5% 0.177 163.2)"},
|
||||
{name: "--color-warning", value: "oklch(79.5% 0.184 86.0)"},
|
||||
],
|
||||
},
|
||||
note: "This is a fallback. For complete theme variables, ensure the API is accessible.",
|
||||
source: "fallback",
|
||||
theme: "default",
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetch data from HeroUI API with app parameter for analytics.
|
||||
*/
|
||||
async function fetchApi(endpoint) {
|
||||
const separator = endpoint.includes("?") ? "&" : "?";
|
||||
const url = `${API_BASE}${endpoint}${separator}${APP_PARAM}`;
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
headers: {"User-Agent": "HeroUI-Skill/1.0"},
|
||||
signal: AbortSignal.timeout(30000),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(`# API Error: HTTP ${response.status}`);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error(`# API Error: ${error.message}`);
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Format theme variables for display.
|
||||
*/
|
||||
function formatVariables(variables) {
|
||||
const lines = [];
|
||||
|
||||
for (const variable of variables) {
|
||||
const name = variable.name || "";
|
||||
const value = variable.value || "";
|
||||
const desc = variable.description || "";
|
||||
|
||||
if (desc) {
|
||||
lines.push(` ${name}: ${value}; /* ${desc} */`);
|
||||
} else {
|
||||
lines.push(` ${name}: ${value};`);
|
||||
}
|
||||
}
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Main function to get theme variables.
|
||||
*/
|
||||
async function main() {
|
||||
console.error("# Fetching theme variables...");
|
||||
|
||||
const rawData = await fetchApi("/v1/themes/variables?theme=default");
|
||||
|
||||
let data;
|
||||
let version;
|
||||
|
||||
if (!rawData) {
|
||||
console.error("# API failed, using fallback theme reference...");
|
||||
data = FALLBACK_THEME;
|
||||
version = FALLBACK_THEME.latestVersion || "unknown";
|
||||
} else {
|
||||
// Handle API response format: { themes: [...], latestVersion: "..." }
|
||||
if (rawData.themes && rawData.themes.length > 0) {
|
||||
data = rawData.themes[0]; // Get first theme (default)
|
||||
version = rawData.latestVersion || rawData.version || "unknown";
|
||||
} else {
|
||||
// Direct format
|
||||
data = rawData;
|
||||
version = rawData.latestVersion || "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
// Output as formatted CSS-like structure for readability
|
||||
console.log("/* HeroUI v3 Theme Variables */");
|
||||
console.log(`/* Theme: ${data.theme || "default"} */`);
|
||||
console.log(`/* Version: ${version} */`);
|
||||
console.log();
|
||||
|
||||
// Common variables
|
||||
if (data.common) {
|
||||
console.log(":root {");
|
||||
console.log(" /* Base Variables */");
|
||||
if (data.common.base) {
|
||||
console.log(formatVariables(data.common.base));
|
||||
}
|
||||
console.log();
|
||||
console.log(" /* Calculated Variables */");
|
||||
if (data.common.calculated) {
|
||||
console.log(formatVariables(data.common.calculated));
|
||||
}
|
||||
console.log("}");
|
||||
console.log();
|
||||
}
|
||||
|
||||
// Light mode
|
||||
if (data.light) {
|
||||
console.log(":root, [data-theme='light'] {");
|
||||
console.log(" /* Light Mode Semantic Variables */");
|
||||
if (data.light.semantic) {
|
||||
console.log(formatVariables(data.light.semantic));
|
||||
}
|
||||
console.log("}");
|
||||
console.log();
|
||||
}
|
||||
|
||||
// Dark mode
|
||||
if (data.dark) {
|
||||
console.log("[data-theme='dark'] {");
|
||||
console.log(" /* Dark Mode Semantic Variables */");
|
||||
if (data.dark.semantic) {
|
||||
console.log(formatVariables(data.dark.semantic));
|
||||
}
|
||||
console.log("}");
|
||||
}
|
||||
|
||||
// Also output raw JSON to stderr for programmatic use
|
||||
console.error("\n# Raw JSON output:");
|
||||
console.error(JSON.stringify(rawData || data, null, 2));
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,134 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* List all available HeroUI v3 components.
|
||||
*
|
||||
* Usage:
|
||||
* node list_components.mjs
|
||||
*
|
||||
* Output:
|
||||
* JSON with components array, latestVersion, and count
|
||||
*/
|
||||
|
||||
const API_BASE = process.env.HEROUI_API_BASE || "https://mcp-api.heroui.com";
|
||||
const APP_PARAM = "app=react-skills";
|
||||
const LLMS_TXT_URL = "https://heroui.com/react/llms.txt";
|
||||
|
||||
/**
|
||||
* Fetch data from HeroUI API with app parameter for analytics.
|
||||
*/
|
||||
async function fetchApi(endpoint) {
|
||||
const separator = endpoint.includes("?") ? "&" : "?";
|
||||
const url = `${API_BASE}${endpoint}${separator}${APP_PARAM}`;
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
headers: {"User-Agent": "HeroUI-Skill/1.0"},
|
||||
signal: AbortSignal.timeout(30000),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(`HTTP Error ${response.status}: ${response.statusText}`);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error(`API Error: ${error.message}`);
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch component list from llms.txt fallback URL.
|
||||
*/
|
||||
async function fetchFallback() {
|
||||
try {
|
||||
const response = await fetch(LLMS_TXT_URL, {
|
||||
headers: {"User-Agent": "HeroUI-Skill/1.0"},
|
||||
signal: AbortSignal.timeout(30000),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const content = await response.text();
|
||||
|
||||
// Parse markdown to extract component names from pattern: - [ComponentName](url)
|
||||
// Look for links under the Components section (### Components)
|
||||
const components = [];
|
||||
let inComponentsSection = false;
|
||||
|
||||
for (const line of content.split("\n")) {
|
||||
// Check if we're entering the Components section (uses ### header)
|
||||
if (line.trim() === "### Components") {
|
||||
inComponentsSection = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check if we're leaving the Components section (another ### header)
|
||||
if (inComponentsSection && line.trim().startsWith("### ")) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Extract component name from markdown link pattern
|
||||
// Match: - [ComponentName](https://www.heroui.com/docs/react/components/component-name)
|
||||
// Skip "All Components" which links to /components without a specific component
|
||||
if (inComponentsSection) {
|
||||
const match = line.match(
|
||||
/^\s*-\s*\[([^\]]+)\]\(https:\/\/www\.heroui\.com\/docs\/react\/components\/[a-z]/,
|
||||
);
|
||||
|
||||
if (match) {
|
||||
components.push(match[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (components.length > 0) {
|
||||
console.error(`# Using fallback: ${LLMS_TXT_URL}`);
|
||||
|
||||
return {
|
||||
components: components.sort(),
|
||||
count: components.length,
|
||||
latestVersion: "unknown",
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error(`Fallback Error: ${error.message}`);
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Main function to list all available HeroUI v3 components.
|
||||
*/
|
||||
async function main() {
|
||||
let data = await fetchApi("/v1/components");
|
||||
|
||||
// Check if API returned valid data with components
|
||||
if (!data || !data.components || data.components.length === 0) {
|
||||
console.error("# API returned no components, trying fallback...");
|
||||
data = await fetchFallback();
|
||||
}
|
||||
|
||||
if (!data || !data.components || data.components.length === 0) {
|
||||
console.error("Error: Failed to fetch component list from API and fallback");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Output formatted JSON
|
||||
console.log(JSON.stringify(data, null, 2));
|
||||
|
||||
// Print summary to stderr for human readability
|
||||
console.error(
|
||||
`\n# Found ${data.components.length} components (${data.latestVersion || "unknown"})`,
|
||||
);
|
||||
}
|
||||
|
||||
main();
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../.agents/skills/heroui-migration
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../.agents/skills/heroui-native
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../../.agents/skills/heroui-react
|
||||
@@ -0,0 +1,32 @@
|
||||
# Normalize line endings so the repo builds the same on Windows, macOS and Linux.
|
||||
#
|
||||
# Git for Windows installs with core.autocrlf=true by default, which rewrites
|
||||
# checked-out files to CRLF. That is harmless for source we only ever compile,
|
||||
# but fatal for anything the Docker images execute: a shell script whose shebang
|
||||
# becomes "#!/bin/sh\r" fails at container start with
|
||||
# exec /usr/local/bin/docker-entrypoint.sh: no such file or directory
|
||||
# which names the file it just copied in and reads like the file is missing.
|
||||
* text=auto
|
||||
|
||||
# Scripts that run inside a Linux container must stay LF regardless of platform.
|
||||
*.sh text eol=lf
|
||||
docker-entrypoint.sh text eol=lf
|
||||
Dockerfile text eol=lf
|
||||
*.Dockerfile text eol=lf
|
||||
.dockerignore text eol=lf
|
||||
|
||||
# Lockfiles: keep LF so they don't churn across platforms.
|
||||
package-lock.json text eol=lf
|
||||
|
||||
# Binary assets — never touch these.
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.jpeg binary
|
||||
*.gif binary
|
||||
*.ico binary
|
||||
*.webp binary
|
||||
*.woff binary
|
||||
*.woff2 binary
|
||||
*.ttf binary
|
||||
*.otf binary
|
||||
*.pdf binary
|
||||
+104
-28
@@ -3,6 +3,11 @@
|
||||
# Trigger: push a semver tag, e.g.
|
||||
# git tag v0.1.0 && git push origin v0.1.0
|
||||
#
|
||||
# Multi-arch (amd64 + arm64) is built on NATIVE runners — amd64 on ubuntu-24.04,
|
||||
# arm64 on ubuntu-24.04-arm — and merged into a manifest. We do NOT emulate arm64
|
||||
# with QEMU anymore: a runner/QEMU update started crashing `npm ci` under
|
||||
# emulation ("illegal instruction") and hanging the build for hours.
|
||||
#
|
||||
# The frontend image bakes NO API URL — it resolves the backend from the host
|
||||
# the browser uses at runtime — so one published image works for every clinic.
|
||||
#
|
||||
@@ -18,27 +23,30 @@ on:
|
||||
tags:
|
||||
- "v*.*.*"
|
||||
|
||||
permissions:
|
||||
contents: write # create the GitHub Release (the update check reads this)
|
||||
|
||||
env:
|
||||
REGISTRY_NAMESPACE: khalidxv
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
# One build per (image × platform) on the platform's native runner, pushed to
|
||||
# Docker Hub by digest (no tag yet). The merge job stitches the per-arch
|
||||
# digests into a single tagged multi-arch manifest.
|
||||
build:
|
||||
name: Build ${{ matrix.image }} (${{ matrix.platform }})
|
||||
runs-on: ${{ matrix.platform == 'linux/arm64' && 'ubuntu-24.04-arm' || 'ubuntu-24.04' }}
|
||||
timeout-minutes: 40
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
image: [backend, frontend]
|
||||
platform: [linux/amd64, linux/arm64]
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Derive version from tag
|
||||
id: meta
|
||||
run: echo "version=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# QEMU lets the amd64 runner emulate arm64 so the images below build for
|
||||
# both platforms (Intel + Apple Silicon self-hosters).
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
- name: Prepare platform pair
|
||||
run: |
|
||||
platform="${{ matrix.platform }}"
|
||||
echo "PLATFORM_PAIR=${platform//\//-}" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Set up Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
@@ -49,25 +57,93 @@ jobs:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Build & push backend
|
||||
- name: Build & push by digest
|
||||
id: build
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: ./backend
|
||||
push: true
|
||||
platforms: linux/amd64,linux/arm64
|
||||
tags: |
|
||||
${{ env.REGISTRY_NAMESPACE }}/temetro-backend:${{ steps.meta.outputs.version }}
|
||||
${{ env.REGISTRY_NAMESPACE }}/temetro-backend:latest
|
||||
context: ./${{ matrix.image }}
|
||||
platforms: ${{ matrix.platform }}
|
||||
provenance: false
|
||||
outputs: type=image,name=${{ env.REGISTRY_NAMESPACE }}/temetro-${{ matrix.image }},push-by-digest=true,name-canonical=true,push=true
|
||||
|
||||
- name: Build & push frontend
|
||||
uses: docker/build-push-action@v6
|
||||
- name: Export digest
|
||||
run: |
|
||||
mkdir -p "${{ runner.temp }}/digests"
|
||||
digest="${{ steps.build.outputs.digest }}"
|
||||
touch "${{ runner.temp }}/digests/${digest#sha256:}"
|
||||
|
||||
- name: Upload digest
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
context: ./frontend
|
||||
push: true
|
||||
platforms: linux/amd64,linux/arm64
|
||||
tags: |
|
||||
${{ env.REGISTRY_NAMESPACE }}/temetro-frontend:${{ steps.meta.outputs.version }}
|
||||
${{ env.REGISTRY_NAMESPACE }}/temetro-frontend:latest
|
||||
name: digests-${{ matrix.image }}-${{ env.PLATFORM_PAIR }}
|
||||
path: ${{ runner.temp }}/digests/*
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
|
||||
# Combine the per-arch digests for each image into one multi-arch manifest and
|
||||
# tag it (X.Y.Z + latest).
|
||||
merge:
|
||||
name: Merge ${{ matrix.image }} manifest
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
needs: build
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
image: [backend, frontend]
|
||||
steps:
|
||||
- name: Derive version from tag
|
||||
id: meta
|
||||
run: echo "version=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Download digests
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: ${{ runner.temp }}/digests
|
||||
pattern: digests-${{ matrix.image }}-*
|
||||
merge-multiple: true
|
||||
|
||||
- name: Set up Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Create manifest list and push
|
||||
working-directory: ${{ runner.temp }}/digests
|
||||
env:
|
||||
IMAGE: ${{ env.REGISTRY_NAMESPACE }}/temetro-${{ matrix.image }}
|
||||
VERSION: ${{ steps.meta.outputs.version }}
|
||||
run: |
|
||||
docker buildx imagetools create \
|
||||
-t "$IMAGE:$VERSION" \
|
||||
-t "$IMAGE:latest" \
|
||||
$(printf "$IMAGE@sha256:%s " *)
|
||||
|
||||
- name: Inspect
|
||||
env:
|
||||
IMAGE: ${{ env.REGISTRY_NAMESPACE }}/temetro-${{ matrix.image }}
|
||||
VERSION: ${{ steps.meta.outputs.version }}
|
||||
run: docker buildx imagetools inspect "$IMAGE:$VERSION"
|
||||
|
||||
# Both images are published — now cut the GitHub Release with the changelog.
|
||||
release:
|
||||
name: GitHub Release
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
needs: merge
|
||||
permissions:
|
||||
contents: write # create the GitHub Release (the update check reads this)
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Derive version from tag
|
||||
id: meta
|
||||
run: echo "version=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# Pull this version's section out of CHANGELOG.md so the release has real,
|
||||
# human-written notes (the auto "Full Changelog" link is still appended
|
||||
|
||||
@@ -6,6 +6,16 @@
|
||||
"shadcn@latest",
|
||||
"mcp"
|
||||
]
|
||||
},
|
||||
"XcodeBuildMCP": {
|
||||
"type": "stdio",
|
||||
"command": "npx",
|
||||
"args": [
|
||||
"-y",
|
||||
"xcodebuildmcp@latest",
|
||||
"mcp"
|
||||
],
|
||||
"env": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+238
@@ -7,6 +7,244 @@ for how releases are cut and published.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.17.0] — 2026-07-19
|
||||
|
||||
### Changed
|
||||
- **Pharmacy Add-item now uses a hardware barcode scanner.** The inventory Add-item dialog is
|
||||
built for a USB barcode scanner connected to the computer (a keyboard wedge): scanning a
|
||||
medication types the code as a fast keystroke burst ending in Enter, which is parsed and
|
||||
auto-fills the Barcode/NDC, expiry (AI 17), and lot (AI 10) fields — no need to focus any input
|
||||
first. The barcode field also parses on Enter for manual entry. This replaces the camera scanner
|
||||
in this dialog (the camera scanner stays for importing a patient's wallet code)
|
||||
(`frontend/components/pharmacy/add-inventory-dialog.tsx`).
|
||||
- **Care team settings use Separated Panels.** The Care team section now renders as distinct
|
||||
bordered panels on a muted tray, matching the Preferences and AI settings frames
|
||||
(`frontend/components/settings/settings-care-team.tsx`).
|
||||
|
||||
### Fixed
|
||||
- **Pointer cursor on Activity rows.** Hovering an entry in the Activity feed now shows the pointer
|
||||
cursor (`frontend/components/activity/activity-view.tsx`).
|
||||
|
||||
## [0.16.0] — 2026-07-18
|
||||
|
||||
### Added
|
||||
- **Show / Add tabs on the patient record dialog.** Editing a record now opens on a read-only
|
||||
"Show" view (the existing `PatientDetail`), with an "Add" tab for the editable form and its Add
|
||||
buttons. Saving from the Add tab still offers the existing "send to the patient's wallet" step
|
||||
when the patient is wallet-linked (`frontend/components/chat/patient-form-dialog.tsx`).
|
||||
- **Barcode scanning in the pharmacy.** The inventory Add-item dialog can now scan a medication
|
||||
barcode with the camera (`@zxing/browser`, native `BarcodeDetector` where available) into a new
|
||||
Barcode/NDC field, auto-filling expiry (AI 17) and lot (AI 10) from a GS1 DataMatrix. Adds a
|
||||
nullable `inventory.barcode` column (migration `0036`).
|
||||
- **Scan a patient's wallet code when importing.** "Import from a patient app" gains a Scan button
|
||||
that reads the QR or 2D barcode shown in the patient's wallet app and fills the wallet number
|
||||
(`frontend/components/patients/import-from-wallet-dialog.tsx`).
|
||||
|
||||
### Changed
|
||||
- **Settings "separated panels" now match COSS exactly.** The opt-in `separated` settings frames
|
||||
render a real COSS Frame — a muted tray holding distinct bordered panels spaced apart — instead
|
||||
of a `gap-4` bolted onto the panel-fusing `CardFrame`. New `frontend/components/ui/frame.tsx`.
|
||||
|
||||
## [0.15.1] — 2026-07-17
|
||||
|
||||
### Fixed
|
||||
- **Settings frames with more than one panel now breathe.** When a settings section stacked
|
||||
several cards — the AI availability toggles and the patient/account notification lists — the
|
||||
panels sat flush against each other with no gap, reading as one joined block. Those frames now
|
||||
use the COSS "separated panels" spacing (a 1rem gap that keeps each card's rounded corners),
|
||||
while intentional joined lists (care team, records) stay flush. Opt-in via a new `separated`
|
||||
prop on `SettingsFrame`/`SettingsSection` (`frontend/components/settings/settings-parts.tsx`).
|
||||
|
||||
## [0.15.0] — 2026-07-15
|
||||
|
||||
### Fixed
|
||||
- **Prescriptions pushed to a wallet now actually arrive.** `createPrescription` writes to the
|
||||
`prescriptions` table, but the sealed bundle only carried `patient.medications`, which comes from
|
||||
the separate `patient_medications` table and never grows when a prescription is written. The
|
||||
patient approved a bundle identical to what they already had, so nothing appeared in the app's
|
||||
Prescriptions section — the "New prescription: X" line in `changes` is display text, not data.
|
||||
The bundle now ships `prescriptions` alongside the appointments and invoices that were already
|
||||
handled this way, keeping prescriber/status/dates (`backend/src/services/wallet-updates.ts`).
|
||||
- **No more bogus "this clinic's key changed" warnings.** Update events now carry a stable
|
||||
`clinicId`. Wallets pinned a clinic's signing key against its display *name*, which is mutable
|
||||
and falls back to the literal "A clinic" for unnamed orgs — so two unnamed clinics collided on
|
||||
one pin and the second always warned.
|
||||
- **Silent drops on the wallet-push path are now logged.** `sendToWallet` no-ops when an org has no
|
||||
live relay hub, and `applyUpdateResponse` returned `null` without a word when a response arrived
|
||||
unsigned or already resolved. From the clinic side both looked exactly like a patient who never
|
||||
tapped Approve.
|
||||
- **Windows checkouts no longer break the backend image.** The repo had no `.gitattributes`, so Git
|
||||
for Windows' default `core.autocrlf=true` rewrote `docker-entrypoint.sh` to CRLF; the container
|
||||
then died with `exec /usr/local/bin/docker-entrypoint.sh: no such file or directory`. Line
|
||||
endings are pinned, and the image strips CR before `chmod` so existing checkouts are fixed too.
|
||||
- **Settings frames use the COSS default padding.** `CardFramePanel` (added in 0.14.0) isn't part of
|
||||
the COSS registry: its `p-5` inset content twice over, and wrapping the body made every card a
|
||||
grandchild of `CardFrame`, so the frame's direct-child selectors never applied and each card drew
|
||||
its own border — a box inside a box. Body padding now sits on the card, where COSS puts it.
|
||||
- **99 lint errors cleared.** `npm run lint` had been failing (the build hides it via
|
||||
`eslint.ignoreDuringBuilds`). Vendored `components/charts` and `components/ai-elements` are now
|
||||
ignored; the 31 in our own code are fixed. Two were real bugs: the employee dialog could keep a
|
||||
typed password when switching to another member, and the wallet-sync hook could carry a patient's
|
||||
`linked` state to a newly-selected patient, briefly offering to push a record to someone else's
|
||||
wallet.
|
||||
|
||||
### Changed
|
||||
- The clinic→wallet update event carries `clinicId`, and the sealed bundle carries `prescriptions`.
|
||||
Both are additive; older wallets ignore them. See the
|
||||
[signing API docs](https://docs.temetro.com/docs/api/signing#clinic--wallet-record-updates).
|
||||
|
||||
## [0.14.2] — 2026-07-15
|
||||
|
||||
### Fixed
|
||||
- **Docker images build on ARM64 again.** Next 16's default Turbopack production build has no native
|
||||
bindings for `linux/arm64` in the Alpine image, so `docker compose up --build` failed with
|
||||
"Turbopack is not supported on this platform". The frontend now builds with Webpack
|
||||
(`next build --webpack`), which builds on every architecture (`frontend/package.json`).
|
||||
|
||||
## [0.14.1] — 2026-07-15
|
||||
|
||||
### Fixed
|
||||
- **"Send to wallet" now works from every dialog, not just the patient sheet.** The wallet step in
|
||||
the appointment, invoice, prescription, patient-edit, and scribe dialogs was gated on a wallet-link
|
||||
check that resolved asynchronously; if the clinician saved before it resolved (or it briefly
|
||||
failed), the dialog silently closed without pushing. The dialogs now await the link check before
|
||||
deciding, and an empty change summary can no longer be sent
|
||||
(`frontend/components/wallet/use-wallet-sync.ts`, `wallet-sync-step.tsx`).
|
||||
|
||||
### Changed
|
||||
- **Settings sections composed from `CardFrame` primitives.** Each settings section now builds on
|
||||
`CardFrameHeader`/`CardFrameTitle`/`CardFrameDescription` + a new `CardFramePanel` body, and the
|
||||
per-row `SettingsCard` renders a real `Card`, giving a consistent framed surface
|
||||
(`frontend/components/ui/card.tsx`, `frontend/components/settings/settings-parts.tsx`).
|
||||
|
||||
## [0.14.0] — 2026-07-13
|
||||
|
||||
### Changed
|
||||
- **Patients page filter moved to its own row.** The status filter left the toolbar and now sits on a
|
||||
dedicated **"Filter"** row directly above the table, so the header stays a clean title + search +
|
||||
"Add patient" + `⋯` cluster (`frontend/components/patients/patients-view.tsx`).
|
||||
- **Patient detail sheet header.** The patient name, status badge, and the `⋯` menu now share one
|
||||
left-aligned row, and the standalone **Edit** button moved to be the first item inside the `⋯` menu
|
||||
(`frontend/components/patients/patient-detail.tsx`).
|
||||
- **Settings redesigned with the COSS frame surface.** Every settings section now renders in a
|
||||
`CardFrame` (header + body) via a new `SettingsFrame` part, replacing the flat `SettingsCard` divs
|
||||
(`frontend/components/settings/settings-parts.tsx`, `settings-ai.tsx`).
|
||||
|
||||
### Added
|
||||
- **AI Mode: Automatic and Off.** Settings → AI gains two modes beyond API / Local: **Automatic**
|
||||
(use a cloud API key when set, else fall back to local Ollama) and **Off** (assistant disabled).
|
||||
Automatic is the new default, so a fresh install shows the setup banner until a provider is wired
|
||||
(`frontend/lib/ai-settings.ts`, `backend/src/services/ai/{config,provider}.ts`, `types/ai.ts`).
|
||||
|
||||
### Fixed
|
||||
- **AI setup banner now appears when no provider is configured.** Previously the defaulted Ollama URL
|
||||
counted as "configured," so the "connect an AI model" banner never showed; it now reflects the
|
||||
actual mode (`frontend/components/chat/ai-setup-notice.tsx`).
|
||||
- **Chat cards no longer silently vanish.** An unrecognized/renamed streamed data part now renders a
|
||||
small placeholder instead of nothing (`frontend/components/chat/chat-panel.tsx`).
|
||||
|
||||
### Wallet app
|
||||
- **Documents/files reach the wallet.** Clinic record-update pushes now include attachment metadata,
|
||||
which the wallet folds into the record so the **Documents** tile counts them and the Documents
|
||||
screen lists them (`backend/src/services/wallet-updates.ts`, `temetro-app` types + home/documents).
|
||||
- **Failed pushes are no longer swallowed.** A record update that fails signature verification or
|
||||
decoding is now logged (and a "couldn't verify" notice is raised) instead of disappearing silently.
|
||||
- **i18next translation.** The wallet app now uses `i18next` + `react-i18next` + `expo-localization`
|
||||
(English shipped; other locales can be added later), with the home, record-update inbox, navigation
|
||||
titles, and the visits/prescriptions-adjacent detail screens extracted to translation keys.
|
||||
|
||||
## [0.13.1] — 2026-07-13
|
||||
|
||||
### Changed
|
||||
- **New Invoice checkboxes.** The Back-date / Due-date toggles now use the COSS `Checkbox`
|
||||
(`frontend/components/ui/checkbox.tsx`) instead of raw, misshapen native checkboxes.
|
||||
- **Patients page toolbar & table.** The list is now a COSS **Table in a `CardFrame`**
|
||||
(`frontend/components/ui/table.tsx`), and the secondary "Import from a patient app" action moved
|
||||
into a `⋯` overflow menu so the toolbar keeps a single primary "Add patient" CTA.
|
||||
- **Patient detail sheet header.** The five action buttons plus delete collapse into a primary
|
||||
**Edit** button and a `⋯ More` menu (Download summary, Record visit, Transfer, Push to wallet, and
|
||||
a destructive Delete).
|
||||
|
||||
### Wallet app
|
||||
- **Home quick actions open sheets.** "Share record" now opens a bottom sheet with a scannable **QR**
|
||||
of the wallet number (`react-native-qrcode-svg`); "My wallet" opens a bottom sheet with copyable
|
||||
wallet number / fingerprint / algorithm; and the duplicate "Notifications" action (the header
|
||||
already has a bell) is replaced with **Scan**.
|
||||
|
||||
## [0.13.0] — 2026-07-12
|
||||
|
||||
### Added
|
||||
- **Prescription date pickers.** The New Prescription dialog's Start/End date now use a proper COSS
|
||||
date picker (`frontend/components/ui/date-picker.tsx`, Popover + Calendar) instead of the raw
|
||||
native date input.
|
||||
- **Working profile fields.** Settings → Profile **Specialty** (a Select) and **Professional links**
|
||||
(editable rows) are now wired to persisted preferences — previously they were inert stubs.
|
||||
- **Patient filters.** The Patients page gains a status filter (all / active / inpatient /
|
||||
discharged) and its search now also matches conditions and allergies.
|
||||
- **Language quick-switch.** A language submenu in the sidebar user menu (alongside Theme), applied
|
||||
immediately with Arabic RTL.
|
||||
- **Wallet app — home & settings.** The patient app home screen adds a quick-action row (Share
|
||||
record / My wallet / Notifications) and a recent-activity feed; the settings screen adds an About
|
||||
section (version, docs, blog) and a privacy footer.
|
||||
|
||||
### Changed
|
||||
- **Record history renders in full.** The patient sheet's Record history replaces the fragile
|
||||
timeline-separator layout with a continuous-rail list, so every audited change shows completely
|
||||
(and mirrors correctly under RTL).
|
||||
- **Update banner + AI setup notice.** The "update available" banner now uses the COSS warning Alert
|
||||
and stays bottom-right under Arabic; the "connect an AI provider" notice is a clearer, thinner bar
|
||||
shown above the chat input in active conversations too.
|
||||
- **Wallet app — bottom sheets.** Polished the shared sheet building blocks (spacing, radii, close
|
||||
and action affordances).
|
||||
|
||||
### Fixed
|
||||
- **Blog reachable.** `blog.temetro.com` was returning 502 due to a custom-domain target-port
|
||||
mismatch (Ghost listens on 2368); documented and corrected.
|
||||
- **Docs freshness.** Corrected stale `CLAUDE.md` claims (the AI chat is real and `@ai-sdk/react` is
|
||||
installed; the signing/approval flow is built) and reduced the vendored `ai-elements` Base UI
|
||||
type-drift errors.
|
||||
|
||||
## [0.12.1] — 2026-07-10
|
||||
|
||||
### Changed
|
||||
- **Centered wallet-sync stepper.** The in-dialog "Sync to wallet" stepper (`DialogStepper` in
|
||||
`frontend/components/wallet/wallet-sync-step.tsx`) now uses a proper Stepper primitive
|
||||
(`components/ui/stepper.tsx`), so the numbered indicators sit centered inline with their labels
|
||||
instead of the previous left-aligned look.
|
||||
- **Record history is now a timeline.** The patient sheet's **Record history** section
|
||||
(`RecordHistory` in `frontend/components/patients/patient-detail.tsx`) renders as a vertical
|
||||
timeline (`components/ui/timeline.tsx`) — who made the change, an entity-type icon, what happened,
|
||||
and when — replacing the flat avatar list.
|
||||
|
||||
### Performance
|
||||
- **Landing page: defer the 3D globe.** The Temetro Network globe (three.js) on the marketing site
|
||||
now mounts only when its section scrolls near the viewport (IntersectionObserver), instead of on
|
||||
hydration — removing ~730 KB of JS and its main-thread execution from initial page load. (Landing
|
||||
page lives in the sibling `temetro/landing-page` repo.)
|
||||
|
||||
## [0.12.0] — 2026-07-09
|
||||
|
||||
### Added
|
||||
- **In-dialog "Sync to wallet" stepper.** When a clinician adds or edits a record for a
|
||||
wallet-linked patient — invoice, appointment, prescription, patient demographics, or an AI
|
||||
scribe note — the create/edit dialog shows a two-step stepper: after saving, step 2 offers to
|
||||
push the change to the patient's wallet (reusing `pushWalletUpdate` + approval polling). Shared
|
||||
`useWalletSync` hook and `DialogStepper` / `WalletSyncStep` components under `components/wallet/`.
|
||||
Patients without a linked wallet see the old close-on-save behaviour.
|
||||
|
||||
### Changed
|
||||
- **Appointment & invoice date pickers block past dates.** The new-appointment date picker disables
|
||||
days before today; the invoice issue-date picker does too, with an opt-in **Back-date** checkbox
|
||||
for recording genuinely older invoices (edit mode keeps existing past dates).
|
||||
- **Patient Portal wallet link is identified by wallet number only.** The portal `link` action no
|
||||
longer asks the wallet app for a name + file number — it resolves the file the clinic already
|
||||
paired the wallet number to (`services/portal.ts#linkWallet`), returning a friendly 404 when the
|
||||
wallet isn't paired yet.
|
||||
|
||||
### Removed
|
||||
- **Stale Settings "Features" section.** Dropped the inert "patient-owned storage" / "require signed
|
||||
records" toggles (and their unused i18n keys) that did nothing.
|
||||
|
||||
## [0.11.0] — 2026-07-09
|
||||
|
||||
### Added
|
||||
|
||||
@@ -31,9 +31,12 @@ repository (published as `temetro`).
|
||||
> is imported (with optional **temporary share + auto-delete**). Clinic→wallet **record-update push**
|
||||
> and **QR pairing** are built too. See `backend/src/routes/{signing,patients-wallet}.ts`.
|
||||
>
|
||||
> **Also built:** the **AI chat is real** — the frontend streams from the backend's tool-using
|
||||
> agent (`POST /api/chat`), not mock replies (see `frontend/CLAUDE.md`).
|
||||
>
|
||||
> **Still vision, not built:** in-app record editing and cryptographic time-boxing of temporary
|
||||
> shares. The AI chat is still **mock replies**. Email verification is wired but currently **not
|
||||
> enforced** at sign-in (see `backend/CLAUDE.md`).
|
||||
> shares. Email verification is wired but currently **not enforced** at sign-in (see
|
||||
> `backend/CLAUDE.md`).
|
||||
|
||||
## Patient wallet app (sibling repo `~/Desktop/temetro-app`)
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ information as rich record cards — backed by a **patient-owned data model**.
|
||||
|
||||
[](./LICENSE)
|
||||
[](https://hub.docker.com/u/khalidxv)
|
||||
[](./CHANGELOG.md)
|
||||
[](./CHANGELOG.md)
|
||||
|
||||

|
||||
|
||||
|
||||
@@ -6,5 +6,15 @@ dist
|
||||
*.log
|
||||
.DS_Store
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
docker-compose.yml
|
||||
docker-compose.tunnel.yml
|
||||
README.md
|
||||
CLAUDE.md
|
||||
# Deploy manifests for other targets — not needed inside the image.
|
||||
fly.toml
|
||||
railway.json
|
||||
render.yaml
|
||||
# Tracked, but only the runtime migrator (dist/migrate.js) runs in the image.
|
||||
drizzle.config.ts
|
||||
.env.example
|
||||
|
||||
+7
-1
@@ -19,7 +19,13 @@ RUN npm ci --omit=dev
|
||||
COPY --from=build /app/dist ./dist
|
||||
COPY --from=build /app/drizzle ./drizzle
|
||||
COPY docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
|
||||
RUN chmod +x /usr/local/bin/docker-entrypoint.sh
|
||||
# Strip CR before chmod. .gitattributes keeps this file LF on fresh clones, but
|
||||
# a Windows checkout made before that existed still has CRLF on disk, and a
|
||||
# "#!/bin/sh\r" shebang fails at container start with a "no such file or
|
||||
# directory" error that names the file it just copied in. Cheap to make the
|
||||
# image self-healing rather than rely on every contributor re-cloning.
|
||||
RUN sed -i 's/\r$//' /usr/local/bin/docker-entrypoint.sh \
|
||||
&& chmod +x /usr/local/bin/docker-entrypoint.sh
|
||||
EXPOSE 4000
|
||||
# The entrypoint auto-generates any missing secrets, then we apply migrations
|
||||
# and start the API.
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE "inventory" ADD COLUMN "barcode" text;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -253,6 +253,13 @@
|
||||
"when": 1783530491321,
|
||||
"tag": "0035_slippery_retro_girl",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 36,
|
||||
"version": "7",
|
||||
"when": 1784406410448,
|
||||
"tag": "0036_aspiring_expediter",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "temetro-backend",
|
||||
"version": "0.11.0",
|
||||
"version": "0.17.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "temetro backend — Express + Postgres API with Better Auth (email/password, organizations) and org-scoped patient records.",
|
||||
|
||||
@@ -29,6 +29,8 @@ export const inventory = pgTable(
|
||||
stockQuantity: integer("stock_quantity").notNull().default(0),
|
||||
reorderThreshold: integer("reorder_threshold").notNull().default(0),
|
||||
location: text("location").notNull().default(""),
|
||||
// Scanned medication barcode / NDC (GTIN when read from a GS1 DataMatrix).
|
||||
barcode: text("barcode"),
|
||||
expiresAt: date("expires_at"),
|
||||
notes: text("notes"),
|
||||
createdBy: text("created_by").references(() => user.id, {
|
||||
|
||||
@@ -5,7 +5,7 @@ import { z } from "zod";
|
||||
// is the plaintext key for the *currently selected* provider — it is encrypted
|
||||
// before storage and never echoed back.
|
||||
export const aiConfigInputSchema = z.object({
|
||||
mode: z.enum(["api", "local"]).optional(),
|
||||
mode: z.enum(["api", "local", "auto", "off"]).optional(),
|
||||
provider: z.enum(["openai", "anthropic", "gemini"]).optional(),
|
||||
ollamaBaseUrl: z.string().url().optional(),
|
||||
ollamaModel: z.string().min(1).max(120).optional(),
|
||||
|
||||
@@ -13,6 +13,7 @@ export const inventoryInputSchema = z.object({
|
||||
stockQuantity: z.number().int().min(0).max(1_000_000).default(0),
|
||||
reorderThreshold: z.number().int().min(0).max(1_000_000).default(0),
|
||||
location: z.string().trim().max(200).default(""),
|
||||
barcode: z.string().trim().max(120).nullish(),
|
||||
expiresAt: z
|
||||
.string()
|
||||
.regex(/^\d{4}-\d{2}-\d{2}$/, "Date must be YYYY-MM-DD.")
|
||||
|
||||
@@ -208,6 +208,12 @@ chatRouter.post("/", async (req, res, next) => {
|
||||
}
|
||||
|
||||
const settings = await getAiSettings(req.user!.id);
|
||||
if (settings.mode === "off") {
|
||||
throw new HttpError(
|
||||
400,
|
||||
"The AI assistant is turned off. Turn it on in Settings → AI.",
|
||||
);
|
||||
}
|
||||
const modelId = requestedModel || settings.defaultModel;
|
||||
const resolved = resolveModel(settings, modelId);
|
||||
const veil = createVeil(settings.veilLevel, resolved.isExternal);
|
||||
|
||||
@@ -13,7 +13,9 @@ import {
|
||||
type AiSettingsRow = typeof userAiSettings.$inferSelect;
|
||||
|
||||
const DEFAULTS: Omit<AiSettingsRow, "userId" | "updatedAt"> = {
|
||||
mode: "local",
|
||||
// Default to auto: use a cloud key if the user adds one, else local Ollama.
|
||||
// A fresh user with nothing configured then sees the setup banner.
|
||||
mode: "auto",
|
||||
provider: "anthropic",
|
||||
ollamaBaseUrl: DEFAULT_OLLAMA_BASE_URL,
|
||||
ollamaModel: "llama3.1",
|
||||
|
||||
@@ -69,8 +69,30 @@ export function resolveModel(
|
||||
settings: AiSettingsRow,
|
||||
requestedModelId: string,
|
||||
): ResolvedModel {
|
||||
// Local mode (or the local sentinel) → Ollama's OpenAI-compatible endpoint.
|
||||
if (settings.mode === "local" || requestedModelId === OLLAMA_SENTINEL) {
|
||||
// Off → the assistant is disabled. Guard here in case a request slips past the
|
||||
// route-level short-circuit.
|
||||
if (settings.mode === "off") {
|
||||
throw new HttpError(
|
||||
400,
|
||||
"The AI assistant is turned off. Turn it on in Settings → AI.",
|
||||
);
|
||||
}
|
||||
|
||||
const requested = providerForModel(requestedModelId);
|
||||
// In api/auto mode, find a cloud provider that actually has a key. Auto with
|
||||
// no key (and api mode's remaining fall-through) drops to local Ollama below.
|
||||
const provider =
|
||||
settings.mode === "api" || settings.mode === "auto"
|
||||
? chooseProvider(settings, requested)
|
||||
: null;
|
||||
|
||||
// Local when: explicit local mode, the local sentinel was picked, or auto with
|
||||
// no configured cloud key. → Ollama's OpenAI-compatible endpoint.
|
||||
if (
|
||||
settings.mode === "local" ||
|
||||
requestedModelId === OLLAMA_SENTINEL ||
|
||||
(settings.mode === "auto" && !provider)
|
||||
) {
|
||||
const ollama = createOpenAICompatible({
|
||||
name: "ollama",
|
||||
baseURL: `${settings.ollamaBaseUrl.replace(/\/$/, "")}/v1`,
|
||||
@@ -82,11 +104,7 @@ export function resolveModel(
|
||||
};
|
||||
}
|
||||
|
||||
// API mode. Pick a provider that actually has a key, falling back gracefully
|
||||
// so a configured key (e.g. Gemini) is used even if the picked model belongs
|
||||
// to a different, unconfigured provider.
|
||||
const requested = providerForModel(requestedModelId);
|
||||
const provider = chooseProvider(settings, requested);
|
||||
// API mode with a picked cloud model but no matching/any key.
|
||||
if (!provider) {
|
||||
throw new HttpError(
|
||||
400,
|
||||
|
||||
@@ -21,6 +21,7 @@ function toInventoryItem(row: InventoryRow): InventoryItem {
|
||||
stockQuantity: row.stockQuantity,
|
||||
reorderThreshold: row.reorderThreshold,
|
||||
location: row.location,
|
||||
barcode: row.barcode,
|
||||
expiresAt: row.expiresAt,
|
||||
notes: row.notes,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
@@ -38,6 +39,7 @@ function columns(orgId: string, input: InventoryInput, createdBy?: string) {
|
||||
stockQuantity: input.stockQuantity,
|
||||
reorderThreshold: input.reorderThreshold,
|
||||
location: input.location,
|
||||
barcode: input.barcode ?? null,
|
||||
expiresAt: input.expiresAt ?? null,
|
||||
notes: input.notes ?? null,
|
||||
...(createdBy ? { createdBy } : {}),
|
||||
|
||||
@@ -30,7 +30,6 @@ import { getPatient } from "./patients.js";
|
||||
|
||||
// Clinical-capable roles that can be a patient's provider (mirrors portal.ts).
|
||||
const PROVIDER_ROLES = ["owner", "admin", "doctor", "member"] as const;
|
||||
const norm = (s: string) => s.trim().toLowerCase();
|
||||
|
||||
export type PortalDoctor = { name: string; specialty: string | null };
|
||||
|
||||
@@ -87,35 +86,31 @@ export async function getAvailability(
|
||||
|
||||
// --- wallet linkage ---------------------------------------------------------
|
||||
|
||||
// Save a wallet number onto a patient file after verifying the patient's
|
||||
// identity (name + file number, like the kiosk). Once linked, clinic→wallet
|
||||
// pushes and portal actions resolve to this file directly.
|
||||
// Confirm the wallet link for a device. The wallet is identified purely by its
|
||||
// relay-verified wallet number — the clinic attaches that number to the patient
|
||||
// file ahead of time (via "Import from a patient app" / QR pairing, which sets
|
||||
// `patients.walletNumber`), so the device never types a name or file number.
|
||||
// Resolves the linked file, or a friendly 404 when the clinic hasn't paired yet.
|
||||
export async function linkWallet(
|
||||
orgId: string,
|
||||
walletNumber: string,
|
||||
fileNumber: string,
|
||||
name: string,
|
||||
): Promise<{ fileNumber: string; name: string }> {
|
||||
const patient = await getPatient(orgId, fileNumber);
|
||||
if (!patient || norm(patient.name) !== norm(name)) {
|
||||
if (!walletNumber) {
|
||||
throw new HttpError(400, "Missing wallet identity.");
|
||||
}
|
||||
const fileNumber = await fileNumberForWallet(orgId, walletNumber);
|
||||
if (!fileNumber) {
|
||||
throw new HttpError(
|
||||
404,
|
||||
"We couldn't find a record matching that name and file number.",
|
||||
"This wallet isn't paired with a record at this clinic yet. Ask the front desk to add your wallet number, then try again.",
|
||||
);
|
||||
}
|
||||
await db
|
||||
.update(patients)
|
||||
.set({ walletNumber })
|
||||
.where(
|
||||
and(
|
||||
eq(patients.organizationId, orgId),
|
||||
eq(patients.fileNumber, patient.fileNumber),
|
||||
),
|
||||
);
|
||||
const patient = await getPatient(orgId, fileNumber);
|
||||
if (!patient) throw new HttpError(404, "Linked record not found.");
|
||||
await recordActivity({
|
||||
orgId,
|
||||
actor: { id: "", name: patient.name },
|
||||
action: `Patient portal — ${patient.name} linked a wallet`,
|
||||
action: `Patient portal — ${patient.name} confirmed their wallet link`,
|
||||
entityType: "patient",
|
||||
entityId: patient.fileNumber,
|
||||
});
|
||||
@@ -277,7 +272,7 @@ export async function handlePortalRequest(
|
||||
case "availability":
|
||||
return getAvailability(orgId, s("provider"), s("date"));
|
||||
case "link":
|
||||
return linkWallet(orgId, walletNumber, s("fileNumber"), s("name"));
|
||||
return linkWallet(orgId, walletNumber);
|
||||
case "book":
|
||||
return bookForWallet(orgId, walletNumber, {
|
||||
date: s("date"),
|
||||
|
||||
@@ -40,7 +40,17 @@ export function sendToWallet(
|
||||
event: string,
|
||||
data: unknown,
|
||||
): void {
|
||||
hubs.get(orgId)?.emit("wallet:send", { walletNumber, event, data });
|
||||
const hub = hubs.get(orgId);
|
||||
if (!hub) {
|
||||
// No live hub means the push is dropped on the floor. The row still sits
|
||||
// pending and `wallet:online` replays it once a device reconnects, but say
|
||||
// so — a silent no-op here looks exactly like a wallet that ignored us.
|
||||
console.warn(
|
||||
`Temetro Network: no hub connection for clinic ${orgId}; "${event}" not sent (queued for wallet:online replay).`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
hub.emit("wallet:send", { walletNumber, event, data });
|
||||
}
|
||||
|
||||
// Tell the relay to expect a device response for `requestId` and route it back
|
||||
|
||||
@@ -15,8 +15,10 @@ import {
|
||||
} from "../lib/wallet-crypto.js";
|
||||
import { ed25519PubToX25519Hex } from "../lib/wallet-x25519.js";
|
||||
import { listAppointments } from "./appointments.js";
|
||||
import { listAttachments } from "./attachments.js";
|
||||
import { listInvoices } from "./invoices.js";
|
||||
import { getPatient } from "./patients.js";
|
||||
import { listPrescriptions } from "./prescriptions.js";
|
||||
import { signWithClinicKey } from "./signing.js";
|
||||
|
||||
type UpdateRow = typeof walletRecordUpdates.$inferSelect;
|
||||
@@ -24,8 +26,15 @@ type UpdateRow = typeof walletRecordUpdates.$inferSelect;
|
||||
// The payload the relay pushes to a wallet. `sealed` is the encrypted patient
|
||||
// snapshot; `signature`/`clinicPublicKey`/`fingerprint` let the wallet verify
|
||||
// provenance (TOFU pin) before applying.
|
||||
//
|
||||
// `clinicId` is the stable org id. The wallet pins a clinic's signing key
|
||||
// against it — pinning against the mutable `clinicName` meant every unnamed org
|
||||
// collided on the "A clinic" fallback and tripped a bogus "key changed" warning.
|
||||
// It also doubles as the relay routing id the wallet needs to fetch document
|
||||
// bytes over the portal.
|
||||
export type WalletUpdateEvent = {
|
||||
requestId: string;
|
||||
clinicId: string;
|
||||
clinicName: string;
|
||||
sealed: string;
|
||||
signature: string;
|
||||
@@ -119,22 +128,49 @@ export async function createRecordUpdate(
|
||||
const patient = await getPatient(orgId, fileNumber);
|
||||
if (!patient) throw new HttpError(404, "Patient not found.");
|
||||
|
||||
// Appointments and invoices live in their own tables (not on the Patient
|
||||
// snapshot), so pull the ones for this patient and ship them alongside — the
|
||||
// wallet has no other way to see them and they'd otherwise silently vanish.
|
||||
const [orgAppointments, orgInvoices] = await Promise.all([
|
||||
listAppointments(orgId),
|
||||
listInvoices(orgId),
|
||||
]);
|
||||
// Appointments, invoices and prescriptions live in their own tables (not on
|
||||
// the Patient snapshot), so pull the ones for this patient and ship them
|
||||
// alongside — the wallet has no other way to see them and they'd otherwise
|
||||
// silently vanish. `patient.medications` comes from `patient_medications`,
|
||||
// which `createPrescription` never writes to, so a prescription that isn't
|
||||
// shipped here would leave the approved bundle identical to what the wallet
|
||||
// already had.
|
||||
// Attachments (files/documents) are shipped as metadata; the bytes stay on the
|
||||
// clinic and the wallet fetches them on demand over the portal `result-file`
|
||||
// action, keyed by the same attachment id shipped here.
|
||||
const [orgAppointments, orgInvoices, orgPrescriptions, attachmentRows] =
|
||||
await Promise.all([
|
||||
listAppointments(orgId),
|
||||
listInvoices(orgId),
|
||||
listPrescriptions(orgId),
|
||||
listAttachments(orgId, fileNumber),
|
||||
]);
|
||||
const appointments = orgAppointments.filter(
|
||||
(a) => a.fileNumber === fileNumber,
|
||||
);
|
||||
const invoices = orgInvoices.filter((i) => i.fileNumber === fileNumber);
|
||||
const prescriptions = orgPrescriptions.filter(
|
||||
(p) => p.fileNumber === fileNumber,
|
||||
);
|
||||
const documents = attachmentRows.map((a) => ({
|
||||
id: a.id,
|
||||
filename: a.filename,
|
||||
mimeType: a.mimeType,
|
||||
sizeBytes: a.sizeBytes,
|
||||
createdAt: a.createdAt,
|
||||
}));
|
||||
|
||||
// The wallet opens this, verifies the signature over the same bytes, then
|
||||
// replaces its on-device record with `patient` (+ appointments/invoices).
|
||||
// replaces its on-device record with `patient` (+ the sibling-table lists).
|
||||
const bundle = utf8ToBytes(
|
||||
JSON.stringify({ patient, appointments, invoices, changes }),
|
||||
JSON.stringify({
|
||||
patient,
|
||||
appointments,
|
||||
invoices,
|
||||
prescriptions,
|
||||
documents,
|
||||
changes,
|
||||
}),
|
||||
);
|
||||
const { signature, publicKey } = await signWithClinicKey(orgId, bundle);
|
||||
const x25519Hex = ed25519PubToX25519Hex(decodeWalletNumber(walletNumber));
|
||||
@@ -165,6 +201,7 @@ export async function toEvent(row: UpdateRow): Promise<WalletUpdateEvent> {
|
||||
.where(eq(organization.id, row.organizationId));
|
||||
return {
|
||||
requestId: row.id,
|
||||
clinicId: row.organizationId,
|
||||
clinicName: org?.name ?? "A clinic",
|
||||
sealed: row.payloadSealed,
|
||||
signature: row.clinicSignature,
|
||||
@@ -223,9 +260,24 @@ export async function applyUpdateResponse(
|
||||
.select()
|
||||
.from(walletRecordUpdates)
|
||||
.where(eq(walletRecordUpdates.id, requestId));
|
||||
if (!row || row.resolvedAt) return null;
|
||||
if (row.walletNumber !== walletNumber.trim()) return null;
|
||||
if (!signatureHex) return null;
|
||||
// These all mean the patient tapped Approve and nothing happened, so say so —
|
||||
// silently returning null here is indistinguishable from a lost connection.
|
||||
if (!row) {
|
||||
console.warn(`Wallet update ${requestId}: no such update row.`);
|
||||
return null;
|
||||
}
|
||||
if (row.resolvedAt) {
|
||||
console.warn(`Wallet update ${requestId}: already resolved.`);
|
||||
return null;
|
||||
}
|
||||
if (row.walletNumber !== walletNumber.trim()) {
|
||||
console.warn(`Wallet update ${requestId}: wallet number did not match.`);
|
||||
return null;
|
||||
}
|
||||
if (!signatureHex) {
|
||||
console.warn(`Wallet update ${requestId}: response carried no signature.`);
|
||||
return null;
|
||||
}
|
||||
|
||||
const publicKey = decodeWalletNumber(walletNumber);
|
||||
const message = utf8ToBytes(`${decision}:${requestId}`);
|
||||
|
||||
@@ -2,8 +2,12 @@
|
||||
// AI panel. The chat agent reads these to decide which provider/model to call
|
||||
// and how strict the Veil de-identification safeguard should be.
|
||||
|
||||
// Two inference modes: a user-provided cloud API key, or a local Ollama model.
|
||||
export type AiMode = "api" | "local";
|
||||
// Inference modes:
|
||||
// api — a user-provided cloud API key
|
||||
// local — a local Ollama model
|
||||
// auto — auto-pick: use a cloud key when one is set, else fall back to local
|
||||
// off — the assistant is disabled
|
||||
export type AiMode = "api" | "local" | "auto" | "off";
|
||||
|
||||
// The three supported cloud providers for API-key mode.
|
||||
export type ApiProvider = "openai" | "anthropic" | "gemini";
|
||||
|
||||
@@ -11,6 +11,7 @@ export type InventoryItem = {
|
||||
stockQuantity: number;
|
||||
reorderThreshold: number;
|
||||
location: string;
|
||||
barcode: string | null;
|
||||
expiresAt: string | null; // YYYY-MM-DD
|
||||
notes: string | null;
|
||||
createdAt: string;
|
||||
|
||||
@@ -7,3 +7,6 @@ npm-debug.log*
|
||||
.DS_Store
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
tsconfig.tsbuildinfo
|
||||
CLAUDE.md
|
||||
AGENTS.md
|
||||
|
||||
+8
-6
@@ -12,8 +12,9 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
||||
|
||||
`temetro` — an **open-source** clinical "AI middleman" (see the project vision in the root
|
||||
`../CLAUDE.md`). This app is the clinician-facing chat UI. It is now **wired to the real
|
||||
`../backend/`** for authentication and patient data (no longer a standalone UI-only demo); the AI
|
||||
chat replies are **still mocked** (no LLM call yet).
|
||||
`../backend/`** for authentication and patient data (no longer a standalone UI-only demo). The AI
|
||||
chat is **real**: `components/chat/chat-panel.tsx` streams from the backend's tool-using agent
|
||||
(`POST /api/chat`) via `useChat` and renders the record data parts it streams back.
|
||||
|
||||
- The chat parses `/patient <file#>` (or a bare `/<file#>`) in `components/chat/chat-panel.tsx` and
|
||||
renders the record as a horizontal row of cards (`components/chat/patient-cards.tsx`), with small
|
||||
@@ -21,7 +22,7 @@ chat replies are **still mocked** (no LLM call yet).
|
||||
dialog; the Summary card has an **Edit record** button.
|
||||
- Patients can be **created and edited** via the shared `components/chat/patient-form-dialog.tsx`
|
||||
(mode `create` | `edit`). The "Add patient" pill in `chat-input.tsx` opens it.
|
||||
- Non-command messages still get a mock assistant reply.
|
||||
- Non-command messages stream a real reply from the backend agent (`POST /api/chat`).
|
||||
|
||||
### Auth & data (talks to `../backend`)
|
||||
|
||||
@@ -42,7 +43,8 @@ chat replies are **still mocked** (no LLM call yet).
|
||||
`components/settings/settings-care-team.tsx` manages members + invitations.
|
||||
- `.env.local` / `.env.example` hold `NEXT_PUBLIC_API_URL`.
|
||||
|
||||
The signing / patient-owned-storage / approval features from the root vision are **still not built**.
|
||||
The signing / patient-owned-storage / approval features from the root vision **are built** (clinic
|
||||
signing key, encrypted share/import, patient approval, clinic→wallet update push, QR pairing).
|
||||
|
||||
## Commands
|
||||
|
||||
@@ -77,8 +79,8 @@ trailer. See the root `../CLAUDE.md` for the project-wide per-folder commit poli
|
||||
`components.json` (baseColor `neutral`).
|
||||
- **`components/ai-elements/`** — a large AI-chat primitive library (`PromptInput`, `Conversation`,
|
||||
`Message`, `Suggestion`, etc.) typed against **AI SDK v6** (`ai` package: `UIMessage`,
|
||||
`ChatStatus`, `FileUIPart`). Note: `@ai-sdk/react` (`useChat`) is **not installed** — chat state
|
||||
is managed with local React state.
|
||||
`ChatStatus`, `FileUIPart`). `@ai-sdk/react` (`useChat`) **is installed** and drives the live chat
|
||||
(`chat-panel.tsx`) with a custom transport pointed at `POST /api/chat`.
|
||||
- **`components/sidebar-02/`** — the dashboard sidebar (`SidebarProvider` / `Sidebar` /
|
||||
`SidebarInset` from `components/ui/sidebar.tsx`). `app-sidebar.tsx` holds the nav config (New chat
|
||||
· Patients · Settings) + notifications; `team-switcher.tsx` is the `OrgSwitcher` (clinic switch).
|
||||
|
||||
@@ -212,7 +212,7 @@ export function ActivityView() {
|
||||
|
||||
<button
|
||||
className={cn(
|
||||
"-mx-2 flex-1 rounded-lg px-2 py-1 text-start transition-colors hover:bg-accent/40",
|
||||
"-mx-2 flex-1 cursor-pointer rounded-lg px-2 py-1 text-start transition-colors hover:bg-accent/40",
|
||||
isLast ? "pb-1" : "mb-5",
|
||||
)}
|
||||
onClick={() => setSelected(entry)}
|
||||
|
||||
@@ -369,15 +369,18 @@ export const AttachmentRemove = ({
|
||||
// AttachmentHoverCard - Hover preview
|
||||
// ============================================================================
|
||||
|
||||
export type AttachmentHoverCardProps = ComponentProps<typeof HoverCard>;
|
||||
export type AttachmentHoverCardProps = ComponentProps<typeof HoverCard> & {
|
||||
// Base UI moved hover delay to the Trigger (`delay`); kept here for API
|
||||
// back-compat but no longer forwarded to the Root.
|
||||
openDelay?: number;
|
||||
closeDelay?: number;
|
||||
};
|
||||
|
||||
export const AttachmentHoverCard = ({
|
||||
openDelay = 0,
|
||||
closeDelay = 0,
|
||||
openDelay,
|
||||
closeDelay,
|
||||
...props
|
||||
}: AttachmentHoverCardProps) => (
|
||||
<HoverCard closeDelay={closeDelay} openDelay={openDelay} {...props} />
|
||||
);
|
||||
}: AttachmentHoverCardProps) => <HoverCard {...props} />;
|
||||
|
||||
export type AttachmentHoverCardTriggerProps = ComponentProps<
|
||||
typeof HoverCardTrigger
|
||||
|
||||
@@ -56,7 +56,7 @@ export const Context = ({
|
||||
|
||||
return (
|
||||
<ContextContext.Provider value={contextValue}>
|
||||
<HoverCard closeDelay={0} openDelay={0} {...props} />
|
||||
<HoverCard {...props} />
|
||||
</ContextContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -50,7 +50,7 @@ export const InlineCitationText = ({
|
||||
export type InlineCitationCardProps = ComponentProps<typeof HoverCard>;
|
||||
|
||||
export const InlineCitationCard = (props: InlineCitationCardProps) => (
|
||||
<HoverCard closeDelay={0} openDelay={0} {...props} />
|
||||
<HoverCard {...props} />
|
||||
);
|
||||
|
||||
export type InlineCitationCardTriggerProps = ComponentProps<typeof Badge> & {
|
||||
|
||||
@@ -128,5 +128,18 @@ export const PlanFooter = (props: PlanFooterProps) => (
|
||||
export type PlanTriggerProps = ComponentProps<typeof CollapsibleTrigger>;
|
||||
|
||||
export const PlanTrigger = ({ className, ...props }: PlanTriggerProps) => (
|
||||
<CollapsibleTrigger render={<Button className={cn("size-8", className)} data-slot="plan-trigger" size="icon" variant="ghost" {...props} />}><ChevronsUpDownIcon className="size-4" /><span className="sr-only">Toggle plan</span></CollapsibleTrigger>
|
||||
<CollapsibleTrigger
|
||||
{...props}
|
||||
render={
|
||||
<Button
|
||||
className={cn("size-8", className)}
|
||||
data-slot="plan-trigger"
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<ChevronsUpDownIcon className="size-4" />
|
||||
<span className="sr-only">Toggle plan</span>
|
||||
</CollapsibleTrigger>
|
||||
);
|
||||
|
||||
@@ -1311,15 +1311,18 @@ export const PromptInputSelectValue = ({
|
||||
<SelectValue className={cn(className)} {...props} />
|
||||
);
|
||||
|
||||
export type PromptInputHoverCardProps = ComponentProps<typeof HoverCard>;
|
||||
export type PromptInputHoverCardProps = ComponentProps<typeof HoverCard> & {
|
||||
// Base UI moved hover delay to the Trigger (`delay`); kept here for API
|
||||
// back-compat but no longer forwarded to the Root.
|
||||
openDelay?: number;
|
||||
closeDelay?: number;
|
||||
};
|
||||
|
||||
export const PromptInputHoverCard = ({
|
||||
openDelay = 0,
|
||||
closeDelay = 0,
|
||||
openDelay,
|
||||
closeDelay,
|
||||
...props
|
||||
}: PromptInputHoverCardProps) => (
|
||||
<HoverCard closeDelay={closeDelay} openDelay={openDelay} {...props} />
|
||||
);
|
||||
}: PromptInputHoverCardProps) => <HoverCard {...props} />;
|
||||
|
||||
export type PromptInputHoverCardTriggerProps = ComponentProps<
|
||||
typeof HoverCardTrigger
|
||||
|
||||
@@ -107,7 +107,9 @@ export const SchemaDisplayPath = ({
|
||||
<span
|
||||
className={cn("font-mono text-sm", className)}
|
||||
// oxlint-disable-next-line eslint-plugin-react(no-danger)
|
||||
dangerouslySetInnerHTML={{ __html: children ?? highlightedPath }}
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: typeof children === "string" ? children : highlightedPath,
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -23,6 +23,11 @@ import { Popover, PopoverPopup, PopoverTrigger } from "@/components/ui/popover";
|
||||
import { listPatients, type Patient } from "@/lib/patients";
|
||||
import { listProviders, type Provider } from "@/lib/staff";
|
||||
import { notify } from "@/lib/toast";
|
||||
import { useWalletSync } from "@/components/wallet/use-wallet-sync";
|
||||
import {
|
||||
DialogStepper,
|
||||
WalletSyncStep,
|
||||
} from "@/components/wallet/wallet-sync-step";
|
||||
|
||||
export type NewAppointment = {
|
||||
fileNumber: string;
|
||||
@@ -51,6 +56,14 @@ const TYPES = [
|
||||
const controlClass =
|
||||
"h-9 w-full rounded-3xl border border-transparent bg-input/50 px-3 text-sm text-foreground outline-none transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/30";
|
||||
|
||||
// Local start-of-day so the calendar can disable days strictly before today
|
||||
// (appointments can't be scheduled in the past).
|
||||
const startOfToday = () => {
|
||||
const d = new Date();
|
||||
d.setHours(0, 0, 0, 0);
|
||||
return d;
|
||||
};
|
||||
|
||||
function Field({ label, children }: { label: string; children: ReactNode }) {
|
||||
return (
|
||||
<label className="flex flex-col gap-1.5">
|
||||
@@ -70,7 +83,7 @@ export function AddAppointmentDialog({
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onAdd: (appt: NewAppointment) => void;
|
||||
onAdd: (appt: NewAppointment) => void | Promise<void>;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [patients, setPatients] = useState<Patient[]>([]);
|
||||
@@ -82,6 +95,10 @@ export function AddAppointmentDialog({
|
||||
const [type, setType] = useState(TYPES[0]);
|
||||
const [provider, setProvider] = useState("");
|
||||
const [providerQuery, setProviderQuery] = useState("");
|
||||
const [step, setStep] = useState<"form" | "wallet">("form");
|
||||
const [walletSummary, setWalletSummary] = useState("");
|
||||
|
||||
const sync = useWalletSync(selected?.fileNumber ?? null);
|
||||
|
||||
// Load patients + providers lazily when the dialog opens (for the searches).
|
||||
useEffect(() => {
|
||||
@@ -147,7 +164,16 @@ export function AddAppointmentDialog({
|
||||
setProviderQuery("");
|
||||
};
|
||||
|
||||
const submit = (event: FormEvent) => {
|
||||
const handleOpenChange = (o: boolean) => {
|
||||
onOpenChange(o);
|
||||
if (!o) {
|
||||
reset();
|
||||
setStep("form");
|
||||
sync.reset();
|
||||
}
|
||||
};
|
||||
|
||||
const submit = async (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (!selected) {
|
||||
notify.error(
|
||||
@@ -156,7 +182,7 @@ export function AddAppointmentDialog({
|
||||
);
|
||||
return;
|
||||
}
|
||||
onAdd({
|
||||
await onAdd({
|
||||
fileNumber: selected.fileNumber,
|
||||
name: selected.name,
|
||||
initials: selected.initials,
|
||||
@@ -169,26 +195,36 @@ export function AddAppointmentDialog({
|
||||
t("appointments.dialog.addedTitle"),
|
||||
`${selected.name} · ${time}`,
|
||||
);
|
||||
reset();
|
||||
onOpenChange(false);
|
||||
if (await sync.ensureLinked()) {
|
||||
setWalletSummary(
|
||||
t("walletSync.summary.appointment", { date: keyOf(date), time }),
|
||||
);
|
||||
setStep("wallet");
|
||||
} else {
|
||||
reset();
|
||||
onOpenChange(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
onOpenChange={(o) => {
|
||||
onOpenChange(o);
|
||||
if (!o) reset();
|
||||
}}
|
||||
open={open}
|
||||
>
|
||||
<DialogPopup className="sm:max-w-md">
|
||||
<Dialog onOpenChange={handleOpenChange} open={open}>
|
||||
<DialogPopup className="flex max-h-[85dvh] flex-col sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t("appointments.dialog.title")}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{t("appointments.dialog.description")}
|
||||
</DialogDescription>
|
||||
{sync.linked && <DialogStepper step={step} />}
|
||||
</DialogHeader>
|
||||
|
||||
{step === "wallet" ? (
|
||||
<WalletSyncStep
|
||||
onDone={() => handleOpenChange(false)}
|
||||
patientName={selected?.name ?? ""}
|
||||
summary={walletSummary}
|
||||
sync={sync}
|
||||
/>
|
||||
) : (
|
||||
<form className="contents" onSubmit={submit}>
|
||||
<DialogPanel className="flex flex-col gap-4">
|
||||
<Field label={t("appointments.dialog.patient")}>
|
||||
@@ -251,6 +287,7 @@ export function AddAppointmentDialog({
|
||||
/>
|
||||
<PopoverPopup>
|
||||
<Calendar
|
||||
disabled={{ before: startOfToday() }}
|
||||
mode="single"
|
||||
onSelect={(d) => {
|
||||
if (d) {
|
||||
@@ -311,6 +348,7 @@ export function AddAppointmentDialog({
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
)}
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
);
|
||||
|
||||
@@ -87,15 +87,18 @@ export function AppointmentDetailSheet({
|
||||
const [status, setStatus] = useState<AppointmentStatus>("confirmed");
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
// Seed the form from the selected appointment whenever it changes.
|
||||
useEffect(() => {
|
||||
if (!appt) return;
|
||||
// Seed the form from the selected appointment whenever it changes. Adjusted
|
||||
// during render rather than in an effect, so the sheet never paints one frame
|
||||
// of the previous appointment's values.
|
||||
const [prevAppt, setPrevAppt] = useState(appt);
|
||||
if (appt && prevAppt !== appt) {
|
||||
setPrevAppt(appt);
|
||||
setDate(new Date(`${appt.date}T00:00:00`));
|
||||
setTime(appt.time);
|
||||
setType(appt.type);
|
||||
setProvider(appt.provider);
|
||||
setStatus(appt.status);
|
||||
}, [appt]);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { ChevronLeft, ChevronRight } from "lucide-react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import {
|
||||
@@ -72,13 +72,22 @@ export function CalendarDialog({
|
||||
});
|
||||
const [selectedKey, setSelectedKey] = useState<string>(startKey);
|
||||
|
||||
// When opened via a deep-link date, jump the view to that month/day.
|
||||
useEffect(() => {
|
||||
if (!open || !initialDate || !/^\d{4}-\d{2}-\d{2}$/.test(initialDate)) return;
|
||||
const d = parseKey(initialDate);
|
||||
setViewMonth(new Date(d.getFullYear(), d.getMonth(), 1));
|
||||
setSelectedKey(initialDate);
|
||||
}, [open, initialDate]);
|
||||
// When opened via a deep-link date, jump the view to that month/day. Adjusted
|
||||
// during render rather than in an effect, so the calendar never paints the
|
||||
// current month before jumping to the linked one.
|
||||
const jumpTo =
|
||||
open && initialDate && /^\d{4}-\d{2}-\d{2}$/.test(initialDate)
|
||||
? initialDate
|
||||
: null;
|
||||
const [prevJumpTo, setPrevJumpTo] = useState<string | null>(null);
|
||||
if (prevJumpTo !== jumpTo) {
|
||||
setPrevJumpTo(jumpTo);
|
||||
if (jumpTo) {
|
||||
const d = parseKey(jumpTo);
|
||||
setViewMonth(new Date(d.getFullYear(), d.getMonth(), 1));
|
||||
setSelectedKey(jumpTo);
|
||||
}
|
||||
}
|
||||
|
||||
const byDate = useMemo(() => {
|
||||
const map = new Map<string, Appointment[]>();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { Sparkles, X } from "lucide-react";
|
||||
import { TriangleAlert, X } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -8,12 +8,19 @@ import { useTranslation } from "react-i18next";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { getAiConfig } from "@/lib/ai-settings";
|
||||
|
||||
// A single, dismissible heads-up shown above the chat input on a fresh chat when
|
||||
// no AI provider is configured yet (no API key, and no local Ollama). It only
|
||||
// renders on the empty state, so it naturally disappears once a message is sent.
|
||||
// A thin, dismissible warning bar shown flush above the chat input whenever no
|
||||
// AI provider is wired up yet — either no API key for any cloud provider, or the
|
||||
// app is in local mode with no Ollama endpoint set. Without this, sending a
|
||||
// message just fails silently, so the banner spells out the missing setup and
|
||||
// links straight to AI settings. Rendered in both the empty and active chat
|
||||
// states so a user mid-conversation with no provider still sees why replies fail.
|
||||
// Which advisory (if any) to show: the setup nudge (no provider wired), or a
|
||||
// notice that the assistant has been switched off.
|
||||
type Notice = "setup" | "off" | null;
|
||||
|
||||
export function AiSetupNotice() {
|
||||
const { t } = useTranslation();
|
||||
const [needsSetup, setNeedsSetup] = useState(false);
|
||||
const [notice, setNotice] = useState<Notice>(null);
|
||||
const [dismissed, setDismissed] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -21,43 +28,60 @@ export function AiSetupNotice() {
|
||||
getAiConfig()
|
||||
.then((cfg) => {
|
||||
if (!active) return;
|
||||
// Configured = an API key for any provider, or a local Ollama endpoint.
|
||||
if (cfg.mode === "off") {
|
||||
setNotice("off");
|
||||
return;
|
||||
}
|
||||
const hasApiKey = Object.values(cfg.apiKeySet).some(Boolean);
|
||||
const hasLocal =
|
||||
cfg.mode === "local" && cfg.ollamaBaseUrl.trim().length > 0;
|
||||
setNeedsSetup(!(hasApiKey || hasLocal));
|
||||
// Whether the assistant is actually wired up for the chosen mode:
|
||||
// - api / auto → needs a cloud API key (auto silently falls back to
|
||||
// local, but with no key we nudge the user to finish
|
||||
// setup rather than depend on an unverified Ollama).
|
||||
// - local → needs a non-empty Ollama endpoint (opted in).
|
||||
const configured =
|
||||
cfg.mode === "local"
|
||||
? cfg.ollamaBaseUrl.trim().length > 0
|
||||
: hasApiKey;
|
||||
setNotice(configured ? null : "setup");
|
||||
})
|
||||
.catch(() => {
|
||||
// If we can't read the config, don't nag — the chat still works.
|
||||
if (active) setNeedsSetup(false);
|
||||
if (active) setNotice(null);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
if (!needsSetup || dismissed) return null;
|
||||
if (!notice || dismissed) return null;
|
||||
|
||||
const isOff = notice === "off";
|
||||
|
||||
return (
|
||||
<div
|
||||
className="flex w-full items-start gap-3 rounded-2xl border border-info/30 bg-info/8 px-4 py-3 text-sm dark:bg-info/12"
|
||||
className="flex w-full items-center gap-2.5 rounded-2xl border border-warning/32 bg-warning/8 px-3.5 py-2 text-sm dark:bg-warning/12"
|
||||
role="status"
|
||||
>
|
||||
<Sparkles className="mt-0.5 size-4 shrink-0 text-info-foreground" />
|
||||
<div className="flex-1 space-y-0.5">
|
||||
<p className="font-medium text-foreground">
|
||||
{t("chat.setupNotice.title")}
|
||||
</p>
|
||||
<p className="text-muted-foreground">{t("chat.setupNotice.body")}</p>
|
||||
<Button
|
||||
className="mt-1 px-0 text-info-foreground"
|
||||
render={<Link href="/settings?tab=ai" />}
|
||||
size="sm"
|
||||
variant="link"
|
||||
>
|
||||
{t("chat.setupNotice.action")}
|
||||
</Button>
|
||||
</div>
|
||||
<TriangleAlert className="size-4 shrink-0 text-warning" />
|
||||
<p className="min-w-0 flex-1 truncate text-foreground">
|
||||
<span className="font-medium">
|
||||
{isOff
|
||||
? t("chat.setupNotice.offTitle")
|
||||
: t("chat.setupNotice.title")}
|
||||
</span>
|
||||
<span className="text-muted-foreground max-sm:hidden">
|
||||
{" — "}
|
||||
{isOff ? t("chat.setupNotice.offBody") : t("chat.setupNotice.body")}
|
||||
</span>
|
||||
</p>
|
||||
<Button
|
||||
className="shrink-0"
|
||||
render={<Link href="/settings?tab=ai" />}
|
||||
size="sm"
|
||||
variant="outline"
|
||||
>
|
||||
{t("chat.setupNotice.action")}
|
||||
</Button>
|
||||
<button
|
||||
aria-label={t("chat.setupNotice.dismiss")}
|
||||
className="-me-1 shrink-0 rounded-md p-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
useSyncExternalStore,
|
||||
} from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
@@ -78,17 +79,23 @@ export function ChatInput({
|
||||
const [addKey, setAddKey] = useState(0);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
// Voice dictation (Web Speech API). Detected client-side so SSR markup and the
|
||||
// first client render agree (button starts disabled, enabled by the effect).
|
||||
const [speechSupported, setSpeechSupported] = useState(false);
|
||||
// Voice dictation (Web Speech API). Read through useSyncExternalStore so SSR
|
||||
// markup and the first client render agree: the server snapshot is `false`
|
||||
// (no Speech API to detect), and the client re-reads on hydration. Support
|
||||
// never changes for the life of the page, so the subscription is a no-op.
|
||||
const speechSupported = useSyncExternalStore(
|
||||
() => () => {},
|
||||
() => getSpeechRecognition() !== null,
|
||||
() => false,
|
||||
);
|
||||
const [isListening, setIsListening] = useState(false);
|
||||
const recognitionRef = useRef<SpeechRecognitionLike | null>(null);
|
||||
// The textarea contents when dictation started; transcript is appended to it.
|
||||
const dictationBaseRef = useRef("");
|
||||
|
||||
useEffect(() => {
|
||||
setSpeechSupported(getSpeechRecognition() !== null);
|
||||
return () => recognitionRef.current?.stop();
|
||||
const recognition = recognitionRef;
|
||||
return () => recognition.current?.stop();
|
||||
}, []);
|
||||
|
||||
const toggleDictation = useCallback(() => {
|
||||
|
||||
@@ -139,8 +139,14 @@ export function ChatPanel() {
|
||||
// Persisted conversation: a client-owned thread id (a fresh one per new chat),
|
||||
// saved to the server after each exchange so history survives reloads.
|
||||
const [threadId, setThreadId] = useState<string>(() => nanoid());
|
||||
// Mirrored into a ref for the transport's fetch closure, which is memoized and
|
||||
// must not be rebuilt per thread. Written in an effect rather than during
|
||||
// render: a render can be thrown away or replayed, and mutating a ref there
|
||||
// makes it observable — the write has to happen once the render is committed.
|
||||
const threadIdRef = useRef(threadId);
|
||||
threadIdRef.current = threadId;
|
||||
useEffect(() => {
|
||||
threadIdRef.current = threadId;
|
||||
}, [threadId]);
|
||||
// Skip the auto-save that would otherwise fire right after loading a thread
|
||||
// (which would needlessly bump it to the top of the history).
|
||||
const justLoadedRef = useRef(false);
|
||||
@@ -188,7 +194,17 @@ export function ChatPanel() {
|
||||
getAiConfig()
|
||||
.then((cfg) => {
|
||||
if (cancelled) return;
|
||||
setModel(cfg.mode === "local" ? "ollama" : cfg.defaultModel);
|
||||
// Seed the model to match the configured mode. In "auto" we prefer the
|
||||
// user's cloud default when a key exists, else fall back to the local
|
||||
// sentinel (mirrors the backend's provider resolution).
|
||||
const hasApiKey = Object.values(cfg.apiKeySet).some(Boolean);
|
||||
const seeded =
|
||||
cfg.mode === "local"
|
||||
? "ollama"
|
||||
: cfg.mode === "auto" && !hasApiKey
|
||||
? "ollama"
|
||||
: cfg.defaultModel;
|
||||
setModel(seeded);
|
||||
setEffort(cfg.defaultEffort);
|
||||
})
|
||||
.catch(() => {
|
||||
@@ -204,9 +220,11 @@ export function ChatPanel() {
|
||||
// stays visible until acknowledged and isn't duplicated. Reset the dismissed
|
||||
// flag whenever a fresh error arrives.
|
||||
const [errorDismissed, setErrorDismissed] = useState(false);
|
||||
useEffect(() => {
|
||||
const [prevError, setPrevError] = useState(error);
|
||||
if (prevError !== error) {
|
||||
setPrevError(error);
|
||||
if (error) setErrorDismissed(false);
|
||||
}, [error]);
|
||||
}
|
||||
|
||||
const isCloudModel = (getModel(model)?.provider ?? "ollama") !== "ollama";
|
||||
|
||||
@@ -291,9 +309,16 @@ export function ChatPanel() {
|
||||
);
|
||||
|
||||
// Drain the queue one message at a time whenever the chat returns to idle.
|
||||
//
|
||||
// This is the shape the rule exists to catch, but it's the shape we want: the
|
||||
// trigger is the transport going idle — an external async system — and the
|
||||
// dequeue has to happen in the same tick we hand the message to `send`, or a
|
||||
// re-render could drain it twice. There's no render-phase equivalent, since
|
||||
// `send` is a side effect.
|
||||
useEffect(() => {
|
||||
if (status !== "ready" || pendingConsent || queued.length === 0) return;
|
||||
const [next, ...rest] = queued;
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setQueued(rest);
|
||||
if (next) void send(next.text, next.files);
|
||||
}, [status, pendingConsent, queued, send]);
|
||||
@@ -328,6 +353,10 @@ export function ChatPanel() {
|
||||
|
||||
// Open a saved thread from `/?thread=<id>` (sidebar history); a bare `/` starts
|
||||
// a fresh chat. Driven by the URL so the sidebar links and "New chat" work.
|
||||
//
|
||||
// Stays an effect: the thread branch is an async fetch, and the fresh-chat
|
||||
// branch mints an id with nanoid(), which is impure and so can't be adjusted
|
||||
// during render — moving it there would just trade this for a purity error.
|
||||
const requestedThread = searchParams.get("thread");
|
||||
useEffect(() => {
|
||||
if (requestedThread) {
|
||||
@@ -357,6 +386,7 @@ export function ChatPanel() {
|
||||
};
|
||||
}
|
||||
// No ?thread → fresh chat (e.g. after "New chat").
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setThreadId(nanoid());
|
||||
setMessages([]);
|
||||
}, [requestedThread, setMessages]);
|
||||
@@ -687,6 +717,22 @@ export function ChatPanel() {
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
// Fallback: a structured card the client doesn't recognize (e.g. a
|
||||
// data part added or renamed on the backend). Surface a small
|
||||
// placeholder so a written-but-unhandled result is never silently
|
||||
// invisible. `data-step`/`data-source` intentionally render nothing
|
||||
// here (they're consumed above), so skip them.
|
||||
if (
|
||||
part.type.startsWith("data-") &&
|
||||
part.type !== "data-step" &&
|
||||
part.type !== "data-source"
|
||||
) {
|
||||
return (
|
||||
<Badge className="self-start" key={key} variant="outline">
|
||||
{t("chat.card.unsupported")}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
})}
|
||||
|
||||
@@ -723,8 +769,7 @@ export function ChatPanel() {
|
||||
<div className="flex w-full flex-col gap-3">
|
||||
{errorAlert}
|
||||
{veilGate}
|
||||
{/* One-time setup heads-up — only on the empty state, so it clears
|
||||
itself once the first message is sent. */}
|
||||
{/* Setup heads-up when no AI provider is configured. */}
|
||||
<AiSetupNotice />
|
||||
{promptInput}
|
||||
<Suggestions className="justify-center pt-1">
|
||||
@@ -761,6 +806,9 @@ export function ChatPanel() {
|
||||
{errorAlert}
|
||||
{veilGate}
|
||||
{queuePanel}
|
||||
{/* Also warn mid-conversation when no AI provider is configured, so
|
||||
failing replies have a visible cause and a fix. */}
|
||||
<AiSetupNotice />
|
||||
{promptInput}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -23,6 +23,8 @@ import {
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Tabs, TabsList, TabsTab } from "@/components/ui/tabs";
|
||||
import { PatientDetail } from "@/components/patients/patient-detail";
|
||||
import { ROLE_LABELS } from "@/lib/access";
|
||||
import { authClient } from "@/lib/auth-client";
|
||||
import { cn } from "@/lib/utils";
|
||||
@@ -38,6 +40,11 @@ import { uploadAttachment } from "@/lib/attachments";
|
||||
import { hasClinicalAccess, useActiveRole } from "@/lib/roles";
|
||||
import { listProviders, type Provider } from "@/lib/staff";
|
||||
import { notify } from "@/lib/toast";
|
||||
import { useWalletSync } from "@/components/wallet/use-wallet-sync";
|
||||
import {
|
||||
DialogStepper,
|
||||
WalletSyncStep,
|
||||
} from "@/components/wallet/wallet-sync-step";
|
||||
|
||||
type PatientFormDialogProps = {
|
||||
open: boolean;
|
||||
@@ -233,6 +240,24 @@ export function PatientFormDialog({
|
||||
const [fileNumber, setFileNumber] = useState(() =>
|
||||
isEdit && patient ? patient.fileNumber : generateFileNumber()
|
||||
);
|
||||
const [step, setStep] = useState<"form" | "wallet">("form");
|
||||
// Editing an existing record shows Show/Add tabs: "Show" (default) is the
|
||||
// read-only record; "Add" is the editable form with the Add buttons. Create
|
||||
// and import-review keep the plain form (nothing to show yet).
|
||||
const showTabs = isEdit && !isReview && Boolean(patient);
|
||||
const [tab, setTab] = useState<"add" | "show">(showTabs ? "show" : "add");
|
||||
|
||||
// Only edits to an existing (non-review) record can sync to a wallet — a newly
|
||||
// created patient has no wallet, and review mode stages an import.
|
||||
const sync = useWalletSync(isEdit && !isReview ? fileNumber : null);
|
||||
|
||||
const handleOpenChange = (o: boolean) => {
|
||||
onOpenChange(o);
|
||||
if (!o) {
|
||||
setStep("form");
|
||||
sync.reset();
|
||||
}
|
||||
};
|
||||
const [name, setName] = useState(patient?.name ?? "");
|
||||
const [age, setAge] = useState(patient ? String(patient.age) : "");
|
||||
const [sex, setSex] = useState<Patient["sex"]>(patient?.sex ?? "F");
|
||||
@@ -378,6 +403,10 @@ export function PatientFormDialog({
|
||||
t("patientForm.updatedTitle"),
|
||||
t("patientForm.updatedBody", { name: saved.name }),
|
||||
);
|
||||
if (await sync.ensureLinked()) {
|
||||
setStep("wallet");
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
onCreated?.(saved.fileNumber);
|
||||
notify.success(
|
||||
@@ -400,8 +429,8 @@ export function PatientFormDialog({
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog onOpenChange={onOpenChange} open={open}>
|
||||
<DialogPopup className="max-h-[85dvh] sm:max-w-lg">
|
||||
<Dialog onOpenChange={handleOpenChange} open={open}>
|
||||
<DialogPopup className="flex max-h-[85dvh] flex-col sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{isReview
|
||||
@@ -419,13 +448,39 @@ export function PatientFormDialog({
|
||||
})
|
||||
: t("patientForm.createDescription")}
|
||||
</DialogDescription>
|
||||
{sync.linked && <DialogStepper step={step} />}
|
||||
</DialogHeader>
|
||||
|
||||
{step === "wallet" ? (
|
||||
<WalletSyncStep
|
||||
onDone={() => handleOpenChange(false)}
|
||||
patientName={name.trim()}
|
||||
summary={t("walletSync.summary.demographics")}
|
||||
sync={sync}
|
||||
/>
|
||||
) : (
|
||||
<form className="contents" onSubmit={handleSubmit}>
|
||||
{showTabs && (
|
||||
<div className="px-1 pt-1">
|
||||
<Tabs
|
||||
onValueChange={(value) => setTab(value as "add" | "show")}
|
||||
value={tab}
|
||||
>
|
||||
<TabsList className="w-full">
|
||||
<TabsTab value="add">{t("patientForm.tabs.add")}</TabsTab>
|
||||
<TabsTab value="show">{t("patientForm.tabs.show")}</TabsTab>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
</div>
|
||||
)}
|
||||
<DialogPanel
|
||||
scrollFade={false}
|
||||
className="no-scrollbar flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto"
|
||||
>
|
||||
{showTabs && tab === "show" && patient ? (
|
||||
<PatientDetail patient={patient} />
|
||||
) : (
|
||||
<>
|
||||
<Field label={t("patientForm.fileNumber")}>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
@@ -749,6 +804,8 @@ export function PatientFormDialog({
|
||||
)}
|
||||
|
||||
<StagedFilesField onChange={setFiles} value={files} />
|
||||
</>
|
||||
)}
|
||||
</DialogPanel>
|
||||
|
||||
<DialogFooter className="flex-col items-stretch gap-2 sm:flex-row sm:items-center">
|
||||
@@ -756,19 +813,22 @@ export function PatientFormDialog({
|
||||
<p className="text-sm text-destructive sm:me-auto">{error}</p>
|
||||
)}
|
||||
<DialogClose render={<Button type="button" variant="outline" />}>
|
||||
{t("patientForm.cancel")}
|
||||
{tab === "show" ? t("patientForm.close") : t("patientForm.cancel")}
|
||||
</DialogClose>
|
||||
<Button disabled={!name.trim() || submitting} type="submit">
|
||||
{submitting
|
||||
? t("patientForm.saving")
|
||||
: isReview
|
||||
? t("patientForm.saveDraft")
|
||||
: isEdit
|
||||
? t("patientForm.saveChanges")
|
||||
: t("patientForm.savePatient")}
|
||||
</Button>
|
||||
{tab !== "show" && (
|
||||
<Button disabled={!name.trim() || submitting} type="submit">
|
||||
{submitting
|
||||
? t("patientForm.saving")
|
||||
: isReview
|
||||
? t("patientForm.saveDraft")
|
||||
: isEdit
|
||||
? t("patientForm.saveChanges")
|
||||
: t("patientForm.savePatient")}
|
||||
</Button>
|
||||
)}
|
||||
</DialogFooter>
|
||||
</form>
|
||||
)}
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
);
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
// array fields (invoice line items, inventory items) edited as add/remove rows.
|
||||
|
||||
import { Plus, X } from "lucide-react";
|
||||
import { type ReactNode, useEffect, useState } from "react";
|
||||
import { type ReactNode, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -196,10 +196,14 @@ export function RecordEditDialog({
|
||||
const schema = EDIT_SCHEMAS[kind];
|
||||
const [draft, setDraft] = useState<Rec>(record);
|
||||
|
||||
// Re-seed the draft whenever a fresh record is opened for editing.
|
||||
useEffect(() => {
|
||||
if (open) setDraft(record);
|
||||
}, [open, record]);
|
||||
// Re-seed the draft whenever a fresh record is opened for editing. Adjusted
|
||||
// during render so the form never paints the previous record's values.
|
||||
const [prevSeed, setPrevSeed] = useState<Rec | null>(null);
|
||||
const seed = open ? record : null;
|
||||
if (prevSeed !== seed) {
|
||||
setPrevSeed(seed);
|
||||
if (seed) setDraft(seed);
|
||||
}
|
||||
|
||||
const setField = (key: string, value: unknown) =>
|
||||
setDraft((d) => ({ ...d, [key]: value }));
|
||||
|
||||
@@ -75,7 +75,7 @@ const dotClass: Record<Kind, string> = {
|
||||
// A round node with the label below it and hidden connection handles so edges
|
||||
// meet the dot's centre cleanly. Memoized; it re-renders only when the hovered
|
||||
// id changes (via context), never via React Flow re-measuring.
|
||||
const RecordNode = memo(function RecordNode({ id, data }: NodeProps) {
|
||||
const RecordNode = memo(function RecordNode({ data }: NodeProps) {
|
||||
const { label, sub, kind, family } = data as RecordNodeData;
|
||||
const hovered = useContext(HoverContext);
|
||||
const focus: "active" | "dim" | null =
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
Split,
|
||||
Trash2,
|
||||
} from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { AiBadge } from "@/components/ai-badge";
|
||||
@@ -67,9 +67,14 @@ export function InvoiceDetailSheet({
|
||||
const [count, setCount] = useState(3);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
// Collapse the "show more" list back when a different invoice is shown.
|
||||
// Adjusted during render so the sheet never paints the previous invoice's
|
||||
// expanded state.
|
||||
const [prevInvoiceId, setPrevInvoiceId] = useState(invoice?.id);
|
||||
if (prevInvoiceId !== invoice?.id) {
|
||||
setPrevInvoiceId(invoice?.id);
|
||||
setCount(3);
|
||||
}, [invoice?.id]);
|
||||
}
|
||||
|
||||
if (!invoice) {
|
||||
return (
|
||||
|
||||
@@ -12,6 +12,7 @@ import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Calendar } from "@/components/ui/calendar";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Combobox, type ComboboxOption } from "@/components/ui/combobox";
|
||||
import {
|
||||
Dialog,
|
||||
@@ -35,6 +36,11 @@ import {
|
||||
} from "@/lib/invoices";
|
||||
import { listPatients, type Patient } from "@/lib/patients";
|
||||
import { notify } from "@/lib/toast";
|
||||
import { useWalletSync } from "@/components/wallet/use-wallet-sync";
|
||||
import {
|
||||
DialogStepper,
|
||||
WalletSyncStep,
|
||||
} from "@/components/wallet/wallet-sync-step";
|
||||
|
||||
const STATUSES: InvoiceStatus[] = ["draft", "sent", "paid", "void"];
|
||||
|
||||
@@ -59,12 +65,23 @@ function Field({ label, children }: { label: string; children: ReactNode }) {
|
||||
);
|
||||
}
|
||||
|
||||
// Local start-of-day, used to disable days strictly before today.
|
||||
const startOfToday = () => {
|
||||
const d = new Date();
|
||||
d.setHours(0, 0, 0, 0);
|
||||
return d;
|
||||
};
|
||||
|
||||
function DatePicker({
|
||||
value,
|
||||
onChange,
|
||||
allowPast = true,
|
||||
}: {
|
||||
value: Date;
|
||||
onChange: (d: Date) => void;
|
||||
// When false, days before today are disabled (used for the issue date unless
|
||||
// the clinician opts into back-dating an older invoice).
|
||||
allowPast?: boolean;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
@@ -87,6 +104,7 @@ function DatePicker({
|
||||
/>
|
||||
<PopoverPopup>
|
||||
<Calendar
|
||||
disabled={allowPast ? undefined : { before: startOfToday() }}
|
||||
mode="single"
|
||||
onSelect={(d) => {
|
||||
if (d) {
|
||||
@@ -131,18 +149,40 @@ export function InvoiceFormDialog({
|
||||
: null;
|
||||
|
||||
const [issuedAt, setIssuedAt] = useState<Date>(() => new Date());
|
||||
// Off by default: the issue date can't be back-dated unless the clinician
|
||||
// opts in (for recording an older, pre-existing invoice).
|
||||
const [allowBackdate, setAllowBackdate] = useState(false);
|
||||
const [hasDue, setHasDue] = useState(false);
|
||||
const [dueAt, setDueAt] = useState<Date>(() => new Date());
|
||||
const [status, setStatus] = useState<InvoiceStatus>("draft");
|
||||
const [notes, setNotes] = useState("");
|
||||
const [lineItems, setLineItems] = useState<InvoiceLineItem[]>([emptyLine()]);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [step, setStep] = useState<"form" | "wallet">("form");
|
||||
const [walletSummary, setWalletSummary] = useState("");
|
||||
|
||||
// Seed the form when opening.
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
if (mode === "edit" && invoice) {
|
||||
const activePatient = fixedPatient ?? selected;
|
||||
const sync = useWalletSync(activePatient?.fileNumber ?? null);
|
||||
|
||||
const handleOpenChange = (next: boolean) => {
|
||||
if (!next) {
|
||||
setStep("form");
|
||||
sync.reset();
|
||||
}
|
||||
onOpenChange(next);
|
||||
};
|
||||
|
||||
// Seed the form when opening. Adjusted during render rather than in an
|
||||
// effect, so the dialog never paints one frame of the previous invoice.
|
||||
// `false` means closed, so reopening on the same invoice re-seeds.
|
||||
const [prevSeed, setPrevSeed] = useState<Invoice | null | false>(false);
|
||||
const seed = open ? (invoice ?? null) : false;
|
||||
if (prevSeed !== seed) {
|
||||
setPrevSeed(seed);
|
||||
if (open && mode === "edit" && invoice) {
|
||||
setIssuedAt(new Date(`${invoice.issuedAt}T00:00:00`));
|
||||
// Existing invoices legitimately carry past issue dates.
|
||||
setAllowBackdate(true);
|
||||
setHasDue(Boolean(invoice.dueAt));
|
||||
setDueAt(new Date(`${invoice.dueAt ?? invoice.issuedAt}T00:00:00`));
|
||||
setStatus(invoice.status);
|
||||
@@ -150,16 +190,17 @@ export function InvoiceFormDialog({
|
||||
setLineItems(
|
||||
invoice.lineItems.length ? invoice.lineItems : [emptyLine()],
|
||||
);
|
||||
} else {
|
||||
} else if (open) {
|
||||
setSelected(null);
|
||||
setIssuedAt(new Date());
|
||||
setAllowBackdate(false);
|
||||
setHasDue(false);
|
||||
setDueAt(new Date());
|
||||
setStatus("draft");
|
||||
setNotes("");
|
||||
setLineItems([emptyLine()]);
|
||||
}
|
||||
}, [open, mode, invoice]);
|
||||
}
|
||||
|
||||
// Load patients lazily for the create combobox.
|
||||
useEffect(() => {
|
||||
@@ -236,7 +277,16 @@ export function InvoiceFormDialog({
|
||||
})
|
||||
: await createInvoice(payload);
|
||||
onSaved(saved);
|
||||
onOpenChange(false);
|
||||
if (await sync.ensureLinked()) {
|
||||
setWalletSummary(
|
||||
mode === "edit"
|
||||
? t("walletSync.summary.invoiceUpdated", { number: saved.number })
|
||||
: t("walletSync.summary.invoiceCreated", { number: saved.number }),
|
||||
);
|
||||
setStep("wallet");
|
||||
} else {
|
||||
onOpenChange(false);
|
||||
}
|
||||
} catch {
|
||||
notify.error(t("invoices.addFailedTitle"), t("invoices.addFailedBody"));
|
||||
} finally {
|
||||
@@ -245,8 +295,8 @@ export function InvoiceFormDialog({
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog onOpenChange={onOpenChange} open={open}>
|
||||
<DialogPopup className="sm:max-w-lg">
|
||||
<Dialog onOpenChange={handleOpenChange} open={open}>
|
||||
<DialogPopup className="flex max-h-[85dvh] flex-col sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{mode === "edit"
|
||||
@@ -256,8 +306,17 @@ export function InvoiceFormDialog({
|
||||
<DialogDescription>
|
||||
{t("invoices.dialog.description")}
|
||||
</DialogDescription>
|
||||
{sync.linked && <DialogStepper step={step} />}
|
||||
</DialogHeader>
|
||||
|
||||
{step === "wallet" ? (
|
||||
<WalletSyncStep
|
||||
onDone={() => handleOpenChange(false)}
|
||||
patientName={activePatient?.name ?? ""}
|
||||
summary={walletSummary}
|
||||
sync={sync}
|
||||
/>
|
||||
) : (
|
||||
<form className="contents" onSubmit={submit}>
|
||||
<DialogPanel className="flex flex-col gap-4">
|
||||
<Field label={t("invoices.dialog.patient")}>
|
||||
@@ -310,17 +369,34 @@ export function InvoiceFormDialog({
|
||||
</Field>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Field label={t("invoices.dialog.issued")}>
|
||||
<DatePicker onChange={setIssuedAt} value={issuedAt} />
|
||||
</Field>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<span className="flex items-center justify-between gap-2 text-muted-foreground text-xs">
|
||||
{t("invoices.dialog.issued")}
|
||||
<label
|
||||
className="flex items-center gap-1.5 text-[11px]"
|
||||
htmlFor="invoice-backdate"
|
||||
>
|
||||
<Checkbox
|
||||
checked={allowBackdate}
|
||||
id="invoice-backdate"
|
||||
onCheckedChange={(checked) => setAllowBackdate(checked)}
|
||||
/>
|
||||
{t("invoices.dialog.backdate")}
|
||||
</label>
|
||||
</span>
|
||||
<DatePicker
|
||||
allowPast={allowBackdate}
|
||||
onChange={setIssuedAt}
|
||||
value={issuedAt}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<span className="flex items-center justify-between text-muted-foreground text-xs">
|
||||
{t("invoices.dialog.due")}
|
||||
<input
|
||||
<Checkbox
|
||||
aria-label={t("invoices.dialog.due")}
|
||||
checked={hasDue}
|
||||
onChange={(e) => setHasDue(e.target.checked)}
|
||||
type="checkbox"
|
||||
onCheckedChange={(checked) => setHasDue(checked)}
|
||||
/>
|
||||
</span>
|
||||
{hasDue ? (
|
||||
@@ -445,6 +521,7 @@ export function InvoiceFormDialog({
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
)}
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
);
|
||||
|
||||
@@ -76,7 +76,6 @@ function VideoTile({
|
||||
speaking ? "border-success" : "border-transparent",
|
||||
)}
|
||||
>
|
||||
{/* eslint-disable-next-line jsx-a11y/media-has-caption */}
|
||||
<video
|
||||
autoPlay
|
||||
className={cn("size-full object-cover", !showVideo && "invisible")}
|
||||
|
||||
@@ -59,7 +59,6 @@ export function MeetingsView() {
|
||||
// ?with=<userId> from the Messages inbox "call" button — open the scheduler
|
||||
// pre-targeted at that person so the user can connect with them.
|
||||
const deepLinkWith = searchParams.get("with");
|
||||
const openedDeepLink = useRef<string | null>(null);
|
||||
const openedWith = useRef<string | null>(null);
|
||||
|
||||
const [tab, setTab] = useState<Tab>("rooms");
|
||||
@@ -104,16 +103,18 @@ export function MeetingsView() {
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Auto-join a room deep-linked from an invite (?room=).
|
||||
useEffect(() => {
|
||||
if (!deepLinkRoom || rooms.length === 0) return;
|
||||
if (openedDeepLink.current === deepLinkRoom) return;
|
||||
// Auto-join a room deep-linked from an invite (?room=). Resolved during
|
||||
// render once the room list arrives, so the room opens on the same paint the
|
||||
// list does instead of flashing the default tab first.
|
||||
const [openedDeepLink, setOpenedDeepLink] = useState<string | null>(null);
|
||||
if (deepLinkRoom && rooms.length > 0 && openedDeepLink !== deepLinkRoom) {
|
||||
const room = rooms.find((r) => r.id === deepLinkRoom);
|
||||
if (!room) return;
|
||||
openedDeepLink.current = deepLinkRoom;
|
||||
setTab("rooms");
|
||||
setActiveRoom(room);
|
||||
}, [deepLinkRoom, rooms]);
|
||||
if (room) {
|
||||
setOpenedDeepLink(deepLinkRoom);
|
||||
setTab("rooms");
|
||||
setActiveRoom(room);
|
||||
}
|
||||
}
|
||||
|
||||
// Open the scheduler pre-targeted at a person (?with=) from the inbox.
|
||||
useEffect(() => {
|
||||
|
||||
@@ -54,12 +54,21 @@ export function ScheduleMeetingDialog({
|
||||
const [picked, setPicked] = useState<Set<string>>(new Set());
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
// Re-seed the form each time the dialog opens. Adjusted during render so it
|
||||
// never paints the previous meeting's title or participants.
|
||||
const [prevOpen, setPrevOpen] = useState(false);
|
||||
if (prevOpen !== open) {
|
||||
setPrevOpen(open);
|
||||
if (open) {
|
||||
setTitle("");
|
||||
setDate(defaultDate ?? "");
|
||||
setTime("09:00");
|
||||
setPicked(new Set(defaultParticipants ?? []));
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setTitle("");
|
||||
setDate(defaultDate ?? "");
|
||||
setTime("09:00");
|
||||
setPicked(new Set(defaultParticipants ?? []));
|
||||
listClinicMembers()
|
||||
.then(setMembers)
|
||||
.catch(() => setMembers([]));
|
||||
|
||||
@@ -8,11 +8,17 @@ import { useEffect, useState } from "react";
|
||||
export function useSpeaking(stream: MediaStream | null): boolean {
|
||||
const [speaking, setSpeaking] = useState(false);
|
||||
|
||||
// Stop reporting "speaking" the moment the stream goes away or changes, so a
|
||||
// muted tile can't keep a stale ring. Adjusted during render rather than in
|
||||
// the effect below, which is only for driving the Web Audio graph.
|
||||
const [prevStream, setPrevStream] = useState(stream);
|
||||
if (prevStream !== stream) {
|
||||
setPrevStream(stream);
|
||||
setSpeaking(false);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!stream || stream.getAudioTracks().length === 0) {
|
||||
setSpeaking(false);
|
||||
return;
|
||||
}
|
||||
if (!stream || stream.getAudioTracks().length === 0) return;
|
||||
let ctx: AudioContext | null = null;
|
||||
let raf = 0;
|
||||
try {
|
||||
|
||||
@@ -245,10 +245,15 @@ export function MessagesView() {
|
||||
const [appts, setAppts] = useState<Appointment[]>([]);
|
||||
const [apptQuery, setApptQuery] = useState("");
|
||||
|
||||
// Refs so the socket handler (registered once) reads current values.
|
||||
// Refs so the socket handler (registered once) reads current values. Written
|
||||
// in an effect rather than during render: a render can be thrown away or
|
||||
// replayed, and mutating a ref there makes it observable — the write has to
|
||||
// happen once the render is committed.
|
||||
const selectedIdRef = useRef<string | null>(null);
|
||||
const myIdRef = useRef<string>("");
|
||||
myIdRef.current = myId;
|
||||
useEffect(() => {
|
||||
myIdRef.current = myId;
|
||||
}, [myId]);
|
||||
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
@@ -354,7 +359,6 @@ export function MessagesView() {
|
||||
openedDeepLink.current = deepLinkConversation;
|
||||
open(deepLinkConversation);
|
||||
// `open` is stable enough for this one-shot; deps intentionally minimal.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [deepLinkConversation, conversations]);
|
||||
|
||||
const send = (event: FormEvent) => {
|
||||
|
||||
@@ -61,6 +61,9 @@ export function NotesView() {
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
// `t` intentionally omitted: it is only read to build a failure message,
|
||||
// and re-fetching on a language change would be pointless.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
const startNew = () => {
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { Check, Loader2, QrCode, Smartphone, X } from "lucide-react";
|
||||
import { Check, Loader2, QrCode, ScanLine, Smartphone, X } from "lucide-react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import QRCodeSvg from "react-qr-code";
|
||||
|
||||
import { PatientFormDialog } from "@/components/chat/patient-form-dialog";
|
||||
import { BarcodeScanner } from "@/components/scan/barcode-scanner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
@@ -63,6 +64,15 @@ export function ImportFromWalletDialog({
|
||||
const { t } = useTranslation();
|
||||
const [mode, setMode] = useState<Mode>("number");
|
||||
const [walletNumber, setWalletNumber] = useState("");
|
||||
const [scanOpen, setScanOpen] = useState(false);
|
||||
|
||||
// Scanning the wallet code shown on the patient's phone (QR or 2D barcode)
|
||||
// drops its wallet number straight into the field.
|
||||
const handleScan = (value: string) => {
|
||||
setScanOpen(false);
|
||||
setMode("number");
|
||||
setWalletNumber(value.trim());
|
||||
};
|
||||
const [temporary, setTemporary] = useState(false);
|
||||
const [durationHours, setDurationHours] = useState<number>(24);
|
||||
const [phase, setPhase] = useState<Phase>("form");
|
||||
@@ -79,8 +89,12 @@ export function ImportFromWalletDialog({
|
||||
}
|
||||
};
|
||||
|
||||
// Reset everything whenever the dialog is (re)opened.
|
||||
useEffect(() => {
|
||||
// Reset everything whenever the dialog is (re)opened. Adjusted during render
|
||||
// so a reopened dialog never flashes the previous import's wallet number or
|
||||
// state before clearing.
|
||||
const [prevOpen, setPrevOpen] = useState(false);
|
||||
if (prevOpen !== open) {
|
||||
setPrevOpen(open);
|
||||
if (open) {
|
||||
setMode("number");
|
||||
setWalletNumber("");
|
||||
@@ -92,8 +106,10 @@ export function ImportFromWalletDialog({
|
||||
setPairUri(null);
|
||||
setReviewOpen(false);
|
||||
}
|
||||
return stopPolling;
|
||||
}, [open]);
|
||||
}
|
||||
|
||||
// Stop polling when the dialog closes or unmounts.
|
||||
useEffect(() => stopPolling, [open]);
|
||||
|
||||
// Poll the request until the patient approves/denies on their device.
|
||||
useEffect(() => {
|
||||
@@ -296,13 +312,25 @@ export function ImportFromWalletDialog({
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{t("patients.importApp.walletLabel")}
|
||||
</span>
|
||||
<Input
|
||||
autoFocus
|
||||
disabled={phase === "requesting"}
|
||||
onChange={(e) => setWalletNumber(e.target.value)}
|
||||
placeholder={t("patients.importApp.walletPlaceholder")}
|
||||
value={walletNumber}
|
||||
/>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
autoFocus
|
||||
disabled={phase === "requesting"}
|
||||
onChange={(e) => setWalletNumber(e.target.value)}
|
||||
placeholder={t("patients.importApp.walletPlaceholder")}
|
||||
value={walletNumber}
|
||||
/>
|
||||
<Button
|
||||
aria-label={t("patients.importApp.scan")}
|
||||
disabled={phase === "requesting"}
|
||||
onClick={() => setScanOpen(true)}
|
||||
size="icon"
|
||||
type="button"
|
||||
variant="outline"
|
||||
>
|
||||
<ScanLine className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</label>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
@@ -405,6 +433,14 @@ export function ImportFromWalletDialog({
|
||||
patient={request.draft}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<BarcodeScanner
|
||||
description={t("patients.importApp.scanHint")}
|
||||
onDetected={handleScan}
|
||||
onOpenChange={setScanOpen}
|
||||
open={scanOpen}
|
||||
title={t("patients.importApp.scan")}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -102,14 +102,29 @@ export function PatientDetailSheet({
|
||||
// Bumped on open so the editor remounts with the latest patient data.
|
||||
const [editKey, setEditKey] = useState(0);
|
||||
|
||||
// Clear the previous chart the moment a different one is opened, so the sheet
|
||||
// can't show one patient's data under another's name while the fetch is in
|
||||
// flight. Adjusted during render rather than in the effects below, which are
|
||||
// only for the fetching itself. Keyed on the role too, so losing clinical
|
||||
// access drops the wallet state instead of leaving the "Push update" button
|
||||
// lit from the previous render.
|
||||
const chart = open ? `${fileNumber ?? ""}|${role ?? ""}` : null;
|
||||
const [prevChart, setPrevChart] = useState<string | null>(null);
|
||||
if (prevChart !== chart) {
|
||||
setPrevChart(chart);
|
||||
setWalletLinked(false);
|
||||
if (chart) {
|
||||
setStatus("loading");
|
||||
setPatient(null);
|
||||
setPrescriptions([]);
|
||||
setAppointments([]);
|
||||
setInvoices([]);
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !fileNumber) return;
|
||||
let active = true;
|
||||
setStatus("loading");
|
||||
setPatient(null);
|
||||
setPrescriptions([]);
|
||||
setAppointments([]);
|
||||
setInvoices([]);
|
||||
getPatient(fileNumber)
|
||||
.then((data) => {
|
||||
if (!active) return;
|
||||
@@ -138,9 +153,10 @@ export function PatientDetailSheet({
|
||||
|
||||
// Whether this patient is wallet-linked (drives the "Push update" button).
|
||||
// Separate from the main load so it re-checks once the role resolves without
|
||||
// refetching the record. Only clinicians can push.
|
||||
// refetching the record. Only clinicians can push. The reset rides on the
|
||||
// same render-phase clear as the chart above, so the button can't stay lit
|
||||
// from the previous patient.
|
||||
useEffect(() => {
|
||||
setWalletLinked(false);
|
||||
if (!open || !fileNumber || !hasClinicalAccess(role)) return;
|
||||
let active = true;
|
||||
getWalletLink(fileNumber)
|
||||
|
||||
@@ -2,12 +2,19 @@
|
||||
|
||||
import {
|
||||
ArrowLeftRight,
|
||||
CalendarDays,
|
||||
FileDown,
|
||||
type LucideIcon,
|
||||
ListTodo,
|
||||
Mic,
|
||||
MoreHorizontal,
|
||||
Network,
|
||||
NotebookPen,
|
||||
Pencil,
|
||||
Pill,
|
||||
Send,
|
||||
Trash2,
|
||||
UserRound,
|
||||
} from "lucide-react";
|
||||
import { type ReactNode, useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -15,10 +22,21 @@ import { useTranslation } from "react-i18next";
|
||||
import { Sparkline } from "@/components/chat/sparkline";
|
||||
import { AttachmentsSection } from "@/components/patients/patient-files";
|
||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
||||
import { type ActivityEntry, listPatientActivity } from "@/lib/activity";
|
||||
import {
|
||||
type ActivityEntityType,
|
||||
type ActivityEntry,
|
||||
listPatientActivity,
|
||||
} from "@/lib/activity";
|
||||
import { printPatientSummary } from "@/lib/patient-pdf";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Menu,
|
||||
MenuItem,
|
||||
MenuPopup,
|
||||
MenuSeparator,
|
||||
MenuTrigger,
|
||||
} from "@/components/ui/menu";
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
@@ -122,8 +140,18 @@ function TrendBlock({ trend }: { trend: Trend }) {
|
||||
);
|
||||
}
|
||||
|
||||
// Which icon marks each kind of audited change on the timeline.
|
||||
const historyIcon: Record<ActivityEntityType, LucideIcon> = {
|
||||
appointment: CalendarDays,
|
||||
note: NotebookPen,
|
||||
patient: UserRound,
|
||||
prescription: Pill,
|
||||
task: ListTodo,
|
||||
};
|
||||
|
||||
// The patient's record history: every audited add/change on this chart, newest
|
||||
// first. Reuses the clinic activity log scoped to this file number.
|
||||
// first. Reuses the clinic activity log scoped to this file number, laid out as
|
||||
// a vertical timeline — who made the change, what happened, and when.
|
||||
function RecordHistory({ fileNumber }: { fileNumber: string }) {
|
||||
const { t } = useTranslation();
|
||||
const [entries, setEntries] = useState<ActivityEntry[] | null>(null);
|
||||
@@ -152,24 +180,40 @@ function RecordHistory({ fileNumber }: { fileNumber: string }) {
|
||||
{t("patientCard.history.empty")}
|
||||
</p>
|
||||
) : (
|
||||
<ol className="flex flex-col gap-3">
|
||||
{entries.map((e) => (
|
||||
<li className="flex items-start gap-3" key={e.id}>
|
||||
<Avatar className="mt-0.5 size-7 shrink-0">
|
||||
<AvatarFallback className="text-[11px]">
|
||||
{e.actorInitials}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="flex min-w-0 flex-1 flex-col">
|
||||
<span className="text-foreground text-sm">
|
||||
<span className="font-medium">{e.actorName}</span> {e.action}
|
||||
</span>
|
||||
<span className="text-muted-foreground text-xs">
|
||||
{new Date(e.createdAt).toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
// A plain vertical rail so EVERY audited change renders in full — the
|
||||
// icon column draws a connector that stretches to the next entry, and
|
||||
// the flex layout mirrors correctly under RTL.
|
||||
<ol className="space-y-0">
|
||||
{entries.map((e, i) => {
|
||||
const Icon = historyIcon[e.entityType] ?? Pencil;
|
||||
const isLast = i === entries.length - 1;
|
||||
return (
|
||||
<li className="flex gap-3" key={e.id}>
|
||||
<div className="flex flex-col items-center">
|
||||
<span className="flex size-6 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground">
|
||||
<Icon size={14} />
|
||||
</span>
|
||||
{!isLast && (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="my-1 w-px flex-1 bg-primary/15"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div
|
||||
className={`min-w-0 flex-1 ${isLast ? "" : "pb-5"}`}
|
||||
>
|
||||
<p className="font-medium text-foreground text-sm">
|
||||
{e.actorName}
|
||||
</p>
|
||||
<p className="text-muted-foreground text-sm">{e.action}</p>
|
||||
<time className="mt-0.5 block font-medium text-muted-foreground text-xs">
|
||||
{new Date(e.createdAt).toLocaleString()}
|
||||
</time>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
)}
|
||||
</Section>
|
||||
@@ -259,6 +303,8 @@ export function PatientDetail({
|
||||
<AvatarFallback>{patient.initials}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-1">
|
||||
{/* Name, status, and the overflow menu share one left-aligned row;
|
||||
Edit now lives inside the menu rather than as a separate button. */}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="font-semibold text-base text-foreground">
|
||||
{patient.name}
|
||||
@@ -266,6 +312,59 @@ export function PatientDetail({
|
||||
<Badge variant={statusVariant[patient.status]}>
|
||||
{t(`patients.status.${patient.status}`)}
|
||||
</Badge>
|
||||
<Menu>
|
||||
<MenuTrigger
|
||||
render={
|
||||
<Button
|
||||
aria-label={t("patientCard.moreActions")}
|
||||
size="icon-sm"
|
||||
type="button"
|
||||
variant="outline"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<MoreHorizontal className="size-4" />
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="start">
|
||||
{onEdit && (
|
||||
<MenuItem onClick={onEdit}>
|
||||
<Pencil className="size-4" />
|
||||
{t("patientCard.edit")}
|
||||
</MenuItem>
|
||||
)}
|
||||
<MenuItem onClick={() => printPatientSummary(patient, t)}>
|
||||
<FileDown className="size-4" />
|
||||
{t("patientCard.exportPdf")}
|
||||
</MenuItem>
|
||||
{onScribe && (
|
||||
<MenuItem onClick={onScribe}>
|
||||
<Mic className="size-4" />
|
||||
{t("scribe.recordVisit")}
|
||||
</MenuItem>
|
||||
)}
|
||||
{onTransfer && (
|
||||
<MenuItem onClick={onTransfer}>
|
||||
<ArrowLeftRight className="size-4" />
|
||||
{t("patients.transfer.action")}
|
||||
</MenuItem>
|
||||
)}
|
||||
{onWalletPush && (
|
||||
<MenuItem onClick={onWalletPush}>
|
||||
<Send className="size-4" />
|
||||
{t("walletPush.action")}
|
||||
</MenuItem>
|
||||
)}
|
||||
{onDelete && (
|
||||
<>
|
||||
<MenuSeparator />
|
||||
<MenuItem onClick={onDelete} variant="destructive">
|
||||
<Trash2 className="size-4" />
|
||||
{t("patients.delete.action")}
|
||||
</MenuItem>
|
||||
</>
|
||||
)}
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
</div>
|
||||
<span className="text-muted-foreground text-sm">{idLine}</span>
|
||||
{patient.alerts.length > 0 && (
|
||||
@@ -279,64 +378,6 @@ export function PatientDetail({
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{/* Actions — their own wrapping row beneath the identity. */}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button
|
||||
onClick={() => printPatientSummary(patient, t)}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="outline"
|
||||
>
|
||||
<FileDown className="size-4" />
|
||||
{t("patientCard.exportPdf")}
|
||||
</Button>
|
||||
{onTransfer && (
|
||||
<Button
|
||||
onClick={onTransfer}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="outline"
|
||||
>
|
||||
<ArrowLeftRight className="size-4" />
|
||||
{t("patients.transfer.action")}
|
||||
</Button>
|
||||
)}
|
||||
{onScribe && (
|
||||
<Button onClick={onScribe} size="sm" type="button" variant="outline">
|
||||
<Mic className="size-4" />
|
||||
{t("scribe.recordVisit")}
|
||||
</Button>
|
||||
)}
|
||||
{onEdit && (
|
||||
<Button onClick={onEdit} size="sm" type="button" variant="outline">
|
||||
<Pencil className="size-4" />
|
||||
{t("patientCard.edit")}
|
||||
</Button>
|
||||
)}
|
||||
{onWalletPush && (
|
||||
<Button
|
||||
onClick={onWalletPush}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="outline"
|
||||
>
|
||||
<Send className="size-4" />
|
||||
{t("walletPush.action")}
|
||||
</Button>
|
||||
)}
|
||||
{onDelete && (
|
||||
<Button
|
||||
aria-label={t("patients.delete.action")}
|
||||
className="ms-auto"
|
||||
onClick={onDelete}
|
||||
size="sm"
|
||||
type="button"
|
||||
variant="destructive"
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Section title={t("patientCard.overview")}>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { Plus, Search, Smartphone } from "lucide-react";
|
||||
import { MoreHorizontal, Plus, Search, Smartphone } from "lucide-react";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -11,10 +11,40 @@ import { ImportFromWalletDialog } from "@/components/patients/import-from-wallet
|
||||
import { PatientDetailSheet } from "@/components/patients/patient-detail-sheet";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CardFrame } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { ListPagination } from "@/components/ui/list-pagination";
|
||||
import {
|
||||
Menu,
|
||||
MenuItem,
|
||||
MenuPopup,
|
||||
MenuTrigger,
|
||||
} from "@/components/ui/menu";
|
||||
import {
|
||||
Select,
|
||||
SelectItem,
|
||||
SelectPopup,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { listPatients, type Patient } from "@/lib/patients";
|
||||
|
||||
type StatusFilter = "all" | Patient["status"];
|
||||
const STATUS_FILTERS: StatusFilter[] = [
|
||||
"all",
|
||||
"active",
|
||||
"inpatient",
|
||||
"discharged",
|
||||
];
|
||||
|
||||
// Rows shown per page on the patients table before paginating.
|
||||
const PAGE_SIZE = 10;
|
||||
|
||||
@@ -32,6 +62,7 @@ const statusVariant: Record<Patient["status"], BadgeVariant> = {
|
||||
export function PatientsView() {
|
||||
const { t } = useTranslation();
|
||||
const [query, setQuery] = useState("");
|
||||
const [statusFilter, setStatusFilter] = useState<StatusFilter>("all");
|
||||
const [addOpen, setAddOpen] = useState(false);
|
||||
const [importOpen, setImportOpen] = useState(false);
|
||||
// Bumped on open so the create dialog remounts with a fresh file # / form.
|
||||
@@ -45,9 +76,10 @@ export function PatientsView() {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
|
||||
// Runs once on mount, and `loading` already starts true, so there's nothing
|
||||
// to flip synchronously here.
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
setLoading(true);
|
||||
listPatients()
|
||||
.then((data) => {
|
||||
if (!active) return;
|
||||
@@ -66,12 +98,24 @@ export function PatientsView() {
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
// `t` intentionally omitted: it is only read to build a failure message,
|
||||
// and re-fetching on a language change would be pointless.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
const q = query.trim().toLowerCase();
|
||||
const patients = allPatients.filter(
|
||||
(p) => !q || p.name.toLowerCase().includes(q) || p.fileNumber.includes(q)
|
||||
);
|
||||
// Search matches name, MRN, problem/condition labels, and allergy substances;
|
||||
// the status filter narrows to one clinical status.
|
||||
const patients = allPatients.filter((p) => {
|
||||
if (statusFilter !== "all" && p.status !== statusFilter) return false;
|
||||
if (!q) return true;
|
||||
return (
|
||||
p.name.toLowerCase().includes(q) ||
|
||||
p.fileNumber.includes(q) ||
|
||||
p.problems.some((problem) => problem.label.toLowerCase().includes(q)) ||
|
||||
p.allergies.some((a) => a.substance.toLowerCase().includes(q))
|
||||
);
|
||||
});
|
||||
|
||||
// Client-side pagination over the filtered list (10/page). Searching resets to
|
||||
// the first page (done in the search handler); `page` is clamped at render so a
|
||||
@@ -133,15 +177,6 @@ export function PatientsView() {
|
||||
value={query}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
className="rounded-3xl"
|
||||
onClick={() => setImportOpen(true)}
|
||||
type="button"
|
||||
variant="outline"
|
||||
>
|
||||
<Smartphone className="size-4" />
|
||||
{t("patients.importFromApp")}
|
||||
</Button>
|
||||
<Button
|
||||
className="rounded-3xl"
|
||||
onClick={() => {
|
||||
@@ -153,58 +188,119 @@ export function PatientsView() {
|
||||
<Plus className="size-4" />
|
||||
{t("patients.add")}
|
||||
</Button>
|
||||
{/* Secondary actions tuck into an overflow menu so the toolbar keeps a
|
||||
single primary CTA. */}
|
||||
<Menu>
|
||||
<MenuTrigger
|
||||
render={
|
||||
<Button
|
||||
aria-label={t("patients.moreActions")}
|
||||
className="rounded-full"
|
||||
size="icon"
|
||||
type="button"
|
||||
variant="outline"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<MoreHorizontal className="size-4" />
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="end">
|
||||
<MenuItem onClick={() => setImportOpen(true)}>
|
||||
<Smartphone className="size-4" />
|
||||
{t("patients.importFromApp")}
|
||||
</MenuItem>
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-8 overflow-hidden rounded-2xl border border-border bg-card/30">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-border border-b text-start text-xs text-muted-foreground uppercase">
|
||||
<th className="px-4 py-3 font-medium">{t("patients.columns.name")}</th>
|
||||
<th className="px-4 py-3 font-medium">{t("patients.columns.mrn")}</th>
|
||||
<th className="px-4 py-3 font-medium">
|
||||
{/* Filter sits on its own row just above the table so the toolbar stays a
|
||||
clean title + search + primary actions cluster. */}
|
||||
<div className="mt-8 flex items-center gap-3">
|
||||
<span className="text-sm font-medium text-muted-foreground">
|
||||
{t("patients.filterLabel")}
|
||||
</span>
|
||||
<Select
|
||||
onValueChange={(value) => {
|
||||
setStatusFilter((value ?? "all") as StatusFilter);
|
||||
setPage(1);
|
||||
}}
|
||||
value={statusFilter}
|
||||
>
|
||||
<SelectTrigger
|
||||
aria-label={t("patients.filterStatus")}
|
||||
className="w-40"
|
||||
>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectPopup>
|
||||
{STATUS_FILTERS.map((value) => (
|
||||
<SelectItem key={value} value={value}>
|
||||
{value === "all"
|
||||
? t("patients.allStatuses")
|
||||
: t(`patients.status.${value}`)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<CardFrame className="mt-4 w-full">
|
||||
<Table variant="card">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="ps-4 text-xs uppercase">
|
||||
{t("patients.columns.name")}
|
||||
</TableHead>
|
||||
<TableHead className="text-xs uppercase">
|
||||
{t("patients.columns.mrn")}
|
||||
</TableHead>
|
||||
<TableHead className="text-xs uppercase">
|
||||
{t("patients.columns.ageSex")}
|
||||
</th>
|
||||
<th className="px-4 py-3 font-medium">
|
||||
</TableHead>
|
||||
<TableHead className="text-xs uppercase">
|
||||
{t("patients.columns.status")}
|
||||
</th>
|
||||
<th className="px-4 py-3 font-medium">
|
||||
</TableHead>
|
||||
<TableHead className="text-xs uppercase">
|
||||
{t("patients.columns.lastSeen")}
|
||||
</th>
|
||||
<th className="px-4 py-3 font-medium">
|
||||
</TableHead>
|
||||
<TableHead className="pe-4 text-xs uppercase">
|
||||
{t("patients.columns.allergies")}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{loading ? (
|
||||
<tr>
|
||||
<td
|
||||
className="px-4 py-10 text-center text-muted-foreground"
|
||||
<TableRow>
|
||||
<TableCell
|
||||
className="py-10 text-center text-muted-foreground"
|
||||
colSpan={6}
|
||||
>
|
||||
{t("patients.loading")}
|
||||
</td>
|
||||
</tr>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : loadError ? (
|
||||
<tr>
|
||||
<td className="px-4 py-10 text-center text-destructive" colSpan={6}>
|
||||
<TableRow>
|
||||
<TableCell
|
||||
className="py-10 text-center text-destructive"
|
||||
colSpan={6}
|
||||
>
|
||||
{loadError}
|
||||
</td>
|
||||
</tr>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : patients.length === 0 ? (
|
||||
<tr>
|
||||
<td
|
||||
className="px-4 py-10 text-center text-muted-foreground"
|
||||
<TableRow>
|
||||
<TableCell
|
||||
className="py-10 text-center text-muted-foreground"
|
||||
colSpan={6}
|
||||
>
|
||||
{t("patients.empty")}
|
||||
</td>
|
||||
</tr>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
pageRows.map((p) => (
|
||||
<tr
|
||||
className="cursor-pointer border-border/50 border-b transition-colors last:border-0 hover:bg-accent/50"
|
||||
<TableRow
|
||||
className="cursor-pointer"
|
||||
key={p.fileNumber}
|
||||
onClick={() => open(p.fileNumber)}
|
||||
onKeyDown={(event) => {
|
||||
@@ -216,7 +312,7 @@ export function PatientsView() {
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
>
|
||||
<td className="px-4 py-3 font-medium text-foreground">
|
||||
<TableCell className="ps-4 py-3 font-medium text-foreground">
|
||||
<span className="flex items-center gap-2">
|
||||
{p.name}
|
||||
<AiBadge source={p.source} />
|
||||
@@ -226,30 +322,30 @@ export function PatientsView() {
|
||||
</Badge>
|
||||
) : null}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">
|
||||
</TableCell>
|
||||
<TableCell className="py-3 text-muted-foreground">
|
||||
{p.fileNumber}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">
|
||||
</TableCell>
|
||||
<TableCell className="py-3 text-muted-foreground">
|
||||
{p.age} · {p.sex}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
</TableCell>
|
||||
<TableCell className="py-3">
|
||||
<Badge variant={statusVariant[p.status]}>
|
||||
{t(`patients.status.${p.status}`)}
|
||||
</Badge>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">
|
||||
</TableCell>
|
||||
<TableCell className="py-3 text-muted-foreground">
|
||||
{p.encounters[0]?.date ?? "—"}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">
|
||||
</TableCell>
|
||||
<TableCell className="pe-4 py-3 text-muted-foreground">
|
||||
{p.allergies.length || "—"}
|
||||
</td>
|
||||
</tr>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardFrame>
|
||||
|
||||
{!loading && !loadError ? (
|
||||
<ListPagination
|
||||
|
||||
@@ -29,6 +29,11 @@ import type { Encounter, Patient } from "@/lib/patients";
|
||||
import { draftNote, saveNote, transcribeRecording } from "@/lib/scribe";
|
||||
import { notify } from "@/lib/toast";
|
||||
import { ApiError } from "@/lib/api-client";
|
||||
import { useWalletSync } from "@/components/wallet/use-wallet-sync";
|
||||
import {
|
||||
DialogStepper,
|
||||
WalletSyncStep,
|
||||
} from "@/components/wallet/wallet-sync-step";
|
||||
|
||||
type Phase = "input" | "processing" | "review";
|
||||
type InputTab = "record" | "paste";
|
||||
@@ -76,6 +81,9 @@ export function ScribeDialog({
|
||||
const [draft, setDraft] = useState<Encounter | null>(null);
|
||||
const [veilNote, setVeilNote] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [walletStep, setWalletStep] = useState(false);
|
||||
|
||||
const sync = useWalletSync(patient.fileNumber);
|
||||
|
||||
const mediaRef = useRef<MediaRecorder | null>(null);
|
||||
const chunksRef = useRef<Blob[]>([]);
|
||||
@@ -105,6 +113,8 @@ export function ScribeDialog({
|
||||
setDraft(null);
|
||||
setVeilNote(null);
|
||||
setError(null);
|
||||
setWalletStep(false);
|
||||
sync.reset();
|
||||
chunksRef.current = [];
|
||||
blobRef.current = null;
|
||||
};
|
||||
@@ -223,7 +233,12 @@ export function ScribeDialog({
|
||||
const updated = await saveNote(patient.fileNumber, draft);
|
||||
notify.success(t("scribe.saved.title"), patient.name);
|
||||
onSaved(updated);
|
||||
handleOpenChange(false);
|
||||
if (await sync.ensureLinked()) {
|
||||
setPhase("review");
|
||||
setWalletStep(true);
|
||||
} else {
|
||||
handleOpenChange(false);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof ApiError ? err.message : t("scribe.errors.generic"),
|
||||
@@ -245,8 +260,20 @@ export function ScribeDialog({
|
||||
<DialogDescription>
|
||||
{t("scribe.subtitle", { name: patient.name })}
|
||||
</DialogDescription>
|
||||
{sync.linked && (
|
||||
<DialogStepper step={walletStep ? "wallet" : "form"} />
|
||||
)}
|
||||
</DialogHeader>
|
||||
|
||||
{walletStep ? (
|
||||
<WalletSyncStep
|
||||
onDone={() => handleOpenChange(false)}
|
||||
patientName={patient.name}
|
||||
summary={t("walletSync.summary.note")}
|
||||
sync={sync}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<DialogPanel className="min-h-0 flex-1 overflow-y-auto">
|
||||
{phase === "review" && draft ? (
|
||||
<div className="flex flex-col gap-4">
|
||||
@@ -430,6 +457,8 @@ export function ScribeDialog({
|
||||
</>
|
||||
)}
|
||||
</DialogFooter>
|
||||
</>
|
||||
)}
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
);
|
||||
|
||||
@@ -44,10 +44,19 @@ export function TransferPatientDialog({
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Re-seed the form each time the dialog opens. Adjusted during render so it
|
||||
// never paints the previous patient's provider.
|
||||
const [prevOpen, setPrevOpen] = useState(false);
|
||||
if (prevOpen !== open) {
|
||||
setPrevOpen(open);
|
||||
if (open) {
|
||||
setProviderId(patient.primaryProviderId ?? "");
|
||||
setError(null);
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setProviderId(patient.primaryProviderId ?? "");
|
||||
setError(null);
|
||||
let active = true;
|
||||
listProviders()
|
||||
.then((list) => active && setProviders(list))
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { type FormEvent, type ReactNode, useState } from "react";
|
||||
import {
|
||||
type FormEvent,
|
||||
type ReactNode,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useState,
|
||||
} from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -15,6 +21,7 @@ import {
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { parseGs1 } from "@/lib/gs1";
|
||||
import type { InventoryInput } from "@/lib/inventory";
|
||||
import { notify } from "@/lib/toast";
|
||||
|
||||
@@ -48,7 +55,11 @@ export function AddInventoryDialog({
|
||||
const [stockQuantity, setStockQuantity] = useState("0");
|
||||
const [reorderThreshold, setReorderThreshold] = useState("0");
|
||||
const [location, setLocation] = useState("");
|
||||
const [barcode, setBarcode] = useState("");
|
||||
const [expiresAt, setExpiresAt] = useState("");
|
||||
// Lot/batch parsed from a GS1 scan. No dedicated field, so it rides along in
|
||||
// notes (surfaced on the item detail).
|
||||
const [notes, setNotes] = useState("");
|
||||
|
||||
const reset = () => {
|
||||
setName("");
|
||||
@@ -58,9 +69,76 @@ export function AddInventoryDialog({
|
||||
setStockQuantity("0");
|
||||
setReorderThreshold("0");
|
||||
setLocation("");
|
||||
setBarcode("");
|
||||
setExpiresAt("");
|
||||
setNotes("");
|
||||
};
|
||||
|
||||
// A scanned medication barcode: store the code, and when it's a GS1
|
||||
// DataMatrix, auto-fill expiry (AI 17) and lot (AI 10, -> notes).
|
||||
const handleScan = useCallback(
|
||||
(raw: string) => {
|
||||
const gs1 = parseGs1(raw);
|
||||
if (gs1) {
|
||||
setBarcode(gs1.gtin ?? raw);
|
||||
if (gs1.expiry) setExpiresAt(gs1.expiry);
|
||||
if (gs1.lot) setNotes((n) => n || `Lot: ${gs1.lot}`);
|
||||
} else {
|
||||
setBarcode(raw.trim());
|
||||
}
|
||||
notify.success(
|
||||
t("inventory.dialog.scannedTitle"),
|
||||
gs1?.gtin ?? raw.trim(),
|
||||
);
|
||||
},
|
||||
[t],
|
||||
);
|
||||
|
||||
// Hardware barcode scanners are keyboard wedges: they "type" the code as a
|
||||
// fast burst of keystrokes terminated by Enter. While the dialog is open we
|
||||
// watch keydowns globally and, when a fast burst ends in Enter, treat the
|
||||
// buffer as a scan — so the pharmacist can just scan a medication without
|
||||
// first focusing any field. The timing gate (keys < 50ms apart) keeps
|
||||
// ordinary typing out of the buffer; once a burst is detected we swallow the
|
||||
// characters so they don't leak into the focused input.
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
let buffer = "";
|
||||
let lastTime = 0;
|
||||
const MAX_GAP_MS = 50;
|
||||
const MIN_LEN = 6;
|
||||
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
const now = Date.now();
|
||||
const fast = now - lastTime <= MAX_GAP_MS;
|
||||
lastTime = now;
|
||||
|
||||
if (event.key === "Enter") {
|
||||
if (fast && buffer.length >= MIN_LEN) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
handleScan(buffer);
|
||||
}
|
||||
buffer = "";
|
||||
return;
|
||||
}
|
||||
if (
|
||||
event.key.length === 1 &&
|
||||
!event.metaKey &&
|
||||
!event.ctrlKey &&
|
||||
!event.altKey
|
||||
) {
|
||||
buffer = fast ? buffer + event.key : event.key;
|
||||
if (fast && buffer.length >= 2) event.preventDefault();
|
||||
} else {
|
||||
buffer = "";
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onKeyDown, true);
|
||||
return () => window.removeEventListener("keydown", onKeyDown, true);
|
||||
}, [open, handleScan]);
|
||||
|
||||
const submit = (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
const trimmed = name.trim();
|
||||
@@ -79,7 +157,9 @@ export function AddInventoryDialog({
|
||||
stockQuantity: Number.parseInt(stockQuantity, 10) || 0,
|
||||
reorderThreshold: Number.parseInt(reorderThreshold, 10) || 0,
|
||||
location: location.trim(),
|
||||
barcode: barcode.trim() || null,
|
||||
expiresAt: expiresAt || null,
|
||||
notes: notes.trim() || null,
|
||||
});
|
||||
notify.success(t("inventory.dialog.addedTitle"), trimmed);
|
||||
reset();
|
||||
@@ -174,6 +254,27 @@ export function AddInventoryDialog({
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
|
||||
<Field label={t("inventory.dialog.barcode")}>
|
||||
<Input
|
||||
inputMode="numeric"
|
||||
onChange={(event) => setBarcode(event.target.value)}
|
||||
// A hardware scanner sends Enter after the code; parse it here
|
||||
// (instead of submitting the form) so a scan into this field is
|
||||
// handled like the global wedge burst.
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
if (barcode.trim()) handleScan(barcode);
|
||||
}
|
||||
}}
|
||||
placeholder={t("inventory.dialog.barcodePlaceholder")}
|
||||
value={barcode}
|
||||
/>
|
||||
<span className="text-muted-foreground text-xs">
|
||||
{t("inventory.dialog.scanHint")}
|
||||
</span>
|
||||
</Field>
|
||||
</DialogPanel>
|
||||
|
||||
<DialogFooter>
|
||||
|
||||
@@ -109,6 +109,10 @@ export function InventoryDetailDialog({
|
||||
label={t("inventory.dialog.expires")}
|
||||
value={item.expiresAt || "—"}
|
||||
/>
|
||||
<Row
|
||||
label={t("inventory.dialog.barcode")}
|
||||
value={item.barcode || "—"}
|
||||
/>
|
||||
{item.notes ? (
|
||||
<div className="flex flex-col gap-1 py-2">
|
||||
<span className="text-muted-foreground text-sm">
|
||||
|
||||
@@ -13,6 +13,7 @@ import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DatePicker } from "@/components/ui/date-picker";
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
@@ -29,6 +30,11 @@ import { type InventoryItem, listInventory } from "@/lib/inventory";
|
||||
import { listPatients, type Patient } from "@/lib/patients";
|
||||
import { notify } from "@/lib/toast";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useWalletSync } from "@/components/wallet/use-wallet-sync";
|
||||
import {
|
||||
DialogStepper,
|
||||
WalletSyncStep,
|
||||
} from "@/components/wallet/wallet-sync-step";
|
||||
|
||||
export type NewPrescription = {
|
||||
fileNumber: string;
|
||||
@@ -132,7 +138,7 @@ export function AddPrescriptionDialog({
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onAdd: (rx: NewPrescription) => void;
|
||||
onAdd: (rx: NewPrescription) => void | Promise<void>;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [patients, setPatients] = useState<Patient[]>([]);
|
||||
@@ -151,6 +157,19 @@ export function AddPrescriptionDialog({
|
||||
const [startDate, setStartDate] = useState("");
|
||||
const [endDate, setEndDate] = useState("");
|
||||
const [notes, setNotes] = useState("");
|
||||
const [step, setStep] = useState<"form" | "wallet">("form");
|
||||
const [walletSummary, setWalletSummary] = useState("");
|
||||
|
||||
const sync = useWalletSync(selected?.fileNumber ?? null);
|
||||
|
||||
const handleOpenChange = (o: boolean) => {
|
||||
onOpenChange(o);
|
||||
if (!o) {
|
||||
reset();
|
||||
setStep("form");
|
||||
sync.reset();
|
||||
}
|
||||
};
|
||||
|
||||
// Load patients + inventory lazily when the dialog opens (for the quick
|
||||
// searches). Inventory backs the medication combobox; it still accepts free
|
||||
@@ -202,9 +221,19 @@ export function AddPrescriptionDialog({
|
||||
.slice(0, 6);
|
||||
}, [inventory, medication]);
|
||||
|
||||
// Keep the highlighted option in range as the result lists change.
|
||||
useEffect(() => setActiveIndex(0), [query]);
|
||||
useEffect(() => setMedIndex(0), [medication]);
|
||||
// Keep the highlighted option in range as the result lists change. Adjusted
|
||||
// during render rather than in an effect: React re-runs this render before
|
||||
// committing, so the list never paints with a stale highlight.
|
||||
const [prevQuery, setPrevQuery] = useState(query);
|
||||
if (prevQuery !== query) {
|
||||
setPrevQuery(query);
|
||||
setActiveIndex(0);
|
||||
}
|
||||
const [prevMedication, setPrevMedication] = useState(medication);
|
||||
if (prevMedication !== medication) {
|
||||
setPrevMedication(medication);
|
||||
setMedIndex(0);
|
||||
}
|
||||
|
||||
const pickPatient = (p: Patient) => {
|
||||
setSelected(p);
|
||||
@@ -279,7 +308,7 @@ export function AddPrescriptionDialog({
|
||||
setNotes("");
|
||||
};
|
||||
|
||||
const submit = (event: FormEvent) => {
|
||||
const submit = async (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (!selected) {
|
||||
notify.error(
|
||||
@@ -312,7 +341,7 @@ export function AddPrescriptionDialog({
|
||||
);
|
||||
return;
|
||||
}
|
||||
onAdd({
|
||||
await onAdd({
|
||||
fileNumber: selected.fileNumber,
|
||||
name: selected.name,
|
||||
initials: selected.initials,
|
||||
@@ -328,26 +357,36 @@ export function AddPrescriptionDialog({
|
||||
t("prescriptions.dialog.addedTitle"),
|
||||
`${medication.trim()} · ${selected.name}`,
|
||||
);
|
||||
reset();
|
||||
onOpenChange(false);
|
||||
if (await sync.ensureLinked()) {
|
||||
setWalletSummary(
|
||||
t("walletSync.summary.prescription", { drug: medication.trim() }),
|
||||
);
|
||||
setStep("wallet");
|
||||
} else {
|
||||
reset();
|
||||
onOpenChange(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
onOpenChange={(o) => {
|
||||
onOpenChange(o);
|
||||
if (!o) reset();
|
||||
}}
|
||||
open={open}
|
||||
>
|
||||
<DialogPopup className="sm:max-w-md">
|
||||
<Dialog onOpenChange={handleOpenChange} open={open}>
|
||||
<DialogPopup className="flex max-h-[85dvh] flex-col sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t("prescriptions.dialog.title")}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{t("prescriptions.dialog.description")}
|
||||
</DialogDescription>
|
||||
{sync.linked && <DialogStepper step={step} />}
|
||||
</DialogHeader>
|
||||
|
||||
{step === "wallet" ? (
|
||||
<WalletSyncStep
|
||||
onDone={() => handleOpenChange(false)}
|
||||
patientName={selected?.name ?? ""}
|
||||
summary={walletSummary}
|
||||
sync={sync}
|
||||
/>
|
||||
) : (
|
||||
<form className="contents" onSubmit={submit}>
|
||||
<DialogPanel className="flex flex-col gap-4">
|
||||
<Field label={t("prescriptions.dialog.patient")}>
|
||||
@@ -550,19 +589,17 @@ export function AddPrescriptionDialog({
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Field label={t("prescriptions.dialog.startDate")}>
|
||||
<input
|
||||
className={controlClass}
|
||||
onChange={(event) => setStartDate(event.target.value)}
|
||||
type="date"
|
||||
<DatePicker
|
||||
onChange={setStartDate}
|
||||
placeholder={t("prescriptions.dialog.selectDate")}
|
||||
value={startDate}
|
||||
/>
|
||||
</Field>
|
||||
<Field label={t("prescriptions.dialog.endDate")}>
|
||||
<input
|
||||
className={controlClass}
|
||||
<DatePicker
|
||||
min={startDate || undefined}
|
||||
onChange={(event) => setEndDate(event.target.value)}
|
||||
type="date"
|
||||
onChange={setEndDate}
|
||||
placeholder={t("prescriptions.dialog.selectDate")}
|
||||
value={endDate}
|
||||
/>
|
||||
</Field>
|
||||
@@ -616,6 +653,7 @@ export function AddPrescriptionDialog({
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
)}
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogPanel,
|
||||
DialogPopup,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
|
||||
// Camera barcode/QR scanner in a dialog. Decoding uses @zxing/browser
|
||||
// (lazy-loaded so it stays out of the initial bundle), which reads 1D barcodes
|
||||
// (EAN/UPC/Code128) and 2D codes (QR, GS1 DataMatrix, PDF417) — the mix found
|
||||
// on medication packaging and patient wallet codes. Emits the decoded string
|
||||
// once, then the caller closes the dialog.
|
||||
export function BarcodeScanner({
|
||||
open,
|
||||
onOpenChange,
|
||||
onDetected,
|
||||
title,
|
||||
description,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onDetected: (value: string) => void;
|
||||
title?: string;
|
||||
description?: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const videoRef = useRef<HTMLVideoElement>(null);
|
||||
// Keep the latest onDetected without restarting the camera on every render.
|
||||
const onDetectedRef = useRef(onDetected);
|
||||
onDetectedRef.current = onDetected;
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
let stopped = false;
|
||||
let controls: { stop: () => void } | null = null;
|
||||
setError(null);
|
||||
|
||||
(async () => {
|
||||
const video = videoRef.current;
|
||||
if (!video) return;
|
||||
try {
|
||||
const { BrowserMultiFormatReader } = await import("@zxing/browser");
|
||||
const reader = new BrowserMultiFormatReader();
|
||||
controls = await reader.decodeFromConstraints(
|
||||
{ video: { facingMode: "environment" } },
|
||||
video,
|
||||
(result) => {
|
||||
if (result && !stopped) {
|
||||
stopped = true;
|
||||
controls?.stop();
|
||||
onDetectedRef.current(result.getText());
|
||||
}
|
||||
},
|
||||
);
|
||||
// The dialog may have closed while getUserMedia was resolving.
|
||||
if (stopped) controls.stop();
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof DOMException && err.name === "NotAllowedError"
|
||||
? t("scan.permissionDenied")
|
||||
: t("scan.unavailable"),
|
||||
);
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
stopped = true;
|
||||
controls?.stop();
|
||||
};
|
||||
}, [open, t]);
|
||||
|
||||
return (
|
||||
<Dialog onOpenChange={onOpenChange} open={open}>
|
||||
<DialogPopup className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title ?? t("scan.title")}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{description ?? t("scan.description")}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<DialogPanel>
|
||||
{error ? (
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
) : (
|
||||
<div className="relative aspect-video overflow-hidden rounded-2xl border bg-black">
|
||||
{/* biome-ignore lint/a11y/useMediaCaption: live camera preview */}
|
||||
<video
|
||||
className="size-full object-cover"
|
||||
muted
|
||||
playsInline
|
||||
ref={videoRef}
|
||||
/>
|
||||
<div className="pointer-events-none absolute inset-6 rounded-xl border-2 border-white/70" />
|
||||
</div>
|
||||
)}
|
||||
</DialogPanel>
|
||||
|
||||
<DialogFooter>
|
||||
<DialogClose render={<Button type="button" variant="outline" />}>
|
||||
{t("scan.cancel")}
|
||||
</DialogClose>
|
||||
</DialogFooter>
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
Trash2,
|
||||
Users,
|
||||
} from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
||||
@@ -115,12 +115,19 @@ export function EmployeeDetailDialog({
|
||||
const [confirmPw, setConfirmPw] = useState("");
|
||||
const [savingPw, setSavingPw] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
// Re-seed when a different member (or their role/specialty) is shown, and
|
||||
// always clear the password fields so they can't carry across. Adjusted
|
||||
// during render rather than in an effect, so the dialog never paints another
|
||||
// member's values — and a typed password never survives a switch.
|
||||
const seed = `${member?.id ?? ""}|${member?.role ?? ""}|${member?.specialty ?? ""}`;
|
||||
const [prevSeed, setPrevSeed] = useState(seed);
|
||||
if (prevSeed !== seed) {
|
||||
setPrevSeed(seed);
|
||||
setRole(member?.role ?? "");
|
||||
setSpecialty(member?.specialty ?? "");
|
||||
setNewPw("");
|
||||
setConfirmPw("");
|
||||
}, [member?.id, member?.role, member?.specialty]);
|
||||
}
|
||||
|
||||
const summary = rolePermissionSummary(member?.role);
|
||||
const secondary = member?.username ? `@${member.username}` : member?.email;
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
import {
|
||||
FieldLabel,
|
||||
SettingsCard,
|
||||
SettingsSection,
|
||||
SettingsFrame,
|
||||
ToggleRow,
|
||||
} from "@/components/settings/settings-parts";
|
||||
import {
|
||||
@@ -41,7 +41,7 @@ const PROVIDERS: ApiProvider[] = ["openai", "anthropic", "gemini"];
|
||||
const VEIL_LEVELS: VeilLevel[] = ["full", "names", "off"];
|
||||
|
||||
const DEFAULTS: AiConfig = {
|
||||
mode: "local",
|
||||
mode: "auto",
|
||||
provider: "anthropic",
|
||||
ollamaBaseUrl: "http://localhost:11434",
|
||||
ollamaModel: "llama3.1",
|
||||
@@ -196,15 +196,26 @@ export function AIPanel() {
|
||||
|
||||
const keyIsSet = config.apiKeySet[config.provider];
|
||||
|
||||
// Which mode-hint copy to show under the Mode select.
|
||||
const modeHintSuffix =
|
||||
config.mode === "api"
|
||||
? "Api"
|
||||
: config.mode === "local"
|
||||
? "Local"
|
||||
: config.mode === "off"
|
||||
? "Off"
|
||||
: "Auto";
|
||||
|
||||
return (
|
||||
<>
|
||||
{policy ? (
|
||||
<SettingsSection
|
||||
<SettingsFrame
|
||||
description={t("settings.ai.availability.description")}
|
||||
separated
|
||||
title={t("settings.ai.availability.title")}
|
||||
>
|
||||
{isAdmin ? (
|
||||
<div className="space-y-3">
|
||||
<>
|
||||
<ToggleRow
|
||||
checked={policy.aiEnabled}
|
||||
description={t("settings.ai.availability.enabledHint")}
|
||||
@@ -228,7 +239,7 @@ export function AIPanel() {
|
||||
/>
|
||||
) : null}
|
||||
{policyDirty ? (
|
||||
<div className="flex justify-end">
|
||||
<SettingsCard className="flex flex-row justify-end p-4">
|
||||
<Button
|
||||
disabled={savingPolicy}
|
||||
onClick={savePolicy}
|
||||
@@ -238,11 +249,11 @@ export function AIPanel() {
|
||||
? t("settings.ai.saving")
|
||||
: t("settings.ai.saveChanges")}
|
||||
</Button>
|
||||
</div>
|
||||
</SettingsCard>
|
||||
) : null}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<SettingsCard className="px-4 py-3.5">
|
||||
<SettingsCard className="p-5">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{policy.aiEnabled
|
||||
? policy.disabledForEmployees
|
||||
@@ -252,46 +263,59 @@ export function AIPanel() {
|
||||
</p>
|
||||
</SettingsCard>
|
||||
)}
|
||||
</SettingsSection>
|
||||
</SettingsFrame>
|
||||
) : null}
|
||||
|
||||
<SettingsSection
|
||||
<SettingsFrame
|
||||
description={t("settings.ai.modeDescription")}
|
||||
title={t("settings.ai.modeTitle")}
|
||||
>
|
||||
<SettingsCard className="space-y-5 p-5">
|
||||
<div className="space-y-1.5">
|
||||
<FieldLabel>{t("settings.ai.mode")}</FieldLabel>
|
||||
<Select
|
||||
onValueChange={(value) => set("mode", value as AiMode)}
|
||||
value={config.mode}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectPopup>
|
||||
<SelectItem value="api">{t("settings.ai.modeApi")}</SelectItem>
|
||||
<SelectItem value="local">
|
||||
{t("settings.ai.modeLocal")}
|
||||
</SelectItem>
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{config.mode === "api"
|
||||
? t("settings.ai.modeApiHint")
|
||||
: t("settings.ai.modeLocalHint")}
|
||||
</p>
|
||||
</div>
|
||||
<SettingsCard className="space-y-1.5 p-5">
|
||||
<FieldLabel>{t("settings.ai.mode")}</FieldLabel>
|
||||
<Select
|
||||
onValueChange={(value) => set("mode", value as AiMode)}
|
||||
value={config.mode}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectPopup>
|
||||
<SelectItem value="auto">
|
||||
{t("settings.ai.modeAuto")}
|
||||
</SelectItem>
|
||||
<SelectItem value="api">{t("settings.ai.modeApi")}</SelectItem>
|
||||
<SelectItem value="local">
|
||||
{t("settings.ai.modeLocal")}
|
||||
</SelectItem>
|
||||
<SelectItem value="off">{t("settings.ai.modeOff")}</SelectItem>
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(`settings.ai.mode${modeHintSuffix}Hint`)}
|
||||
</p>
|
||||
</SettingsCard>
|
||||
</SettingsSection>
|
||||
</SettingsFrame>
|
||||
|
||||
{config.mode === "api" ? (
|
||||
<SettingsSection
|
||||
{config.mode === "off" ? (
|
||||
<SettingsFrame
|
||||
description={t("settings.ai.offDescription")}
|
||||
title={t("settings.ai.offTitle")}
|
||||
>
|
||||
<SettingsCard className="p-5">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("settings.ai.offNote")}
|
||||
</p>
|
||||
</SettingsCard>
|
||||
</SettingsFrame>
|
||||
) : config.mode !== "local" ? (
|
||||
// API and Automatic both configure a cloud provider (Automatic falls
|
||||
// back to local Ollama when no key is set).
|
||||
<SettingsFrame
|
||||
description={t("settings.ai.providerDescription")}
|
||||
title={t("settings.ai.providerTitle")}
|
||||
>
|
||||
<SettingsCard className="space-y-5 p-5">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-1.5">
|
||||
<FieldLabel>{t("settings.ai.provider")}</FieldLabel>
|
||||
<Select
|
||||
@@ -378,14 +402,14 @@ export function AIPanel() {
|
||||
</Select>
|
||||
</div>
|
||||
</SettingsCard>
|
||||
</SettingsSection>
|
||||
</SettingsFrame>
|
||||
) : (
|
||||
<SettingsSection
|
||||
<SettingsFrame
|
||||
description={t("settings.ai.localDescription")}
|
||||
title={t("settings.ai.localTitle")}
|
||||
>
|
||||
<SettingsCard className="space-y-5 p-5">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-1.5">
|
||||
<FieldLabel>{t("settings.ai.ollamaBaseUrl")}</FieldLabel>
|
||||
<Input
|
||||
@@ -415,39 +439,41 @@ export function AIPanel() {
|
||||
: t("settings.ai.testConnection")}
|
||||
</Button>
|
||||
</SettingsCard>
|
||||
</SettingsSection>
|
||||
</SettingsFrame>
|
||||
)}
|
||||
|
||||
<SettingsSection
|
||||
description={t("settings.ai.veilDescription")}
|
||||
title={t("settings.ai.veilTitle")}
|
||||
>
|
||||
<SettingsCard className="space-y-4 p-5">
|
||||
{config.mode !== "off" ? (
|
||||
<SettingsFrame
|
||||
description={t("settings.ai.veilDescription")}
|
||||
title={t("settings.ai.veilTitle")}
|
||||
>
|
||||
<SettingsCard className="space-y-4 p-5">
|
||||
<div className="space-y-1.5">
|
||||
<FieldLabel>{t("settings.ai.veilLevel")}</FieldLabel>
|
||||
<Select
|
||||
onValueChange={(value) => set("veilLevel", value as VeilLevel)}
|
||||
value={config.veilLevel}
|
||||
>
|
||||
<SelectTrigger className="sm:w-64">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectPopup>
|
||||
{VEIL_LEVELS.map((level) => (
|
||||
<SelectItem key={level} value={level}>
|
||||
{t(`settings.ai.veilLevels.${level}`)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{config.mode === "local"
|
||||
? t("settings.ai.veilLocalNote")
|
||||
: t("settings.ai.veilApiNote")}
|
||||
</p>
|
||||
</SettingsCard>
|
||||
</SettingsSection>
|
||||
<FieldLabel>{t("settings.ai.veilLevel")}</FieldLabel>
|
||||
<Select
|
||||
onValueChange={(value) => set("veilLevel", value as VeilLevel)}
|
||||
value={config.veilLevel}
|
||||
>
|
||||
<SelectTrigger className="sm:w-64">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectPopup>
|
||||
{VEIL_LEVELS.map((level) => (
|
||||
<SelectItem key={level} value={level}>
|
||||
{t(`settings.ai.veilLevels.${level}`)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{config.mode === "local"
|
||||
? t("settings.ai.veilLocalNote")
|
||||
: t("settings.ai.veilApiNote")}
|
||||
</p>
|
||||
</SettingsCard>
|
||||
</SettingsFrame>
|
||||
) : null}
|
||||
|
||||
{dirty ? (
|
||||
<div className="sticky bottom-4 z-10">
|
||||
|
||||
@@ -176,7 +176,7 @@ export function SigningPanel() {
|
||||
description={t("settings.network.description")}
|
||||
title={t("settings.network.title")}
|
||||
>
|
||||
<SettingsCard className="flex items-center justify-between gap-4 p-5">
|
||||
<SettingsCard className="flex flex-row items-center justify-between gap-4 p-5">
|
||||
<div className="min-w-0 space-y-0.5">
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="text-sm font-medium">
|
||||
@@ -251,7 +251,7 @@ export function SigningPanel() {
|
||||
description={t("settings.signing.backupDescription")}
|
||||
title={t("settings.signing.backupTitle")}
|
||||
>
|
||||
<SettingsCard className="flex items-center justify-between gap-4 p-4">
|
||||
<SettingsCard className="flex flex-row items-center justify-between gap-4 p-4">
|
||||
<div className="space-y-0.5">
|
||||
<p className="text-sm font-medium">
|
||||
{t("settings.signing.backupLabel")}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { Info, UserPlus } from "lucide-react";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { AddStaffDialog } from "@/components/settings/add-staff-dialog";
|
||||
@@ -64,36 +64,47 @@ export function CareTeamPanel({
|
||||
const [pendingRemove, setPendingRemove] = useState<StaffMember | null>(null);
|
||||
const [removing, setRemoving] = useState(false);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const data = await apiFetch<StaffMember[]>("/api/staff");
|
||||
setMembers(data);
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof Error ? err.message : t("settings.careTeam.loadError"),
|
||||
);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
// The effect owns the fetch; `reload()` just bumps a key to re-run it. That
|
||||
// keeps every setState inside a promise callback rather than running
|
||||
// synchronously when the effect fires, and it drops the exhaustive-deps
|
||||
// suppression the old useCallback needed.
|
||||
const [reloadKey, setReloadKey] = useState(0);
|
||||
const reload = () => setReloadKey((k) => k + 1);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [load]);
|
||||
let active = true;
|
||||
apiFetch<StaffMember[]>("/api/staff")
|
||||
.then((data) => {
|
||||
if (!active) return;
|
||||
setMembers(data);
|
||||
setError(null);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (!active) return;
|
||||
setError(
|
||||
err instanceof Error ? err.message : t("settings.careTeam.loadError"),
|
||||
);
|
||||
})
|
||||
.finally(() => {
|
||||
if (active) setLoading(false);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
// `t` is intentionally omitted: re-fetching the staff list on a language
|
||||
// change would be pointless, and the message is only read on failure.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [reloadKey]);
|
||||
|
||||
// Deep-link: open a specific member (e.g. from a password-reset system card).
|
||||
const appliedDeepLink = useRef(false);
|
||||
useEffect(() => {
|
||||
if (appliedDeepLink.current || !initialMemberId || members.length === 0)
|
||||
return;
|
||||
// Resolved during render once the list arrives, so the member's dialog opens
|
||||
// on the same paint the list does.
|
||||
const [appliedDeepLink, setAppliedDeepLink] = useState(false);
|
||||
if (!appliedDeepLink && initialMemberId && members.length > 0) {
|
||||
setAppliedDeepLink(true);
|
||||
const target = members.find((m) => m.userId === initialMemberId);
|
||||
if (target) {
|
||||
setSelected(target);
|
||||
appliedDeepLink.current = true;
|
||||
}
|
||||
}, [initialMemberId, members]);
|
||||
if (target) setSelected(target);
|
||||
}
|
||||
|
||||
const myRole = members.find((m) => m.userId === session?.user?.id)?.role;
|
||||
const canManage = myRole === "owner" || myRole === "admin";
|
||||
@@ -119,22 +130,23 @@ export function CareTeamPanel({
|
||||
}),
|
||||
);
|
||||
setPendingRemove(null);
|
||||
void load();
|
||||
reload();
|
||||
};
|
||||
|
||||
return (
|
||||
<SettingsSection
|
||||
description={t("settings.careTeam.description")}
|
||||
separated
|
||||
title={t("settings.careTeam.title")}
|
||||
>
|
||||
{error && (
|
||||
<p className="rounded-2xl bg-destructive/10 px-3 py-2 text-sm text-destructive">
|
||||
{error}
|
||||
</p>
|
||||
<SettingsCard className="bg-destructive/10 p-4">
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
</SettingsCard>
|
||||
)}
|
||||
|
||||
{canManage && (
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<SettingsCard className="flex flex-row items-center justify-between gap-4 p-4">
|
||||
<p className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<Info className="size-3.5 shrink-0" />
|
||||
{t("settings.careTeam.clickHint")}
|
||||
@@ -143,10 +155,10 @@ export function CareTeamPanel({
|
||||
<UserPlus className="size-4" />
|
||||
{t("settings.careTeam.addMember")}
|
||||
</Button>
|
||||
</div>
|
||||
</SettingsCard>
|
||||
)}
|
||||
|
||||
<SettingsCard className="divide-y divide-border">
|
||||
<SettingsCard className="divide-y divide-border overflow-hidden p-0">
|
||||
{loading ? (
|
||||
<p className="p-6 text-center text-sm text-muted-foreground">
|
||||
{t("settings.careTeam.loading")}
|
||||
@@ -211,7 +223,7 @@ export function CareTeamPanel({
|
||||
|
||||
{canManage && (
|
||||
<AddStaffDialog
|
||||
onCreated={() => void load()}
|
||||
onCreated={reload}
|
||||
onOpenChange={setAdding}
|
||||
open={adding}
|
||||
/>
|
||||
@@ -225,7 +237,7 @@ export function CareTeamPanel({
|
||||
selected?.role !== "owner"
|
||||
}
|
||||
member={selected}
|
||||
onChanged={() => void load()}
|
||||
onChanged={reload}
|
||||
onOpenChange={(o) => !o && setSelected(null)}
|
||||
onRemove={(m) => {
|
||||
setSelected(null);
|
||||
|
||||
@@ -1,40 +1,130 @@
|
||||
"use client";
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { useState } from "react";
|
||||
import { createContext, useContext, useState } from "react";
|
||||
import { Check, Copy } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
import {
|
||||
Card,
|
||||
CardFrame,
|
||||
CardFrameAction,
|
||||
CardFrameDescription,
|
||||
CardFrameHeader,
|
||||
CardFrameTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { Frame, FramePanel } from "@/components/ui/frame";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export function SettingsSection({
|
||||
// Whether the enclosing frame is a COSS "Separated Panels" tray. When true,
|
||||
// SettingsCard/ToggleRow render as a FramePanel (a distinct bordered card on the
|
||||
// muted tray) instead of a fused CardFrame Card.
|
||||
const SeparatedFrameContext = createContext(false);
|
||||
|
||||
// A settings section rendered inside the COSS "frame" surface: a titled header
|
||||
// above one or more cards.
|
||||
//
|
||||
// Children are rendered as *direct* children of CardFrame on purpose. CardFrame
|
||||
// styles its cards through direct-child selectors (`*:data-[slot=card]:-m-px`,
|
||||
// the clip-path, `rounded-t/b-xl`, `shadow-none`, `before:hidden`) — it pulls
|
||||
// each card out by a pixel so it sits flush inside the frame's own border. Put
|
||||
// anything between the frame and the card, even an unstyled div, and every one
|
||||
// of those selectors stops matching: the card keeps its own border and shadow
|
||||
// and you get a box inside a box.
|
||||
//
|
||||
// So: no padding here. Body padding belongs on the Card (`<SettingsCard
|
||||
// className="p-5">`), which is where COSS puts it.
|
||||
export function SettingsFrame({
|
||||
title,
|
||||
description,
|
||||
action,
|
||||
children,
|
||||
className,
|
||||
separated = false,
|
||||
}: {
|
||||
title: string;
|
||||
description?: string;
|
||||
action?: ReactNode;
|
||||
children: ReactNode;
|
||||
className?: string;
|
||||
/**
|
||||
* COSS "Separated Panels": render a muted Frame tray whose children are
|
||||
* distinct bordered FramePanels spaced apart (the real coss.com/ui/frame
|
||||
* look), instead of the fused CardFrame surface. Leave off for a joined list.
|
||||
*/
|
||||
separated?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<section className="space-y-5">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="space-y-1">
|
||||
<h2 className="text-lg font-semibold tracking-tight">{title}</h2>
|
||||
{description ? (
|
||||
<p className="text-sm text-muted-foreground">{description}</p>
|
||||
) : null}
|
||||
if (separated) {
|
||||
return (
|
||||
<Frame className={className}>
|
||||
<div
|
||||
className="flex items-start justify-between gap-4 px-4 py-3"
|
||||
data-slot="frame-header"
|
||||
>
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<p className="text-base font-semibold">{title}</p>
|
||||
{description ? (
|
||||
<p className="text-sm text-muted-foreground">{description}</p>
|
||||
) : null}
|
||||
</div>
|
||||
{action ? <div className="shrink-0">{action}</div> : null}
|
||||
</div>
|
||||
{action ? <div className="shrink-0">{action}</div> : null}
|
||||
</div>
|
||||
<SeparatedFrameContext.Provider value={true}>
|
||||
{children}
|
||||
</SeparatedFrameContext.Provider>
|
||||
</Frame>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<CardFrame className={className}>
|
||||
<CardFrameHeader className="border-b border-border/60">
|
||||
<CardFrameTitle className="text-base">{title}</CardFrameTitle>
|
||||
{description ? (
|
||||
<CardFrameDescription>{description}</CardFrameDescription>
|
||||
) : null}
|
||||
{action ? <CardFrameAction>{action}</CardFrameAction> : null}
|
||||
</CardFrameHeader>
|
||||
{children}
|
||||
</section>
|
||||
</CardFrame>
|
||||
);
|
||||
}
|
||||
|
||||
// Back-compat wrapper: existing panels compose with SettingsSection, which
|
||||
// renders through the COSS frame surface so the whole settings page shares one
|
||||
// framed look.
|
||||
export function SettingsSection({
|
||||
title,
|
||||
description,
|
||||
action,
|
||||
children,
|
||||
separated = false,
|
||||
}: {
|
||||
title: string;
|
||||
description?: string;
|
||||
action?: ReactNode;
|
||||
children: ReactNode;
|
||||
/** See {@link SettingsFrame}'s `separated` — spaces sibling panels apart. */
|
||||
separated?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<SettingsFrame
|
||||
action={action}
|
||||
description={description}
|
||||
separated={separated}
|
||||
title={title}
|
||||
>
|
||||
{children}
|
||||
</SettingsFrame>
|
||||
);
|
||||
}
|
||||
|
||||
// A card surface used inside settings panels. Rendering a real COSS `Card` (with
|
||||
// `data-slot="card"`) keeps settings cards consistent with the rest of the app
|
||||
// and lets them pick up the frame's card treatment. `Card` is `flex flex-col`,
|
||||
// so row layouts must pass `flex-row` in their className. It carries no padding
|
||||
// of its own — pass `p-5` (the settings default) or a `divide-y` list.
|
||||
export function SettingsCard({
|
||||
className,
|
||||
children,
|
||||
@@ -42,11 +132,17 @@ export function SettingsCard({
|
||||
className?: string;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className={cn("rounded-2xl border border-border bg-card/30", className)}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
const separated = useContext(SeparatedFrameContext);
|
||||
if (separated) {
|
||||
// A distinct panel on the Frame tray. `flex flex-col` mirrors Card's default
|
||||
// layout; callers that need a row (ToggleRow) override with `flex-row`.
|
||||
return (
|
||||
<FramePanel className={cn("flex flex-col", className)}>
|
||||
{children}
|
||||
</FramePanel>
|
||||
);
|
||||
}
|
||||
return <Card className={className}>{children}</Card>;
|
||||
}
|
||||
|
||||
export function ToggleRow({
|
||||
@@ -64,7 +160,7 @@ export function ToggleRow({
|
||||
onCheckedChange?: (checked: boolean) => void;
|
||||
}) {
|
||||
return (
|
||||
<SettingsCard className="flex items-center justify-between gap-4 px-4 py-3.5">
|
||||
<SettingsCard className="flex flex-row items-center justify-between gap-4 px-4 py-3.5">
|
||||
<div className="space-y-0.5">
|
||||
<p className="text-sm font-medium">{title}</p>
|
||||
{description ? (
|
||||
|
||||
@@ -39,12 +39,18 @@ export function PatientPortalSection() {
|
||||
const origin = typeof window !== "undefined" ? window.location.origin : "";
|
||||
const portalUrl = slug ? `${origin}/portal/${slug}` : "";
|
||||
|
||||
// Drop the previous clinic's QR as soon as the slug changes, rather than
|
||||
// leaving it on screen until the new one arrives. Adjusted during render, so
|
||||
// switching clinics never shows the old clinic's pairing code.
|
||||
const [prevSlug, setPrevSlug] = useState(slug);
|
||||
if (prevSlug !== slug) {
|
||||
setPrevSlug(slug);
|
||||
setQrUri("");
|
||||
}
|
||||
|
||||
// Fetch the relay-based pairing descriptor for the QR (non-secret).
|
||||
useEffect(() => {
|
||||
if (!slug) {
|
||||
setQrUri("");
|
||||
return;
|
||||
}
|
||||
if (!slug) return;
|
||||
let active = true;
|
||||
getPortalLink(slug)
|
||||
.then((link) => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { ChevronDown, Plus } from "lucide-react";
|
||||
import { Plus, X } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
import { authClient } from "@/lib/auth-client";
|
||||
import { supportedLanguages } from "@/lib/i18n/config";
|
||||
import { persistLanguage } from "@/lib/language";
|
||||
import { SPECIALTIES, specialtyLabel } from "@/lib/staff";
|
||||
import {
|
||||
getSettings,
|
||||
saveSettings,
|
||||
@@ -60,8 +61,21 @@ const DEFAULT_PREFS: UserPreferences = {
|
||||
"notif.recordsShared": true,
|
||||
clinic: "",
|
||||
contactEmail: "",
|
||||
specialty: "",
|
||||
// Professional links stored as a JSON array string (values are boolean|string).
|
||||
links: "",
|
||||
};
|
||||
|
||||
// Parse the stored `links` preference (a JSON array string) into an array.
|
||||
function parseLinks(value: unknown): string[] {
|
||||
try {
|
||||
const parsed = JSON.parse(String(value || "[]"));
|
||||
return Array.isArray(parsed) ? parsed.map(String) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function ProfilePanel() {
|
||||
const { t, i18n } = useTranslation();
|
||||
const { data: session } = authClient.useSession();
|
||||
@@ -99,24 +113,38 @@ export function ProfilePanel() {
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Seed the display name from the session once it loads.
|
||||
useEffect(() => {
|
||||
// Seed the display name from the session once it loads. Adjusted during
|
||||
// render so the field isn't briefly empty after the session resolves. Still
|
||||
// `prev ||`, so it never clobbers something the clinician has typed.
|
||||
const [prevUserName, setPrevUserName] = useState(user?.name);
|
||||
if (prevUserName !== user?.name) {
|
||||
setPrevUserName(user?.name);
|
||||
if (user?.name) {
|
||||
setName((prev) => prev || user.name);
|
||||
setBaselineName((prev) => prev || user.name);
|
||||
}
|
||||
}, [user?.name]);
|
||||
}
|
||||
|
||||
const setPref = (key: string, value: boolean | string) =>
|
||||
setPrefs((prev) => ({ ...prev, [key]: value }));
|
||||
|
||||
const links = parseLinks(prefs.links);
|
||||
const setLinks = (next: string[]) =>
|
||||
setPref("links", JSON.stringify(next));
|
||||
|
||||
const dirty =
|
||||
name !== baselineName || JSON.stringify(prefs) !== JSON.stringify(baseline);
|
||||
|
||||
const save = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
const saved = await saveSettings(prefs);
|
||||
// Drop blank link rows before persisting.
|
||||
const cleanedLinks = links.map((l) => l.trim()).filter(Boolean);
|
||||
const toSave: UserPreferences = {
|
||||
...prefs,
|
||||
links: cleanedLinks.length ? JSON.stringify(cleanedLinks) : "",
|
||||
};
|
||||
const saved = await saveSettings(toSave);
|
||||
const trimmed = name.trim();
|
||||
if (trimmed && trimmed !== baselineName) {
|
||||
const { error } = await authClient.updateUser({ name: trimmed });
|
||||
@@ -182,13 +210,31 @@ export function ProfilePanel() {
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<FieldLabel>{t("settings.profile.specialty")}</FieldLabel>
|
||||
<button
|
||||
className="flex h-9 w-full items-center justify-between rounded-3xl bg-input/50 px-3 text-sm text-muted-foreground transition-colors hover:bg-input/70"
|
||||
type="button"
|
||||
<Select
|
||||
onValueChange={(value) => setPref("specialty", value ?? "")}
|
||||
value={String(prefs.specialty ?? "")}
|
||||
>
|
||||
{t("settings.profile.selectSpecialty")}
|
||||
<ChevronDown className="size-4" />
|
||||
</button>
|
||||
<SelectTrigger>
|
||||
<SelectValue>
|
||||
{(value: string) =>
|
||||
value ? (
|
||||
specialtyLabel(t, value)
|
||||
) : (
|
||||
<span className="text-muted-foreground">
|
||||
{t("settings.profile.selectSpecialty")}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectPopup>
|
||||
{SPECIALTIES.map((s) => (
|
||||
<SelectItem key={s} value={s}>
|
||||
{t(`settings.careTeam.specialties.${s}`)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
@@ -221,7 +267,43 @@ export function ProfilePanel() {
|
||||
{t("settings.profile.professionalLinksHint")}
|
||||
</p>
|
||||
</div>
|
||||
<Button className="rounded-lg" size="sm" variant="outline">
|
||||
{links.length > 0 ? (
|
||||
<div className="space-y-2">
|
||||
{links.map((link, index) => (
|
||||
// biome-ignore lint/suspicious/noArrayIndexKey: rows are positional
|
||||
<div className="flex items-center gap-2" key={index}>
|
||||
<Input
|
||||
inputMode="url"
|
||||
onChange={(event) =>
|
||||
setLinks(
|
||||
links.map((value, i) =>
|
||||
i === index ? event.target.value : value,
|
||||
),
|
||||
)
|
||||
}
|
||||
placeholder={t("settings.profile.linkPlaceholder")}
|
||||
value={link}
|
||||
/>
|
||||
<Button
|
||||
aria-label={t("settings.profile.removeLink")}
|
||||
onClick={() =>
|
||||
setLinks(links.filter((_, i) => i !== index))
|
||||
}
|
||||
size="icon-sm"
|
||||
variant="ghost"
|
||||
>
|
||||
<X className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
<Button
|
||||
className="rounded-lg"
|
||||
onClick={() => setLinks([...links, ""])}
|
||||
size="sm"
|
||||
variant="outline"
|
||||
>
|
||||
<Plus className="size-4" />
|
||||
{t("settings.profile.addLink")}
|
||||
</Button>
|
||||
@@ -257,64 +339,45 @@ export function ProfilePanel() {
|
||||
|
||||
<SettingsSection
|
||||
description={t("settings.profile.patientNotificationsDescription")}
|
||||
separated
|
||||
title={t("settings.profile.patientNotifications")}
|
||||
>
|
||||
<div className="space-y-3">
|
||||
{patientNotifications.map((item) => (
|
||||
<ToggleRow
|
||||
checked={Boolean(prefs[`notif.${item.titleKey}`])}
|
||||
description={t(`settings.profile.notif.${item.descKey}`)}
|
||||
key={item.titleKey}
|
||||
onCheckedChange={(checked) =>
|
||||
setPref(`notif.${item.titleKey}`, checked)
|
||||
}
|
||||
title={t(`settings.profile.notif.${item.titleKey}`)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{patientNotifications.map((item) => (
|
||||
<ToggleRow
|
||||
checked={Boolean(prefs[`notif.${item.titleKey}`])}
|
||||
description={t(`settings.profile.notif.${item.descKey}`)}
|
||||
key={item.titleKey}
|
||||
onCheckedChange={(checked) =>
|
||||
setPref(`notif.${item.titleKey}`, checked)
|
||||
}
|
||||
title={t(`settings.profile.notif.${item.titleKey}`)}
|
||||
/>
|
||||
))}
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection
|
||||
description={t("settings.profile.accountNotificationsDescription")}
|
||||
separated
|
||||
title={t("settings.profile.accountNotifications")}
|
||||
>
|
||||
<div className="space-y-3">
|
||||
{accountNotifications.map((item) => (
|
||||
<ToggleRow
|
||||
checked={Boolean(prefs[`notif.${item.titleKey}`])}
|
||||
description={t(`settings.profile.notif.${item.descKey}`)}
|
||||
key={item.titleKey}
|
||||
onCheckedChange={(checked) =>
|
||||
setPref(`notif.${item.titleKey}`, checked)
|
||||
}
|
||||
title={t(`settings.profile.notif.${item.titleKey}`)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</SettingsSection>
|
||||
|
||||
{/* Future features — intentionally not wired to persistence yet. */}
|
||||
<SettingsSection
|
||||
description={t("settings.profile.featuresDescription")}
|
||||
title={t("settings.profile.features")}
|
||||
>
|
||||
<div className="space-y-3">
|
||||
{accountNotifications.map((item) => (
|
||||
<ToggleRow
|
||||
description={t("settings.profile.notif.patientStorageDesc")}
|
||||
title={t("settings.profile.notif.patientStorage")}
|
||||
checked={Boolean(prefs[`notif.${item.titleKey}`])}
|
||||
description={t(`settings.profile.notif.${item.descKey}`)}
|
||||
key={item.titleKey}
|
||||
onCheckedChange={(checked) =>
|
||||
setPref(`notif.${item.titleKey}`, checked)
|
||||
}
|
||||
title={t(`settings.profile.notif.${item.titleKey}`)}
|
||||
/>
|
||||
<ToggleRow
|
||||
description={t("settings.profile.notif.requireSignedDesc")}
|
||||
title={t("settings.profile.notif.requireSigned")}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection
|
||||
description={t("settings.profile.dangerZoneDescription")}
|
||||
title={t("settings.profile.dangerZone")}
|
||||
>
|
||||
<SettingsCard className="flex items-center justify-between gap-4 p-4">
|
||||
<SettingsCard className="flex flex-row items-center justify-between gap-4 p-4">
|
||||
<div className="space-y-0.5">
|
||||
<p className="text-sm font-medium">
|
||||
{t("settings.profile.deleteAccount")}
|
||||
|
||||
@@ -31,8 +31,7 @@ export function DashboardSidebar() {
|
||||
const { t, i18n } = useTranslation();
|
||||
// Anchor the sidebar to the right for RTL locales (Arabic) so the whole shell
|
||||
// mirrors instead of leaving the fixed sidebar pinned physically left.
|
||||
const isRtl = dirFor(i18n.language) === "rtl";
|
||||
const side = isRtl ? "right" : "left";
|
||||
const side = dirFor(i18n.language) === "rtl" ? "right" : "left";
|
||||
const role = useActiveRole();
|
||||
const { allowed: aiAllowed } = useAiAccess();
|
||||
const isCollapsed = state === "collapsed";
|
||||
@@ -65,11 +64,7 @@ export function DashboardSidebar() {
|
||||
"flex md:pt-3.5",
|
||||
isCollapsed
|
||||
? "flex-row items-center justify-between gap-y-4 md:flex-col md:items-start md:justify-start"
|
||||
: "flex-row items-center justify-between",
|
||||
// RTL (Arabic): stack the logo and the toggle/bell controls into a
|
||||
// right-aligned column so the collapse arrow sits ABOVE the nav icons
|
||||
// instead of being pinned to the opposite (left) edge.
|
||||
isRtl && !isCollapsed && "flex-col items-end justify-start gap-y-3"
|
||||
: "flex-row items-center justify-between"
|
||||
)}
|
||||
>
|
||||
<Tooltip>
|
||||
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
MenuSeparator,
|
||||
MenuTrigger,
|
||||
} from "@/components/ui/menu";
|
||||
import { dirFor } from "@/lib/i18n/config";
|
||||
import { markNotificationRead, notificationHref } from "@/lib/notifications";
|
||||
import { useNotifications } from "@/lib/use-notifications";
|
||||
|
||||
@@ -31,11 +30,9 @@ function relativeTime(iso: string): string {
|
||||
}
|
||||
|
||||
export function NotificationsPopover() {
|
||||
const { t, i18n } = useTranslation();
|
||||
const { t } = useTranslation();
|
||||
const router = useRouter();
|
||||
const { items, unread, markAllRead } = useNotifications();
|
||||
// Open toward the content side; flips to the left under RTL.
|
||||
const popupSide = dirFor(i18n.language) === "rtl" ? "left" : "right";
|
||||
|
||||
return (
|
||||
<Menu
|
||||
@@ -61,7 +58,7 @@ export function NotificationsPopover() {
|
||||
</span>
|
||||
)}
|
||||
</MenuTrigger>
|
||||
<MenuPopup side={popupSide} className="my-6 w-80">
|
||||
<MenuPopup side="right" className="my-6 w-80">
|
||||
<MenuGroup>
|
||||
<MenuGroupLabel>{t("nav.notifications")}</MenuGroupLabel>
|
||||
</MenuGroup>
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
Building2,
|
||||
Check,
|
||||
ChevronsUpDown,
|
||||
Languages,
|
||||
LogOut,
|
||||
Moon,
|
||||
Plus,
|
||||
@@ -49,6 +50,8 @@ import {
|
||||
useSidebar,
|
||||
} from "@/components/ui/sidebar";
|
||||
import { authClient } from "@/lib/auth-client";
|
||||
import { supportedLanguages } from "@/lib/i18n/config";
|
||||
import { persistLanguage } from "@/lib/language";
|
||||
import { useActiveRole } from "@/lib/roles";
|
||||
import { notify } from "@/lib/toast";
|
||||
|
||||
@@ -82,7 +85,13 @@ function GitHubIcon({ className }: { className?: string }) {
|
||||
// shortcut hint (below Theme) and a clinic switcher submenu (below that) whose
|
||||
// popup reveals the active clinic's details on hover.
|
||||
export function NavUser() {
|
||||
const { t } = useTranslation();
|
||||
const { t, i18n } = useTranslation();
|
||||
const activeLang = i18n.resolvedLanguage ?? i18n.language;
|
||||
const changeLanguage = (lng: string) => {
|
||||
if (lng === activeLang) return;
|
||||
void i18n.changeLanguage(lng);
|
||||
void persistLanguage(lng);
|
||||
};
|
||||
const { isMobile, state } = useSidebar();
|
||||
const isCollapsed = state === "collapsed";
|
||||
const router = useRouter();
|
||||
@@ -197,6 +206,29 @@ export function NavUser() {
|
||||
</MenuShortcut>
|
||||
</MenuItem>
|
||||
|
||||
{/* Language: quick switch (also available in Settings). Applies
|
||||
immediately and roams via the backend preferences. */}
|
||||
<MenuSub>
|
||||
<MenuSubTrigger>
|
||||
<Languages />
|
||||
<span className="truncate">{t("userMenu.language")}</span>
|
||||
</MenuSubTrigger>
|
||||
<MenuSubPopup className="min-w-44" sideOffset={8}>
|
||||
{supportedLanguages.map((lng) => (
|
||||
<MenuItem
|
||||
className="gap-2"
|
||||
key={lng}
|
||||
onClick={() => changeLanguage(lng)}
|
||||
>
|
||||
<span className="flex-1 truncate">
|
||||
{t(`settings.profile.language.${lng}`)}
|
||||
</span>
|
||||
{lng === activeLang && <Check className="size-4" />}
|
||||
</MenuItem>
|
||||
))}
|
||||
</MenuSubPopup>
|
||||
</MenuSub>
|
||||
|
||||
{/* Command palette: hint + shortcut, sits below Theme. */}
|
||||
<MenuItem onClick={openCommand}>
|
||||
<Search />
|
||||
|
||||
@@ -103,18 +103,26 @@ function AddTaskDialog({
|
||||
const [priority, setPriority] = useState<Priority>("medium");
|
||||
const [status, setStatus] = useState<TaskStatus>(initialStatus);
|
||||
|
||||
// Re-seed the column when the dialog is opened from a specific column, and
|
||||
// load the clinic's providers so a task can be assigned to a specific person.
|
||||
// Re-seed the column when the dialog is opened from a specific column.
|
||||
// Adjusted during render rather than in an effect, so the select never paints
|
||||
// with the previous column's value.
|
||||
const [prevSeed, setPrevSeed] = useState<string | null>(null);
|
||||
const seed = open ? initialStatus : null;
|
||||
if (prevSeed !== seed) {
|
||||
setPrevSeed(seed);
|
||||
if (seed) setStatus(seed);
|
||||
}
|
||||
|
||||
// Load the clinic's providers so a task can be assigned to a specific person.
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setStatus(initialStatus);
|
||||
listProviders()
|
||||
.then((list) => {
|
||||
setProviders(list);
|
||||
setProviderId((id) => id || (list[0]?.userId ?? ""));
|
||||
})
|
||||
.catch(() => setProviders([]));
|
||||
}, [open, initialStatus]);
|
||||
}, [open]);
|
||||
|
||||
const reset = () => {
|
||||
setTitle("");
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
"use client";
|
||||
|
||||
import { Checkbox as CheckboxPrimitive } from "@base-ui/react/checkbox";
|
||||
import type React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export function Checkbox({
|
||||
className,
|
||||
...props
|
||||
}: CheckboxPrimitive.Root.Props): React.ReactElement {
|
||||
return (
|
||||
<CheckboxPrimitive.Root
|
||||
className={cn(
|
||||
"relative inline-flex size-4.5 shrink-0 items-center justify-center rounded-[.25rem] border border-input bg-background not-dark:bg-clip-padding shadow-xs/5 outline-none ring-ring transition-shadow before:pointer-events-none before:absolute before:inset-0 before:rounded-[3px] not-data-disabled:not-data-checked:not-aria-invalid:before:shadow-[0_1px_--theme(--color-black/4%)] focus-visible:ring-2 focus-visible:ring-offset-1 focus-visible:ring-offset-background aria-invalid:border-destructive/36 focus-visible:aria-invalid:border-destructive/64 focus-visible:aria-invalid:ring-destructive/48 data-disabled:cursor-not-allowed data-disabled:opacity-64 sm:size-4 dark:not-data-checked:bg-input/32 dark:aria-invalid:ring-destructive/24 dark:not-data-disabled:not-data-checked:not-aria-invalid:before:shadow-[0_-1px_--theme(--color-white/6%)] [[data-disabled],[data-checked],[aria-invalid]]:shadow-none",
|
||||
className,
|
||||
)}
|
||||
data-slot="checkbox"
|
||||
{...props}
|
||||
>
|
||||
<CheckboxPrimitive.Indicator
|
||||
className="absolute -inset-px flex items-center justify-center rounded-[.25rem] text-primary-foreground data-unchecked:hidden data-checked:bg-primary data-indeterminate:text-foreground"
|
||||
data-slot="checkbox-indicator"
|
||||
render={(
|
||||
props: React.ComponentProps<"span">,
|
||||
state: CheckboxPrimitive.Indicator.State,
|
||||
) => (
|
||||
<span {...props}>
|
||||
{state.indeterminate ? (
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
className="size-3.5 sm:size-3"
|
||||
fill="none"
|
||||
height="24"
|
||||
stroke="currentColor"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="3"
|
||||
viewBox="0 0 24 24"
|
||||
width="24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path d="M5.252 12h13.496" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
className="size-3.5 sm:size-3"
|
||||
fill="none"
|
||||
height="24"
|
||||
stroke="currentColor"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="3"
|
||||
viewBox="0 0 24 24"
|
||||
width="24"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path d="M5.252 12.7 10.2 18.63 18.748 5.37" />
|
||||
</svg>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
/>
|
||||
</CheckboxPrimitive.Root>
|
||||
);
|
||||
}
|
||||
|
||||
export { CheckboxPrimitive };
|
||||
@@ -0,0 +1,103 @@
|
||||
"use client";
|
||||
|
||||
import { CalendarIcon } from "lucide-react";
|
||||
import type { Matcher } from "react-day-picker";
|
||||
import { useState } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Calendar } from "@/components/ui/calendar";
|
||||
import {
|
||||
Popover,
|
||||
PopoverPopup,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
// Parse a `YYYY-MM-DD` string as a LOCAL date. `new Date("YYYY-MM-DD")` parses
|
||||
// as UTC and can shift the day across timezones, so build it from parts.
|
||||
function parseISODate(value?: string): Date | undefined {
|
||||
if (!value) return undefined;
|
||||
const [y, m, d] = value.split("-").map(Number);
|
||||
if (!y || !m || !d) return undefined;
|
||||
return new Date(y, m - 1, d);
|
||||
}
|
||||
|
||||
function toISODate(date: Date): string {
|
||||
const y = date.getFullYear();
|
||||
const m = String(date.getMonth() + 1).padStart(2, "0");
|
||||
const d = String(date.getDate()).padStart(2, "0");
|
||||
return `${y}-${m}-${d}`;
|
||||
}
|
||||
|
||||
export interface DatePickerProps {
|
||||
/** Selected date as `YYYY-MM-DD` (matches native date-input semantics). */
|
||||
value?: string;
|
||||
onChange: (value: string) => void;
|
||||
/** Earliest selectable date, `YYYY-MM-DD`. */
|
||||
min?: string;
|
||||
/** Latest selectable date, `YYYY-MM-DD`. */
|
||||
max?: string;
|
||||
placeholder?: string;
|
||||
id?: string;
|
||||
className?: string;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
// A COSS date picker: an outline Button trigger opening a Popover with the COSS
|
||||
// Calendar. Drop-in replacement for `<input type="date">`, keeping the same
|
||||
// string value shape so callers don't change their state handling.
|
||||
export function DatePicker({
|
||||
value,
|
||||
onChange,
|
||||
min,
|
||||
max,
|
||||
placeholder,
|
||||
id,
|
||||
className,
|
||||
disabled,
|
||||
}: DatePickerProps): React.ReactElement {
|
||||
const [open, setOpen] = useState(false);
|
||||
const selected = parseISODate(value);
|
||||
const minDate = parseISODate(min);
|
||||
const maxDate = parseISODate(max);
|
||||
|
||||
const disabledMatchers: Matcher[] = [
|
||||
...(minDate ? [{ before: minDate }] : []),
|
||||
...(maxDate ? [{ after: maxDate }] : []),
|
||||
];
|
||||
|
||||
return (
|
||||
<Popover onOpenChange={setOpen} open={open}>
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<Button
|
||||
className={cn(
|
||||
"w-full justify-between font-normal",
|
||||
!selected && "text-muted-foreground",
|
||||
className,
|
||||
)}
|
||||
disabled={disabled}
|
||||
id={id}
|
||||
variant="outline"
|
||||
/>
|
||||
}
|
||||
>
|
||||
{selected ? selected.toLocaleDateString() : (placeholder ?? "")}
|
||||
<CalendarIcon className="opacity-80" />
|
||||
</PopoverTrigger>
|
||||
<PopoverPopup align="start" className="w-auto">
|
||||
<Calendar
|
||||
autoFocus
|
||||
defaultMonth={selected ?? minDate}
|
||||
disabled={disabledMatchers.length ? disabledMatchers : undefined}
|
||||
mode="single"
|
||||
onSelect={(date?: Date) => {
|
||||
onChange(date ? toISODate(date) : "");
|
||||
if (date) setOpen(false);
|
||||
}}
|
||||
selected={selected}
|
||||
/>
|
||||
</PopoverPopup>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import type React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
// COSS "Frame" primitive (coss.com/ui/docs/components/frame). A Frame is a muted
|
||||
// tray that holds one or more FramePanels; multiple panels are "Separated
|
||||
// Panels" — spaced apart with `mt-1` by default (via the adjacent-sibling
|
||||
// selector below), each a self-contained bordered card. This is the opposite of
|
||||
// `CardFrame` in card.tsx, which fuses its cards into one flush surface.
|
||||
|
||||
export function Frame({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">): React.ReactElement {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"relative flex flex-col rounded-2xl bg-muted/72 p-1",
|
||||
"*:[[data-slot=frame-panel]+[data-slot=frame-panel]]:mt-1",
|
||||
className,
|
||||
)}
|
||||
data-slot="frame"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function FramePanel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">): React.ReactElement {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"relative rounded-xl border bg-background bg-clip-padding p-5 shadow-xs/5 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-xl)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",
|
||||
className,
|
||||
)}
|
||||
data-slot="frame-panel"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function FrameHeader({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">): React.ReactElement {
|
||||
return (
|
||||
<div
|
||||
className={cn("flex flex-col px-5 py-4", className)}
|
||||
data-slot="frame-header"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function FrameTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">): React.ReactElement {
|
||||
return (
|
||||
<div
|
||||
className={cn("font-semibold text-sm", className)}
|
||||
data-slot="frame-title"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function FrameDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">): React.ReactElement {
|
||||
return (
|
||||
<div
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
data-slot="frame-description"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function FrameFooter({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">): React.ReactElement {
|
||||
return (
|
||||
<div
|
||||
className={cn("px-5 py-4", className)}
|
||||
data-slot="frame-footer"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -299,8 +299,7 @@ export function SidebarTrigger({
|
||||
variant="ghost"
|
||||
{...props}
|
||||
>
|
||||
{/* Mirror the panel arrow under RTL so it points toward the sidebar edge. */}
|
||||
<PanelLeftIcon className="rtl:rotate-180" />
|
||||
<PanelLeftIcon />
|
||||
<span className="sr-only">Toggle Sidebar</span>
|
||||
</Button>
|
||||
);
|
||||
@@ -597,7 +596,7 @@ export function SidebarMenuAction({
|
||||
}): React.ReactElement {
|
||||
const defaultProps = {
|
||||
className: cn(
|
||||
"absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-lg p-0 text-sidebar-foreground outline-hidden ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",
|
||||
"absolute top-1.5 end-1 flex aspect-square w-5 items-center justify-center rounded-lg p-0 text-sidebar-foreground outline-hidden ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg:not([class*='size-'])]:size-4 [&>svg]:shrink-0",
|
||||
// Increases the hit area of the button on mobile.
|
||||
"after:absolute after:-inset-2 md:after:hidden",
|
||||
"peer-data-[size=sm]/menu-button:top-1",
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
"use client";
|
||||
|
||||
import { CheckIcon, LoaderCircleIcon } from "lucide-react";
|
||||
import { Slot } from "radix-ui";
|
||||
import * as React from "react";
|
||||
import { createContext, useContext } from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
// Types
|
||||
type StepperContextValue = {
|
||||
activeStep: number;
|
||||
setActiveStep: (step: number) => void;
|
||||
orientation: "horizontal" | "vertical";
|
||||
};
|
||||
|
||||
type StepItemContextValue = {
|
||||
step: number;
|
||||
state: StepState;
|
||||
isDisabled: boolean;
|
||||
isLoading: boolean;
|
||||
};
|
||||
|
||||
type StepState = "active" | "completed" | "inactive" | "loading";
|
||||
|
||||
// Contexts
|
||||
const StepperContext = createContext<StepperContextValue | undefined>(
|
||||
undefined,
|
||||
);
|
||||
const StepItemContext = createContext<StepItemContextValue | undefined>(
|
||||
undefined,
|
||||
);
|
||||
|
||||
const useStepper = () => {
|
||||
const context = useContext(StepperContext);
|
||||
if (!context) {
|
||||
throw new Error("useStepper must be used within a Stepper");
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
||||
const useStepItem = () => {
|
||||
const context = useContext(StepItemContext);
|
||||
if (!context) {
|
||||
throw new Error("useStepItem must be used within a StepperItem");
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
||||
// Components
|
||||
interface StepperProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
defaultValue?: number;
|
||||
value?: number;
|
||||
onValueChange?: (value: number) => void;
|
||||
orientation?: "horizontal" | "vertical";
|
||||
}
|
||||
|
||||
function Stepper({
|
||||
defaultValue = 0,
|
||||
value,
|
||||
onValueChange,
|
||||
orientation = "horizontal",
|
||||
className,
|
||||
...props
|
||||
}: StepperProps) {
|
||||
const [activeStep, setInternalStep] = React.useState(defaultValue);
|
||||
|
||||
const setActiveStep = React.useCallback(
|
||||
(step: number) => {
|
||||
if (value === undefined) {
|
||||
setInternalStep(step);
|
||||
}
|
||||
onValueChange?.(step);
|
||||
},
|
||||
[value, onValueChange],
|
||||
);
|
||||
|
||||
const currentStep = value ?? activeStep;
|
||||
|
||||
return (
|
||||
<StepperContext.Provider
|
||||
value={{
|
||||
activeStep: currentStep,
|
||||
orientation,
|
||||
setActiveStep,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"group/stepper inline-flex data-[orientation=horizontal]:w-full data-[orientation=horizontal]:flex-row data-[orientation=vertical]:flex-col",
|
||||
className,
|
||||
)}
|
||||
data-orientation={orientation}
|
||||
data-slot="stepper"
|
||||
{...props}
|
||||
/>
|
||||
</StepperContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
// StepperItem
|
||||
interface StepperItemProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
step: number;
|
||||
completed?: boolean;
|
||||
disabled?: boolean;
|
||||
loading?: boolean;
|
||||
}
|
||||
|
||||
function StepperItem({
|
||||
step,
|
||||
completed = false,
|
||||
disabled = false,
|
||||
loading = false,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: StepperItemProps) {
|
||||
const { activeStep } = useStepper();
|
||||
|
||||
const state: StepState =
|
||||
completed || step < activeStep
|
||||
? "completed"
|
||||
: activeStep === step
|
||||
? "active"
|
||||
: "inactive";
|
||||
|
||||
const isLoading = loading && step === activeStep;
|
||||
|
||||
return (
|
||||
<StepItemContext.Provider
|
||||
value={{ isDisabled: disabled, isLoading, state, step }}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"group/step flex items-center group-data-[orientation=horizontal]/stepper:flex-row group-data-[orientation=vertical]/stepper:flex-col",
|
||||
className,
|
||||
)}
|
||||
data-slot="stepper-item"
|
||||
data-state={state}
|
||||
{...(isLoading ? { "data-loading": true } : {})}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</StepItemContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
// StepperTrigger
|
||||
interface StepperTriggerProps
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
asChild?: boolean;
|
||||
}
|
||||
|
||||
function StepperTrigger({
|
||||
asChild = false,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: StepperTriggerProps) {
|
||||
const { setActiveStep } = useStepper();
|
||||
const { step, isDisabled } = useStepItem();
|
||||
|
||||
if (asChild) {
|
||||
const Comp = asChild ? Slot.Root : "span";
|
||||
return (
|
||||
<Comp className={className} data-slot="stepper-trigger">
|
||||
{children}
|
||||
</Comp>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
className={cn(
|
||||
"inline-flex items-center gap-3 rounded-full outline-none focus-visible:z-10 focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50",
|
||||
className,
|
||||
)}
|
||||
data-slot="stepper-trigger"
|
||||
disabled={isDisabled}
|
||||
onClick={() => setActiveStep(step)}
|
||||
type="button"
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
// StepperIndicator
|
||||
interface StepperIndicatorProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
asChild?: boolean;
|
||||
}
|
||||
|
||||
function StepperIndicator({
|
||||
asChild = false,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: StepperIndicatorProps) {
|
||||
const { state, step, isLoading } = useStepItem();
|
||||
|
||||
return (
|
||||
<span
|
||||
className={cn(
|
||||
"relative flex size-6 shrink-0 items-center justify-center rounded-full bg-muted font-medium text-muted-foreground text-xs data-[state=active]:bg-primary data-[state=completed]:bg-primary data-[state=active]:text-primary-foreground data-[state=completed]:text-primary-foreground",
|
||||
className,
|
||||
)}
|
||||
data-slot="stepper-indicator"
|
||||
data-state={state}
|
||||
{...props}
|
||||
>
|
||||
{asChild ? (
|
||||
children
|
||||
) : (
|
||||
<>
|
||||
<span className="transition-all group-data-[state=completed]/step:scale-0 group-data-loading/step:scale-0 group-data-[state=completed]/step:opacity-0 group-data-loading/step:opacity-0 group-data-loading/step:transition-none">
|
||||
{step}
|
||||
</span>
|
||||
<CheckIcon
|
||||
aria-hidden="true"
|
||||
className="absolute scale-0 opacity-0 transition-all group-data-[state=completed]/step:scale-100 group-data-[state=completed]/step:opacity-100"
|
||||
size={16}
|
||||
/>
|
||||
{isLoading && (
|
||||
<span className="absolute transition-all">
|
||||
<LoaderCircleIcon
|
||||
aria-hidden="true"
|
||||
className="animate-spin"
|
||||
size={14}
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
// StepperTitle
|
||||
function StepperTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLHeadingElement>) {
|
||||
return (
|
||||
<h3
|
||||
className={cn("font-medium text-sm", className)}
|
||||
data-slot="stepper-title"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// StepperDescription
|
||||
function StepperDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLParagraphElement>) {
|
||||
return (
|
||||
<p
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
data-slot="stepper-description"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// StepperSeparator
|
||||
function StepperSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.HTMLAttributes<HTMLDivElement>) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"m-0.5 bg-muted group-data-[orientation=horizontal]/stepper:h-0.5 group-data-[orientation=vertical]/stepper:h-12 group-data-[orientation=horizontal]/stepper:w-full group-data-[orientation=vertical]/stepper:w-0.5 group-data-[orientation=horizontal]/stepper:flex-1 group-data-[state=completed]/step:bg-primary",
|
||||
className,
|
||||
)}
|
||||
data-slot="stepper-separator"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
Stepper,
|
||||
StepperDescription,
|
||||
StepperIndicator,
|
||||
StepperItem,
|
||||
StepperSeparator,
|
||||
StepperTitle,
|
||||
StepperTrigger,
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user