# gnostic UI
> Build fast business websites with shadcn UI components and blocks for Astro. Install editable source and bring your own brand palette.
# Shadcn components. Built for Astro.
Source: https://ui.gnosticai.com/
Build fast business websites with polished Astro components and complete page
blocks. Bring your content and brand palette. Keep the source.
## Browse the library
- [Astro UI components](/components): buttons, forms, dialogs, navigation, and more.
- [Astro page blocks](/blocks): heroes, services, reviews, contact sections, and footers.
- [Background patterns](/patterns): dots, grids, and glow effects that use your theme colors.
- [Astro themes](/themes): one preset for colors, fonts, radius, and component styles.
- [Component examples](/examples/overview): see the parts used together.
## Start at the scale you need
Choose a [component](/components), compose a [page block](/blocks), and add a
[background pattern](/patterns). The homepage uses simple form, feature section,
and dot pattern sketches that follow the selected preset in light and dark mode.
Its hero and floating call to action use the shared [CTA button](/components/cta-button).
## Built for websites
A business website does not need to be a React app. Gnostic uses Astro markup,
Tailwind CSS, and small browser scripts where interaction needs them. Install
editable source through the shadcn registry and use Astro props and slots to
compose your pages. Read the [project credits](/docs/credits) for the shadcn,
Fulldev, and Coss foundations.
Follow the [local business website guide](/docs/astro-business-websites) to plan
service pages, choose blocks, and prepare page content for search. Astro serves
HTML; your site still needs useful content, accurate metadata, and internal links.
## Bring your own brand palette
Use the [theme generator](/themes) to choose a complete preset. Preview the
palette, font, radius, and component styles before installation. Read the
[theming guide](/docs/theming) for the supported options.
## Start building
Add the Gnostic registry to your Astro project:
```sh
bunx --bun shadcn@latest registry add "@gnostic=https://ui.gnosticai.com/r/{name}.json"
```
The homepage shows this command in a centered floating section with a copy button.
1. Follow the [Astro installation guide](/docs/installation).
2. Choose your design in the [theme generator](/themes).
3. Add [components](/components) and [blocks](/blocks) through the shadcn CLI.
Inspect the examples and source before you install. Contact blocks supply the
interface; connect form submissions to your chosen backend. The reusable
components, blocks, and patterns are available now.
---
# website Blocks for Astro
Source: https://ui.gnosticai.com/blocks
Choose a block from the content you need to present: an introduction, a service offer, a reading section, or site navigation. Each layout has a descriptive heading, an Astro source example, and its own install command. Use the source for the exact layout because its props can differ from other variants.
## Build a local business website
Follow the [local business website guide](/docs/astro-business-websites) to plan service pages and connect your content to the right blocks. Start with a [hero](/blocks/hero), [services](/blocks/services), and [contact section](/blocks/contact).
## Keep sections reusable
Load collections and route data in your page or template, then pass only the required content to the block. Use local image imports when a prop expects Astro ImageMetadata. Replace sample links and labels with content that describes the actual site.
## Check the complete page
Review heading order, spacing between sections, and image crops at narrow and wide widths. A block can fit on its own while the complete page still has repeated headings or conflicting actions. Use the shared theme tokens across sections and test both light and dark modes. See [Templates](/templates) for full-page composition and [Credits](/docs/credits) for the project sources.
Blocks are grouped by function. Templates compose these same blocks with one
complete preset. For example, Gnotch selects Graphite and Portfolio selects Glow.
Install a block on its own to use it with your project preset.
---
# Article Blocks for Astro
Source: https://ui.gnosticai.com/blocks/article
## Image header
Lead with an image, then keep the author details close to the article title.
```astro
---
import Article1Block from "@/components/blocks/article/article-1.astro"
import { agentAvatars } from "@/lib/agent-avatars"
import placeholderImage from "@/assets/placeholder.webp"
---
Start by checking the tasks that remain open. A task can be unfinished
because the work is large, a question is unanswered, or the next step has no
owner. Record the reason before changing the date.
Ask the team to choose a small number of next actions. Give each action an
owner and write down the information that person needs. Keep new ideas in a
separate list until the current work has a clear direction.
Finish by reading the decisions aloud. A teammate who missed the discussion
should be able to use the notes without asking the same questions again.
Review those notes at the start of the next meeting.
```
```sh
bunx --bun shadcn@latest add @gnostic/article-1
```
## Centered header
Center the title and author details before the reading column.
```astro
---
import Article2Block from "@/components/blocks/article/article-2.astro"
import { agentAvatars } from "@/lib/agent-avatars"
import placeholderImage from "@/assets/placeholder.webp"
---
Start an issue by collecting questions from readers. Group the questions by
topic and choose one that the next story can answer clearly. Leave the
remaining ideas in the editorial list.
Prepare a brief with the reader question, the planned sources, and the
checks the draft will need. Give the writer a date for the first review and
explain which details are still uncertain.
Read the draft for meaning before changing individual sentences. Check each
claim against its source and make sure the ending gives the reader a useful
next step. Keep the review notes with the issue.
```
```sh
bunx --bun shadcn@latest add @gnostic/article-2
```
## Editorial article
Use this section for a case study or journal entry.
```astro
---
import Section from "@/components/blocks/content/content-agency-article.astro"
const section = {
label: "Original concept project",
title: "Rook & Stone",
description:
"A quiet identity and project archive for a residential architecture practice.",
image: {
src: "/media/foldline/rook-stone.webp",
alt: "Limestone courtyard house with an olive tree and reflecting pool",
},
metadata: [
{
label: "Client concept",
value: "Rook & Stone",
},
{
label: "Scope",
value: "Brand strategy, Studio website",
},
{
label: "Year",
value: "2026",
},
],
sections: [
{
title: "The challenge",
description:
"Rook & Stone is a fictional residential practice with a patient approach to materials and light. Its concept brief called for an identity that could feel precise without becoming cold, and a website that could explain a home without turning it into a list of features.",
},
{
title: "The approach",
description:
"We paired a restrained wordmark with warm photography and short project notes. The archive starts with a view of each house, then moves through its setting, plan, and material choices. A small set of page patterns keeps new case studies easy to publish.",
},
{
title: "The outcome",
description:
"The concept brings the practice’s point of view into focus. Visitors can browse the work, understand how the team thinks, and start a relevant conversation. This is an original demonstration project for the Foldline sample brand.",
},
],
back: {
label: "All concept projects",
href: "https://example.com/projects",
},
}
---
```
```sh
bunx --bun shadcn@latest add @gnostic/content-agency-article
```
See [serif accent font setup](/docs/installation#serif-accent-fonts-for-editorial-blocks) when installing this section.
## Choose a article layout
Choose an article layout for one long-form page. Keep the title specific and use the description to set the scope. Author and date details should describe the actual publication, not the demo content.
## Pass content from Astro
Pass the heading, author object, and image required by the chosen block. Place the article body in the supported content slot. The template owns collection queries and the route; the reusable block only receives the resulting content.
## Responsive layout and images
Check line length, long headings, code, and tables on small screens. Supply image dimensions through the expected Astro image type and use a crop that still makes sense beside the title. A decorative lead image can have empty alt text; an informative image needs an accurate description.
## Compose the next section
Use [Articles](/blocks/articles) for a listing, [Doc](/blocks/doc) for a reference page, and [Typeset](/docs/theming#text-and-headings) for prose styles.
---
# Articles Blocks for Astro
Source: https://ui.gnosticai.com/blocks/articles
## Featured grid
Give one story more space while keeping related stories in the same collection.
```astro
---
import Articles1Block from "@/components/blocks/articles/articles-1.astro"
import { agentAvatars } from "@/lib/agent-avatars"
import placeholderImage from "@/assets/placeholder.webp"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/articles-1
```
## Featured sidebar
Place the lead story beside a smaller set of related articles.
```astro
---
import Articles2Block from "@/components/blocks/articles/articles-2.astro"
import { agentAvatars } from "@/lib/agent-avatars"
import placeholderImage from "@/assets/placeholder.webp"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/articles-2
```
## Rows
Use rows when readers need to compare several article summaries.
```astro
---
import Articles3Block from "@/components/blocks/articles/articles-3.astro"
import { agentAvatars } from "@/lib/agent-avatars"
import placeholderImage from "@/assets/placeholder.webp"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/articles-3
```
## Text grid
Use text cards when the titles and summaries carry the collection.
```astro
---
import Articles4Block from "@/components/blocks/articles/articles-4.astro"
import { agentAvatars } from "@/lib/agent-avatars"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/articles-4
```
## Editorial blog
Use this section for the blog part of a studio site.
```astro
---
import Section from "@/components/blocks/blog/blog-agency.astro"
const section = {
label: "Field notes",
title: "A closer",
accent: "look",
articles: [
{
title: "A project is more than a gallery",
description:
"Five useful details that help people understand a space, beyond the finished photographs.",
href: "https://example.com/blogs/a-project-is-more-than-a-gallery",
date: "2026-09-18",
image: {
src: "/media/foldline/rook-stone.webp",
alt: "Light and shadow in a limestone courtyard",
},
},
{
title: "A material-led identity",
description:
"How texture, proportion, and a limited palette can give a studio a clear visual voice.",
href: "https://example.com/blogs/a-material-led-identity",
date: "2026-08-27",
image: {
src: "/media/foldline/material-study.svg",
alt: "Isometric study of stone, timber, and paper samples",
},
},
{
title: "Photography with room to breathe",
description:
"A practical way to sequence images so that a visitor can move through the work.",
href: "https://example.com/blogs/photography-with-room-to-breathe",
date: "2026-07-09",
image: {
src: "/media/foldline/morrow-rooms.webp",
alt: "Soft daylight falling across a guesthouse lounge",
},
},
{
title: "The case for a small website",
description:
"Why a focused set of pages can do more for a practice than a crowded digital archive.",
href: "https://example.com/blogs/the-case-for-a-small-website",
date: "2026-06-16",
image: {
src: "/media/foldline/editorial-grid.svg",
alt: "An isometric set of simple editorial page layouts",
},
},
{
title: "Writing about objects",
description:
"Make dimensions, materials, and making part of a clear product story.",
href: "https://example.com/blogs/writing-about-objects",
date: "2026-05-21",
image: {
src: "/media/foldline/tern-objects.webp",
alt: "Walnut chair and oak table with a ceramic vessel",
},
},
],
}
---
```
```sh
bunx --bun shadcn@latest add @gnostic/blog-agency
```
See [serif accent font setup](/docs/installation#serif-accent-fonts-for-editorial-blocks) when installing this section.
## Journal grid
Supply your own content. The section uses the selected project preset.
```astro
---
import Block from "@/components/blocks/content/content-journal-grid/content-journal-grid.astro"
import type { JournalGridContent } from "@/components/blocks/content/content-journal-grid/types"
const content = {
posts: [
{
label: "AI agents",
title: "Give your AI agent one job, and a clear stopping point.",
date: "2026-10-22",
description:
"A focused brief makes an agent easier to test, review, and improve.",
image: {
src: "/media/gnotch/human-in-the-loop.webp",
alt: "A silver circular track with a gate and a waiting white sphere",
},
href: "/blog/ai-agents",
},
{
label: "Operations",
title: "The hand-off is often where the time goes.",
date: "2026-10-16",
description:
"Look between your tools to find the repeated work hiding in plain sight.",
image: {
src: "/media/gnotch/connected-work.webp",
alt: "Three graphite channels join into one silver path",
},
href: "/blog/save-time",
},
{
label: "Team practice",
title: "Make your first AI rollout a team exercise.",
date: "2026-10-09",
description:
"The people doing the work should help define what better looks like.",
image: {
src: "/media/gnotch/workshop.webp",
alt: "A small group working together with laptops",
},
href: "/blog/ai-adoption",
},
{
label: "Workflow design",
title: "Turn an enquiry into a brief your team can use.",
date: "2026-10-02",
description: "A practical outline for a first intake workflow.",
image: {
src: "/media/gnotch/signal-from-noise.webp",
alt: "Rough graphite pieces become aligned silver cubes inside a glass prism",
},
href: "/blog/workflow-automation",
},
{
label: "Human review",
title: "Put approval where a mistake would matter.",
date: "2026-09-25",
description:
"Design a review point that gives people enough context to decide.",
image: {
src: "/media/gnotch/project-review.webp",
alt: "A project discussion around an office table",
},
href: "/blog/manual-or-automated",
},
{
label: "Measurement",
title: "Measure the work you remove, not the runs you add.",
date: "2026-09-18",
description: "A busy automation log is not the same as a useful outcome.",
image: {
src: "/media/gnotch/desk-session.webp",
alt: "Colleagues reviewing a task at a laptop",
},
href: "/blog/measure-results",
},
],
} satisfies JournalGridContent
---
```
```sh
bunx --bun shadcn@latest add @gnostic/content-journal-grid
```
## Choose a articles layout
Choose a list or grid based on how many articles a reader must compare. Use consistent categories and dates so each card supplies the same kind of information.
## Pass content from Astro
Pass an articles array with the fields required by the selected variant. The first variant includes title, description, category, optional href, image, and author data. Sort and paginate in the route or data layer before passing the array.
## Responsive layout and images
Check mixed title lengths and missing author images at narrow widths. Use deliberate thumbnail crops and avoid downloading full-size lead images for every card. A responsive grid changes the layout; it does not fetch additional pages.
## Compose the next section
Pair the listing with an [Article](/blocks/article) detail page and [Pagination](/components/pagination) when the route has several pages of results.
---
# Banner Blocks for Astro
Source: https://ui.gnosticai.com/blocks/banner
## Inline announcement
Keep a short announcement and its destination together.
```astro
---
import Banner1Block from "@/components/blocks/banner/banner-1.astro"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/banner-1
```
## Floating actions
Give an inset announcement room for two action links.
```astro
---
import Banner2Block from "@/components/blocks/banner/banner-2.astro"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/banner-2
```
## Choose a banner layout
Choose a banner for a temporary service message or an announcement that belongs across several pages. Keep it short enough that it does not dominate the header.
## Pass content from Astro
Pass the title, description, and optional link accepted by the variant. Use the link for the page that explains the notice. If a variant supports dismissal, make sure important information remains available after it closes.
## Responsive layout and images
Check the message and action together on a phone. Text should wrap without hiding the close control. These layouts are text-led; an image is rarely needed. Inspect contrast on the selected banner surface in both modes.
## Compose the next section
Use [Alert](/components/alert) for a message tied to one page region and [Header](/blocks/header) for primary navigation.
---
# Contact Blocks for Astro
Source: https://ui.gnosticai.com/blocks/contact
Each block renders a real form with named, required fields and a submit button.
Set `form.action` to your form handler and `form.method` to `"post"` (the
default) or `"get"`. The blocks do not provide a submission backend.
Pass `form.id` for a stable form ID; field IDs use it as their prefix.
## Split form
Place contact methods beside a labelled enquiry form.
```astro
---
import Contact1Block from "@/components/blocks/contact/contact-1.astro"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/contact-1
```
## Centered form
Give the form a central position after the contact introduction.
```astro
---
import Contact2Block from "@/components/blocks/contact/contact-2.astro"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/contact-2
```
## Sidebar form
Keep the contact information available beside the enquiry fields.
```astro
---
import Contact3Block from "@/components/blocks/contact/contact-3.astro"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/contact-3
```
## Contact details and form
Supply your own content. The section uses the selected project preset.
```astro
---
import Block from "@/components/blocks/contact/contact-details-form/contact-details-form.astro"
import type { DetailsFormContent } from "@/components/blocks/contact/contact-details-form/types"
const content = {
email: "hello@gnotch.example",
phone: "+1 (212) 555-0148",
hours: "Monday–Friday, 9 AM–5 PM ET",
address: "New York · Working everywhere",
label: "Prepare email",
description:
"This form opens your email app. Review and send your message there.",
} satisfies DetailsFormContent
---
```
```sh
bunx --bun shadcn@latest add @gnostic/contact-details-form
```
## Editorial contact
Use this section for a project enquiry with a form endpoint or email draft fallback.
```astro
---
import Section from "@/components/blocks/contact/contact-agency.astro"
const section = {
label: "Your next chapter",
title: "Make room",
accent: "for what’s next",
description:
"Tell us about your practice and the story you want to tell. We will help you find a useful place to start.",
email: "hello@foldline.example",
companyTypes: [
"Architecture practice",
"Interior design studio",
"Furniture maker",
"Hospitality",
"Other",
],
serviceOptions: [
"Brand foundations",
"Studio website",
"Project stories",
"Launch support",
"Other",
],
buttonLabel: "Create email draft",
formTitle: "Tell us about your studio",
image: {
src: "/media/foldline/fold-sculpture.svg",
alt: "",
},
}
---
```
```sh
bunx --bun shadcn@latest add @gnostic/contact-agency
```
See [serif accent font setup](/docs/installation#serif-accent-fonts-for-editorial-blocks) when installing this section.
## Home services area
```astro
---
import Block from "@/components/blocks/contact/contact-remodify-area.astro"
const content = {
eyebrow: "Close to Home",
title: "Rooted in Raleigh.",
map: {
src: "https://www.openstreetmap.org/export/embed.html?bbox=-78.98%2C35.63%2C-78.48%2C35.99&layer=mapnik",
title: "Map of Raleigh, Cary, Apex, and nearby communities",
href: "https://www.openstreetmap.org/#map=11/35.80/-78.73",
label: "Explore the Raleigh service area",
},
mapTitle: "Your Neighborhood. Your Home.",
description:
"Planning a remodel in the Triangle? Tell us where you live and what you have in mind.",
locations: [
"Raleigh",
"Cary",
"Apex",
"Morrisville",
"Garner",
"Wake Forest",
"Holly Springs",
"Knightdale",
],
benefits: [
"Kitchen and bathroom remodeling",
"Whole-home renovations",
"Interior updates and finish carpentry",
],
action: {
label: "Check Your Location",
href: "#contact",
},
phone: {
label: "(919) 555-0142",
href: "tel:+19195550142",
},
}
---
```
```sh
bunx --bun shadcn@latest add @gnostic/contact-remodify-area
```
## Home services contact
```astro
---
import Block from "@/components/blocks/contact/contact-remodify.astro"
const content = {
eyebrow: "Start With a Conversation",
title: "What Could Home Be?",
description:
"Tell us about your space, location, and plans. The next step is a conversation about what is possible.",
image: {
src: "https://images.unsplash.com/photo-1762146828422-50a8bd416d3c?auto=format&fit=max&w=1600&q=80",
alt: "Architectural drawings spread across a work surface",
},
services: [
"Kitchen Remodeling",
"Bathroom Remodeling",
"Whole-Home Renovation",
"Interior Updates",
],
budgets: [
"Under $25,000",
"$25,000 - $75,000",
"$75,000 - $150,000",
"$150,000+",
"Help me plan a budget",
],
submitLabel: "Discuss My Remodel",
demoNotice: "Sample form. No request will be sent.",
demoMessage: "Your sample request is complete. No message was sent.",
}
---
```
```sh
bunx --bun shadcn@latest add @gnostic/contact-remodify
```
## Business hours and booking
An address, opening hours, email, and a configurable booking link.
```astro
---
import Block from "@/components/blocks/contact/contact-hours.astro"
const content = {
eyebrow: "Come as you are",
title: "Make a little time\nfor yourself.",
description:
"Tell us what you have in mind. We will help you find the right appointment.",
address: ["Sable Hair Studio", "12 Example Street", "Your town"],
hours: [
{
label: "Tuesday–Friday",
value: "10 am–7 pm",
},
{
label: "Saturday",
value: "9 am–5 pm",
},
{
label: "Sunday–Monday",
value: "Closed",
},
],
action: {
label: "Email for an appointment",
href: "mailto:hello@example.com",
},
email: "hello@example.com",
note: "Demo salon. Address, hours, and prices are sample content.",
}
---
```
```sh
bunx --bun shadcn@latest add @gnostic/contact-hours
```
## Choose a contact layout
Choose the contact layout from the ways people can actually reach you. A small site may need only direct links; a detailed enquiry can use a form with a short explanation of the next step.
## Pass content from Astro
Contact form variants accept content labels and form action/method props. Connect those to a real endpoint or Astro action. The block displays the form but does not send mail, validate server-side rules, or store submissions by itself.
## Responsive layout and images
Check label wrapping, error messages, and keyboard order on a narrow screen. Keep email and phone links usable without the form. If a variant includes an image, supply useful context rather than an image that competes with the fields.
## Compose the next section
Place [Services](/blocks/services) or [FAQs](/blocks/faqs) before contact when they answer common questions. Use [Field](/components/field) for extra form fields.
---
# Content Blocks for Astro
Source: https://ui.gnosticai.com/blocks/content
## Stacked media
Put the explanation before a full-width media area.
```astro
---
import Content1Block from "@/components/blocks/content/content-1.astro"
import Photo from "@/assets/images/winter-landscape-orion.png"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/content-1
```
## Split media
Keep a supporting image beside the explanation.
```astro
---
import Content2Block from "@/components/blocks/content/content-2.astro"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/content-2
```
## Spread header
Arrange the heading and actions above the media.
```astro
---
import Content3Block from "@/components/blocks/content/content-3.astro"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/content-3
```
## Wide media
Give the media more room than the supporting text.
```astro
---
import Content4Block from "@/components/blocks/content/content-4.astro"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/content-4
```
## Product introduction
Place partner logos above a large heading and product image.
```astro
---
import Block from "@/components/blocks/content/content-nimbus-introduction.astro"
const content = {
title: "A little more room for your day.",
description:
"Meet Loom, a fictional home assistant designed for everyday tasks.",
image: {
src: "/images/nimbus-sample.svg",
alt: "Product sample",
},
logos: [
{
src: "/favicon.svg",
alt: "Sample studio",
},
],
}
---
```
```sh
bunx --bun shadcn@latest add @gnostic/content-nimbus-introduction
```
## Results and method
Pair a main result with metric cards and expandable method notes.
```astro
---
import Block from "@/components/blocks/content/content-nimbus-signals.astro"
const content = {
eyebrow: "Sample results",
title: "Show the results and their limits.",
description:
"These fictional values show how to present a small product trial.",
headline: "90% active each week.",
summary: "Example activity after the first month.",
metrics: [
{
label: "Active homes",
value: "90%",
description: "Homes that used the product during the week.",
source: "Fictional sample",
},
{
label: "Setup time",
value: "35 min",
description: "Median time from unpacking to the first task.",
source: "Fictional sample",
},
{
label: "Trial homes",
value: "120",
description: "Homes included in this example.",
source: "Fictional sample",
},
],
methodologyTitle: "How we count",
methodologyDescription: "Explain the sample and the method.",
methodology: [
{
question: "What is an active home?",
answer: "A home that completed at least one task during the week.",
},
{
question: "Are these real results?",
answer: "No. These are sample values for this block preview.",
},
],
}
---
```
```sh
bunx --bun shadcn@latest add @gnostic/content-nimbus-signals
```
## Content Portfolio About
An independent section from the Portfolio template. Supply its content through props.
```astro
---
import Block from "@/components/blocks/content/content-portfolio-about.astro"
import asset0 from "../../../../../packages/templates/sable/site/src/assets/sable/stylist-at-work.png"
import asset1 from "../../../../../packages/templates/sable/site/src/assets/sable/sculpted-bob.png"
import asset2 from "../../../../../packages/templates/sable/site/src/assets/sable/natural-curls.png"
import asset3 from "../../../../../packages/templates/sable/site/src/assets/sable/soft-balayage.png"
import asset4 from "../../../../../packages/templates/sable/site/src/assets/sable/textured-crop.png"
import asset5 from "../../../../../packages/templates/sable/site/src/assets/sable/silver-pixie.png"
import asset6 from "../../../../../packages/templates/sable/site/src/assets/sable/loose-waves.png"
const content = {
title: "Rowan · Hair stylist",
description:
"A sample profile for an independent stylist. Soft shapes, natural movement, and practical care are at the centre of this fictional studio.",
image: {
src: asset0,
alt: "A stylist finishing shoulder-length hair with a brush and dryer",
},
skills: ["Precision cuts", "Colour", "Curly hair", "Styling"],
experience: [
{
role: "Independent stylist",
company: "Example studio",
period: "Now",
},
{
role: "Stylist",
company: "Example salon",
period: "2021–2025",
},
],
projects: [
{
src: asset1,
alt: "A chin-length dark bob with a soft fringe",
name: "The sculpted bob",
href: "#visit",
label: "The sculpted bob",
},
{
src: asset2,
alt: "Shoulder-length natural curls in soft daylight",
name: "Natural curls",
href: "#visit",
label: "Natural curls",
},
{
src: asset3,
alt: "Long brunette hair with subtle caramel colour",
name: "Soft balayage",
href: "#visit",
label: "Soft balayage",
},
{
src: asset4,
alt: "A short coily crop with a soft taper",
name: "The textured crop",
href: "#visit",
label: "The textured crop",
},
{
src: asset5,
alt: "A textured silver pixie cut",
name: "Silver, softly shaped",
href: "#visit",
label: "Silver, softly shaped",
},
{
src: asset6,
alt: "Shoulder-length dark waves with a soft face frame",
name: "Everyday waves",
href: "#visit",
label: "Everyday waves",
},
],
projectsId: "looks",
}
---
```
```sh
bunx --bun shadcn@latest add @gnostic/content-portfolio-about
```
## Split statement
Supply your own content. The section uses the selected project preset.
```astro
---
import Block from "@/components/blocks/content/content-split-statement/content-split-statement.astro"
import type { SplitStatementContent } from "@/components/blocks/content/content-split-statement/types"
const content = {
value: "01",
title: "One useful workflow is a better start than a hundred new tools.",
description:
"Start with the task your team repeats every day. Build it well. Then take the next step.",
} satisfies SplitStatementContent
---
```
```sh
bunx --bun shadcn@latest add @gnostic/content-split-statement
```
## Story and statistics
Supply your own content. The section uses the selected project preset.
```astro
---
import Block from "@/components/blocks/content/content-story-stats/content-story-stats.astro"
import type { StoryStatsContent } from "@/components/blocks/content/content-story-stats/types"
const content = {
label: "Our point of view",
title: "A Studio Built Around the Next Useful Step",
description:
"We believe good automation starts small, makes sense to the people using it, and gets better with use.",
milestones: [
{
label: "Observe",
title: "Start at the shared desk.",
description:
"Watch how a real request moves through the business. The useful details are often in the small steps between tools.",
image: {
src: "/media/gnotch/workshop.webp",
alt: "A small group working together with laptops",
},
},
{
label: "Connect",
title: "Keep what already works.",
description:
"A familiar tool with a better connection can do more than another dashboard. We build around the systems your team knows.",
image: {
src: "/media/gnotch/desk-session.webp",
alt: "Colleagues reviewing a task at a laptop",
},
},
{
label: "Explain",
title: "Make the system readable.",
description:
"Your team should know what runs, when it runs, and what to do if it stops. Clear instructions are part of the product.",
image: {
src: "/media/gnotch/project-review.webp",
alt: "A project discussion around an office table",
},
},
{
label: "Improve",
title: "Leave room for the next step.",
description:
"Listen to the people who use the workflow. Fix the rough edges, measure the result, and add only what the work needs.",
image: {
src: "/media/gnotch/team-working.webp",
alt: "Colleagues sharing ideas around a work table",
},
},
],
} satisfies StoryStatsContent
---
```
```sh
bunx --bun shadcn@latest add @gnostic/content-story-stats
```
## Editorial about
Use this section for the about part of a studio site.
```astro
---
import Section from "@/components/blocks/content/content-agency.astro"
const section = {
label: "A studio for studios",
title:
"You shape the places people live. We shape the way people find, understand, and remember your work.",
description:
"Foldline brings brand design, editorial thinking, and web development to architecture and interiors. Small team. Close conversations. Care in every detail.",
wordmark: "foldline",
stats: [
{
label: "Connected disciplines",
value: "03",
},
{
label: "Shared project team",
value: "01",
},
{
label: "Clear project stages",
value: "04",
},
],
}
---
```
```sh
bunx --bun shadcn@latest add @gnostic/content-agency
```
See [serif accent font setup](/docs/installation#serif-accent-fonts-for-editorial-blocks) when installing this section.
## Editorial project milestones
Use this list for awards or project milestones. Foldline uses it to describe the work in each concept project.
```astro
---
import Section from "@/components/blocks/awards/awards-agency.astro"
const section = {
label: "Inside the projects",
title: "Small details,",
accent: "lasting value",
awards: [
{
organization: "Rook & Stone",
title: "A clearer studio story",
project: "Positioning & identity",
},
{
organization: "Morrow Rooms",
title: "A warmer first impression",
project: "Art direction & content",
},
{
organization: "Tern Objects",
title: "A collection with room to grow",
project: "Catalogue & website",
},
{
organization: "Foldline",
title: "One connected way of working",
project: "Strategy, design & build",
},
],
}
---
```
```sh
bunx --bun shadcn@latest add @gnostic/awards-agency
```
See [serif accent font setup](/docs/installation#serif-accent-fonts-for-editorial-blocks) when installing this section.
## Home services introduction
```astro
---
import Block from "@/components/blocks/content/content-remodify-introduction.astro"
const content = {
brand: "Remodify",
title: "Keep the place you love. Change the way it lives.",
images: [
{
src: "https://images.unsplash.com/photo-1770756051811-1612ac8bedfa?auto=format&fit=max&w=1600&q=80",
alt: "White home with dark windows and glass garage doors",
},
{
src: "https://images.unsplash.com/photo-1696814543783-c0835c0be682?auto=format&fit=max&w=1600&q=80",
alt: "Bright kitchen with white cabinets, wood flooring, and orange breakfast chairs",
},
{
src: "https://images.unsplash.com/photo-1729173078273-3ee243b9273b?auto=format&fit=max&w=1600&q=80",
alt: "Bathroom with a blue bathtub and a large window",
},
{
src: "https://images.unsplash.com/photo-1726090401458-7abb00f7450c?auto=format&fit=max&w=1600&q=80",
alt: "Living room with timber beams and a stone fireplace",
},
{
src: "https://images.unsplash.com/photo-1771888703723-01d85da1dae1?auto=format&fit=max&w=1600&q=80",
alt: "Open living space with neutral sofas and curved chairs",
},
{
src: "https://images.unsplash.com/photo-1762146828422-50a8bd416d3c?auto=format&fit=max&w=1600&q=80",
alt: "Architectural drawings spread across a work surface",
},
],
trustTitle: "Good spaces start with a good plan.",
description:
"We help Raleigh homeowners connect the details, from the first layout to the last cabinet handle.",
benefits: [
{
title: "A clear scope",
icon: "clipboard-check",
},
{
title: "Care in every detail",
icon: "hammer",
},
{
title: "One point of contact",
icon: "messages-square",
},
],
}
---
```
```sh
bunx --bun shadcn@latest add @gnostic/content-remodify-introduction
```
## Home services confidence
```astro
---
import Block from "@/components/blocks/content/content-remodify-confidence.astro"
const content = {
title: "Less Guesswork. More Home.",
description:
"Your remodel should fit your routines as well as your rooms. We listen first, explain the options, and agree on the work before it begins.",
benefits: [
"Room layouts shaped around your needs",
"A written scope and itemized estimate",
"Regular updates and a tidy work area",
],
action: {
label: "(919) 555-0142",
href: "tel:+19195550142",
},
image: {
src: "https://images.unsplash.com/photo-1769353086138-19ee65291a04?auto=format&fit=max&w=1600&q=80",
alt: "Carpenter shaping a piece of wood in a workshop",
},
stats: [
{
value: "01",
label: "Dedicated project contact",
},
{
value: "04",
label: "Clear steps from idea to finish",
},
],
}
---
```
```sh
bunx --bun shadcn@latest add @gnostic/content-remodify-confidence
```
## Video demonstration
A local video with a poster, playback controls, and a caption.
```astro
---
import Block from "@/components/blocks/content/content-video-demo.astro"
import poster from "../../../../../packages/templates/nimbus/site/src/assets/nimbus-dishes.png"
import video from "../../../../../packages/templates/nimbus/site/src/assets/nimbus-robot-doing-dishes.mp4?url"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/content-video-demo
```
## Split image and story
An imported image beside plain text and an optional action.
```astro
---
import Block from "@/components/blocks/content/content-split-story.astro"
import asset0 from "../../../../../packages/templates/sable/site/src/assets/sable/stylist-at-work.png"
const content = {
eyebrow: "Our kind of salon",
title: "Room to slow down.\nSpace to be you.",
paragraphs: [
"We like good conversations, honest advice, and hair that still feels right weeks after your appointment. Sable is built around those simple things.",
"Bring a picture, a question, or no plan at all. We will listen first and work out the next step together.",
],
image: {
src: asset0,
alt: "A stylist finishing shoulder-length hair with a brush and dryer",
},
action: {
label: "Plan your first visit",
href: "#visit",
},
}
---
```
```sh
bunx --bun shadcn@latest add @gnostic/content-split-story
```
## Choose a content layout
Choose a content layout that fits the balance between your text and media. A short explanation can sit beside one image; a longer story may need several sections with separate headings.
## Pass content from Astro
Pass the chosen variant’s title, description, optional features, buttons, and image data. Keep the text structured rather than placing an entire page in one description string. Use slots where the block exposes them for richer markup.
## Responsive layout and images
Review the order when columns stack on small screens. Import local images for props typed as ImageMetadata and choose a crop suited to the displayed ratio. Check that text remains readable when the image is missing or delayed.
## Compose the next section
Use [Hero](/blocks/hero) for the opening statement, [Features](/blocks/features) for a set of benefits, and [CTA](/blocks/cta) for the next action.
---
# Astro Call to Action blocks
Source: https://ui.gnosticai.com/blocks/cta
## Centered
Center the invitation and keep its actions together.
```astro
---
import CallToActionBlock from "@/components/blocks/cta/cta-1.astro"
import { agentAvatars } from "@/lib/agent-avatars"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/cta-1
```
## Split
Use separate columns for the invitation and its supporting content.
```astro
---
import Cta2Block from "@/components/blocks/cta/cta-2.astro"
import { agentAvatars } from "@/lib/agent-avatars"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/cta-2
```
## Spread
Spread the message and actions across the section.
```astro
---
import Cta3Block from "@/components/blocks/cta/cta-3.astro"
import { agentAvatars } from "@/lib/agent-avatars"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/cta-3
```
## Background
Place a short invitation on a background surface.
```astro
---
import Cta4Block from "@/components/blocks/cta/cta-4.astro"
import { agentAvatars } from "@/lib/agent-avatars"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/cta-4
```
## Checklist
Add a short checklist before the next action.
```astro
---
import Cta5Block from "@/components/blocks/cta/cta-5.astro"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/cta-5
```
## Reversed
Reverse the content order to fit the surrounding sections.
```astro
---
import Cta6Block from "@/components/blocks/cta/cta-6.astro"
import { agentAvatars } from "@/lib/agent-avatars"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/cta-6
```
## Tinted
Use a tinted surface to separate the invitation from adjacent content.
```astro
---
import Cta7Block from "@/components/blocks/cta/cta-7.astro"
import { agentAvatars } from "@/lib/agent-avatars"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/cta-7
```
## Subtle
Keep the message short when the page has already explained the offer.
```astro
---
import Cta8Block from "@/components/blocks/cta/cta-8.astro"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/cta-8
```
## Orbit call to action
Supply your own content. The section uses the selected project preset.
```astro
---
import Block from "@/components/blocks/cta/cta-orbit/cta-orbit.astro"
import type { OrbitCtaContent } from "@/components/blocks/cta/cta-orbit/types"
const content = {
title: "Your Next Chapter Starts with One Better Workflow.",
buttons: [
{
label: "Find your first workflow",
href: "/contact",
},
{
label: "Meet the studio",
href: "/about",
},
],
label: "Gnotch",
} satisfies OrbitCtaContent
---
```
```sh
bunx --bun shadcn@latest add @gnostic/cta-orbit
```
## Home services ticker
```astro
---
import Block from "@/components/blocks/cta/cta-remodify-ticker.astro"
const content = {
labels: ["Make Room for Life", "Keep What You Love", "Make Home Yours"],
}
---
```
```sh
bunx --bun shadcn@latest add @gnostic/cta-remodify-ticker
```
## Choose a layout
Choose a CTA after the reader has enough information to act. State what happens next, such as viewing plans or sending an enquiry, instead of using a vague action label.
## Pass content from Astro
Pass the title, description, and button links required by the block. Some variants also accept avatars, a rating, and proof text. Use those fields only for accurate evidence and keep the main action clear.
## Responsive layout and images
Check the button row and heading on narrow screens. Optional avatars need real image sources or useful initials; they should not become unexplained decorative people. Theme contrast must remain sufficient on tinted CTA backgrounds.
## Compose the next section
Use [Pricing](/blocks/pricing) before a purchase action and [Contact](/blocks/contact) for an enquiry. A CTA link alone does not implement checkout or a form submission.
---
# Doc Blocks for Astro
Source: https://ui.gnosticai.com/blocks/doc
## Guide
Use a reading column with contents links, a callout, and previous and next navigation.
```astro
---
import Doc1Block from "@/components/blocks/doc/doc-1.astro"
---
Prepare the review
Gather the current project brief, the open task list, and the notes from
your previous review. Check that each document describes the same milestone
before you invite the team.
Discuss open questions
Start the discussion with questions that prevent progress. Decide which
questions can be answered now and assign the remaining checks to a named
person. Record the reason for each decision.
When the question list is empty
When there are no open questions, use the time to check unfinished tasks.
Confirm whether each task still belongs in the current milestone rather than
adding work to fill the meeting.
Agree on next actions
Close the review with a short list of actions. Give each action an owner, a
next step, and a date for the next check. Share the notes with anyone who
could not attend.
```
```sh
bunx --bun shadcn@latest add @gnostic/mobile-menu-1
```
Open Components, then Navigation to try two submenu levels. Components has an
Overview link. Navigation has no destination and uses a group label. Each panel opens
from the same edge. The default is the right edge; set `position="bottom"`
to use bottom panels with swipe handles.
## Installation
```sh
bunx --bun shadcn@latest add @gnostic/mobile-menu-1
```
## Header option
All five [header blocks](/blocks/header) accept `mobileMenu="drawer"`.
They use the same navigation data and pass `actions`, plus
`slot="mobile"`, to this block. The default remains `mobileMenu="sheet"`.
```astro
Support
```
The header hides the trigger at `1024px` and closes an open drawer at that width.
## Props
### MobileMenuProps
### MobileMenuLink
### MobileMenuNavigationItem
### MobileMenuButton
The standalone block has no breakpoint restriction. Use `class="lg:hidden"`
and `closeOnMedia="(min-width: 1024px)"` when you pair it with desktop navigation.
Custom footer links can use `DrawerClose as="a"` to close on selection.
Use `class={buttonVariants()}` when that control should look like a button.
## Choose a mobile menu layout
Choose a mobile menu for navigation that does not fit the desktop header at smaller widths. Keep its destinations aligned with the desktop navigation.
## Pass content from Astro
Pass navigation groups, optional actions, and trigger/title labels. Position and variant props change the panel layout. Use closeOnMedia where supported to close a panel when the page returns to a desktop layout.
## Responsive layout and images
Test opening, Escape, link activation, and focus return with a keyboard. A menu with many links needs scrolling that leaves the close control reachable. Logo or icon artwork needs a text name when it is the only visible mark.
## Compose the next section
Use [Header](/blocks/header) for the complete shell and [Sheet](/components/sheet) or [Drawer](/components/drawer) for lower-level panel composition.
---
# Pricing Blocks for Astro
Source: https://ui.gnosticai.com/blocks/pricing
## Plan cards
Present each plan with its price, included features, and action.
```astro
---
import Pricing1Block from "@/components/blocks/pricing/pricing-1.astro"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/pricing-1
```
## Comparison
Keep plan details aligned so readers can compare the offers.
```astro
---
import Pricing2Block from "@/components/blocks/pricing/pricing-2.astro"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/pricing-2
```
## Single offer
Give one offer room for a complete feature list.
```astro
---
import Pricing3Block from "@/components/blocks/pricing/pricing-3.astro"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/pricing-3
```
## Project plans
Supply your own content. The section uses the selected project preset.
```astro
---
import Block from "@/components/blocks/pricing/pricing-plan-cards/pricing-plan-cards.astro"
import type { PlanCardsContent } from "@/components/blocks/pricing/pricing-plan-cards/types"
const content = {
label: "Ways to work together",
title: "Start Small. Build What Comes Next.",
plans: [
{
title: "First Workflow",
price: "$2,500",
period: "/project",
description:
"A focused pilot for one repeated task with a clear beginning and end.",
button: {
label: "Plan a pilot",
href: "/contact?plan=pilot",
},
features: [
"Workflow discovery session",
"One workflow, up to 3 tools",
"Human approval checkpoints",
"Test runs with sample data",
"Team guide and handover",
"30-day launch support",
],
},
{
title: "Connected Operations",
price: "$1,500",
period: "/month",
label: "Ongoing care",
description:
"Keep your workflows healthy and improve them as your team learns.",
button: {
label: "Discuss ongoing care",
href: "/contact?plan=operations",
},
features: [
"Workflow health checks",
"Failed-run review and fixes",
"One improvement each month",
"Usage and outcome reporting",
"Monthly planning session",
"A named technical contact",
],
},
{
title: "Custom Systems",
price: "Let’s talk",
description:
"A scoped engagement for teams with several connected processes.",
button: {
label: "Scope your system",
href: "/contact?plan=custom",
},
features: [
"Process and data discovery",
"Custom agents and integrations",
"Access and approval design",
"Staged rollout with your team",
"Documentation and training",
"A support plan that fits",
],
},
],
} satisfies PlanCardsContent
---
```
```sh
bunx --bun shadcn@latest add @gnostic/pricing-plan-cards
```
## Editorial pricing
Use this section for the pricing part of a studio site.
```astro
---
import Section from "@/components/blocks/pricing/pricing-agency.astro"
const section = {
label: "Ways to work together",
title: "A good fit,",
accent: "from the start",
description:
"Clear scopes for independent studios. The figures below show how a typical engagement can be structured.",
plans: [
{
title: "Foundation",
description: "For a new practice finding its voice",
price: "$4,800+",
period: "/ engagement",
featured: false,
features: [
"Positioning workshop",
"Visual identity direction",
"Type, color, and image guidance",
"A practical brand guide",
],
action: {
label: "Discuss your studio",
href: "https://example.com/contact",
},
},
{
title: "Studio launch",
description: "For a complete identity and digital home",
price: "$9,600+",
period: "/ engagement",
featured: true,
features: [
"Brand foundations",
"Custom studio website",
"Project archive and editing tools",
"Content planning and launch checks",
"Team handover and training",
],
action: {
label: "Plan your launch",
href: "https://example.com/contact",
},
},
{
title: "Ongoing care",
description: "For a studio with more stories to tell",
price: "Let’s plan",
period: "/ partnership",
featured: false,
features: [
"New project stories",
"Website improvements",
"Campaign and press materials",
"A dedicated monthly work plan",
],
action: {
label: "Build a partnership",
href: "https://example.com/contact",
},
},
],
}
---
```
```sh
bunx --bun shadcn@latest add @gnostic/pricing-agency
```
See [serif accent font setup](/docs/installation#serif-accent-fonts-for-editorial-blocks) when installing this section.
## Home services pricing
```astro
---
import Block from "@/components/blocks/pricing/pricing-remodify.astro"
const content = {
eyebrow: "Plan the Investment",
title: "Your Scope.",
description:
"Every home is different. Your written estimate will reflect the work, material choices, and site conditions for your remodel.",
featureLabel: "What we plan together:",
plans: [
{
title: "One Room",
price: "Focused",
unit: "remodel",
description:
"A kitchen, bathroom, or interior update with a clear purpose.",
features: [
"Review of your existing space",
"Layout and finish options",
"Written scope of work",
"Itemized project estimate",
"Material and fixture planning",
"A schedule for your project",
],
action: {
label: "Discuss One Room",
href: "#contact",
},
},
{
title: "Whole Home",
price: "Connected",
unit: "renovation",
badge: "A joined-up plan",
description:
"A coordinated approach for several rooms or a full interior renovation.",
features: [
"Room-by-room priorities",
"A consistent material palette",
"Phased work and access planning",
"Permit requirements review",
"Coordinated trade schedules",
"Final walkthrough and care guidance",
],
action: {
label: "Plan a Larger Remodel",
href: "#contact",
},
},
],
}
---
```
```sh
bunx --bun shadcn@latest add @gnostic/pricing-remodify
```
## Choose a pricing layout
Choose a pricing layout that lets readers compare the same facts across plans. Mark a featured plan only when there is a clear reason to recommend it.
## Pass content from Astro
Pass plan names, amounts, currency, billing unit, features, and button links. Explain recurring charges and limits in the content. The block displays prices; it does not calculate totals, manage subscriptions, or implement checkout.
## Responsive layout and images
Check how cards stack on a phone and keep plan names attached to their feature lists. Long currency values and translated billing units need extra space. Pricing usually needs clear text more than decorative imagery.
## Compose the next section
Use [FAQs](/blocks/faqs) for common billing questions and [CTA](/blocks/cta) for a single next step after a comparison.
---
# Product Blocks for Astro
Source: https://ui.gnosticai.com/blocks/product
## Featured
Keep a product image, price, description, and actions in one section.
```astro
---
import Product1Block from "@/components/blocks/product/product-1.astro"
import placeholderImage from "@/assets/placeholder.webp"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/product-1
```
## Choose a product layout
Choose a product block for one item or offer. Give the description enough detail to explain what the reader receives and use the note for a real condition or limitation.
## Pass content from Astro
Pass the title, image, price object, note, and action links required by the variant. Product data and availability belong in the page or backend. The display does not add an item to a cart by itself.
## Responsive layout and images
Check the product image crop, price wrapping, and action layout on a phone. Supply accurate alt text and an image size suited to the main product view. A detail image should show useful evidence about the item.
## Compose the next section
Use [Products](/blocks/products) for a collection and [Content](/blocks/content) for additional specifications or usage detail.
---
# Products Blocks for Astro
Source: https://ui.gnosticai.com/blocks/products
## Image grid
Show product images and short descriptions in a grid.
```astro
---
import Products1Block from "@/components/blocks/products/products-1.astro"
import placeholderImage from "@/assets/placeholder.webp"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/products-1
```
## List
Use a compact list when the product details need less media.
```astro
---
import Products2Block from "@/components/blocks/products/products-2.astro"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/products-2
```
## Price cards
Make the price easy to compare across product cards.
```astro
---
import Products3Block from "@/components/blocks/products/products-3.astro"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/products-3
```
## Action row
Add a collection action beside the product row.
```astro
---
import Products4Block from "@/components/blocks/products/products-4.astro"
import placeholderImage from "@/assets/placeholder.webp"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/products-4
```
## Hover grid
Use image-led cards with the block hover treatment.
```astro
---
import Products5Block from "@/components/blocks/products/products-5.astro"
import placeholderImage from "@/assets/placeholder.webp"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/products-5
```
## Choose a products layout
Choose a products grid when readers need to scan several items before opening a detail view. Keep each item’s information consistent so comparison is possible.
## Pass content from Astro
Pass the products array accepted by the chosen block. Format price and unit data consistently. Filtering, stock checks, and pagination are separate application concerns.
## Responsive layout and images
Check grid wrapping with long product titles and varied images. Use thumbnail sources and a consistent crop policy. Where the variant exposes links, make each destination name clear without relying only on its image.
## Compose the next section
Use [Product](/blocks/product) for item detail and [Pagination](/components/pagination) for collections split across routes.
---
# Reviews Blocks for Astro
Source: https://ui.gnosticai.com/blocks/reviews
## Cards
Give each sample quote its own card and attribution.
```astro
---
import Reviews1Block from "@/components/blocks/reviews/reviews-1.astro"
import { agentAvatars } from "@/lib/agent-avatars"
const day = 24 * 60 * 60 * 1000
const formatter = new Intl.RelativeTimeFormat("en", { numeric: "auto" })
/** Format a review timestamp. The block only receives the finished label. */
function dateLabel(timestamp: number) {
const days = Math.round((timestamp - Date.now()) / day)
return formatter.format(days, "day")
}
const reviews = [
{
rating: 5,
reviewText:
"The assessment explained which seam needed attention. I could decide on the repair before leaving my bag.",
authorImage: agentAvatars[0],
authorName: "Leila Moreno",
source: "google",
dateLabel: dateLabel(Date.now() - 14 * day),
},
{
rating: 5,
reviewText:
"The collection note listed the completed work and the care steps I should follow at home.",
authorImage: agentAvatars[1],
authorName: "Owen Patel",
source: "yelp",
dateLabel: dateLabel(Date.now() - 30 * day),
},
{
rating: 4.5,
reviewText:
"I brought the loose parts to the visit. The studio checked the fastening before suggesting a replacement.",
authorImage: agentAvatars[2],
authorName: "Nadia Chen",
source: "trustpilot",
},
]
---
```
```sh
bunx --bun shadcn@latest add @gnostic/reviews-1
```
## Featured
Place one featured sample quote beside shorter quotes.
```astro
---
import Reviews2Block from "@/components/blocks/reviews/reviews-2.astro"
import { agentAvatars } from "@/lib/agent-avatars"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/reviews-2
```
## Grid
Arrange sample quotes in a grid with their attributions.
```astro
---
import Reviews3Block from "@/components/blocks/reviews/reviews-3.astro"
import { agentAvatars } from "@/lib/agent-avatars"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/reviews-3
```
## Marquee
Move sample review cards through the section.
```astro
---
import Reviews4Block from "@/components/blocks/reviews/reviews-4.astro"
import { agentAvatars } from "@/lib/agent-avatars"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/reviews-4
```
## Rows
Use rows when each sample quote needs a wider reading area.
```astro
---
import Reviews5Block from "@/components/blocks/reviews/reviews-5.astro"
import { agentAvatars } from "@/lib/agent-avatars"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/reviews-5
```
## Reviews Portfolio
An independent section from the Portfolio template. Supply its content through props.
```astro
---
import Block from "@/components/blocks/reviews/reviews-portfolio.astro"
import asset0 from "../../../../../packages/templates/sable/site/src/assets/sable/salon-interior.png"
const content = {
title: "Words from the chair",
description:
"Fictional reviews for this block example. Replace them with real feedback before publication.",
image: {
src: asset0,
alt: "Warm daylight across the chairs and mirrors at Sable",
},
reviews: [
{
authorName: "Alex",
role: "Example client",
reviewText:
"We talked through the cut first. I left with a shape I can style at home.",
rating: 5,
},
{
authorName: "Sam",
role: "Example client",
reviewText: "A quiet appointment and helpful advice about my curls.",
rating: 5,
},
],
stats: [],
contact: {
label: "Plan your visit",
href: "#visit",
email: "hello@example.com",
available: "Cuts · Colour · Care",
},
servicesHref: "#services",
}
---
```
```sh
bunx --bun shadcn@latest add @gnostic/reviews-portfolio
```
## Image review carousel
Supply your own content. The section uses the selected project preset.
```astro
---
import Block from "@/components/blocks/reviews/reviews-image-carousel/reviews-image-carousel.astro"
import type { ImageReviewsContent } from "@/components/blocks/reviews/reviews-image-carousel/types"
const content = {
label: "Sample client stories",
title: "A Little Less Friction. A Lot More Focus.",
reviews: [
{
authorName: "Avery Cole",
role: "Operations lead, Fieldnote",
reviewText:
"We open the day with a clear brief. The team can talk about the work instead of finding the latest update.",
rating: 5,
source: "google",
image: {
src: "/media/gnotch/team-working.webp",
alt: "Colleagues sharing ideas around a work table",
},
},
{
authorName: "Samira Lane",
role: "Founder, Commonplace",
reviewText:
"Gnotch started with our intake form. One small change made the whole project hand-off easier to follow.",
rating: 5,
source: "yelp",
image: {
src: "/media/gnotch/planning-session.webp",
alt: "A team comparing notes in a shared workspace",
},
},
{
authorName: "Rowan Ellis",
role: "Support lead, Northline",
reviewText:
"The assistant prepares a reply and shows its sources. We can spend our time on the questions that need a person.",
rating: 5,
source: "trustpilot",
image: {
src: "/media/gnotch/desk-session.webp",
alt: "Colleagues reviewing a task at a laptop",
},
},
{
authorName: "Casey Park",
role: "Director, Plainwork",
reviewText:
"We know what runs, what failed, and who owns the next step. That clarity matters as much as the time saved.",
rating: 5,
source: "google",
image: {
src: "/media/gnotch/workshop.webp",
alt: "A small group working together with laptops",
},
},
{
authorName: "Morgan Reed",
role: "Studio lead, Daymark",
reviewText:
"The workflow fits the tools we already use. We did not need to rebuild the way our team works.",
rating: 5,
source: "yelp",
image: {
src: "/media/gnotch/project-review.webp",
alt: "A project discussion around an office table",
},
},
],
} satisfies ImageReviewsContent
---
```
```sh
bunx --bun shadcn@latest add @gnostic/reviews-image-carousel
```
## Editorial reviews
Use this section for the reviews part of a studio site.
```astro
---
import Section from "@/components/blocks/reviews/reviews-agency.astro"
const section = {
label: "Illustrative client notes",
title: "Good work starts",
accent: "with a conversation",
reviews: [
{
rating: 5,
reviewText:
"“The new archive makes the thinking behind each home much easier to understand.”",
authorName: "Leah Wren",
role: "Principal, Rook & Stone · sample quote",
authorImage: "/media/foldline/avatar-lw.svg",
source: "google",
},
{
rating: 5,
reviewText:
"“The site has the same calm welcome we want a guest to feel at the door.”",
authorName: "Owen Hart",
role: "Founder, Morrow Rooms · sample quote",
authorImage: "/media/foldline/avatar-oh.svg",
source: "yelp",
},
{
rating: 5,
reviewText:
"“Our materials, proportions, and process finally feel part of one story.”",
authorName: "Ada Bell",
role: "Director, Tern Objects · sample quote",
authorImage: "/media/foldline/avatar-ab.svg",
source: "trustpilot",
},
{
rating: 5,
reviewText:
"“A close, thoughtful process that gave us space to make the right decisions.”",
authorName: "Kit Arden",
role: "Interior designer · sample quote",
authorImage: "/media/foldline/avatar-ka.svg",
source: "google",
},
],
}
---
```
```sh
bunx --bun shadcn@latest add @gnostic/reviews-agency
```
See [serif accent font setup](/docs/installation#serif-accent-fonts-for-editorial-blocks) when installing this section.
## Home services reviews
```astro
---
import Block from "@/components/blocks/reviews/reviews-remodify.astro"
const content = {
eyebrow: "The Homeowner Experience",
title: "Home Stories.",
note: "[ Illustrative reviews for this template ]",
reviews: [
{
authorName: "Jamie R.",
role: "Sample kitchen review",
reviewText:
"The layout finally makes sense for our family. We have a place for everything, and room to cook together.",
rating: 5,
source: "google",
},
{
authorName: "Morgan T.",
role: "Sample bathroom review",
reviewText:
"We could see the choices clearly before work began. The new bathroom feels calm, bright, and much easier to use.",
rating: 5,
source: "yelp",
},
{
authorName: "Casey L.",
role: "Sample renovation review",
reviewText:
"Having one person to call helped us keep track of the details. Each stage felt clear and manageable.",
rating: 5,
source: "trustpilot",
},
{
authorName: "Alex P.",
role: "Sample interior review",
reviewText:
"The built-in storage made a real difference. Our living room feels open without losing its character.",
rating: 5,
source: "google",
},
{
authorName: "Taylor S.",
role: "Sample kitchen review",
reviewText:
"The team helped us decide where to spend and where to keep things simple. The result fits the way we live.",
rating: 5,
source: "yelp",
},
{
authorName: "Jordan K.",
role: "Sample whole-home review",
reviewText:
"The rooms feel connected now. The finishes work together, and the home still feels like ours.",
rating: 5,
source: "trustpilot",
},
],
promises: [
{
title: "Room for Your Input",
description: "Your priorities guide the work.",
},
{
title: "Clear Next Steps",
description: "Know what is happening and why.",
},
],
action: {
label: "Start Your Home Story",
href: "#contact",
},
}
---
```
```sh
bunx --bun shadcn@latest add @gnostic/reviews-remodify
```
## Choose a reviews layout
Choose a review layout that gives each quote enough room to be read. Use actual feedback and accurate attribution. A short specific quote is more useful than a generic claim.
## Pass content from Astro
Pass each review with review text, the reviewer name, and a rating. Add a portrait when you have one. Pass `source` as an icon name, such as `google` or `yelp`, when you want the platform icon. Pass `dateLabel` when you want a date line. The layout shows that text as supplied and leaves the line out when it is empty. A Google review can pass the `relativeTime` string from the API. You can also format a timestamp in the page and pass the result. The block displays supplied reviews; it does not collect, verify, or moderate them.
## Responsive layout and images
Check long quotes and attribution at narrow widths. Portrait images should have consistent crops, and a missing image needs a useful fallback. Keep the rating understandable in text where the stars alone are unclear.
## Compose the next section
Use [Logos](/blocks/logos) for brand relationships and [CTA](/blocks/cta) after evidence that supports the next action.
---
# Services Blocks for Astro
Source: https://ui.gnosticai.com/blocks/services
## Image grid
Pair each service with an image and a short explanation.
```astro
---
import Services1Block from "@/components/blocks/services/services-1.astro"
import PlaceholderImage from "@/assets/placeholder.webp"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/services-1
```
## Process
Show the service steps in the order a customer will follow.
```astro
---
import Services2Block from "@/components/blocks/services/services-2.astro"
import PlaceholderImage from "@/assets/placeholder.webp"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/services-2
```
## Overlays
Place the service message over its supporting image.
```astro
---
import Services3Block from "@/components/blocks/services/services-3.astro"
import PlaceholderImage from "@/assets/placeholder.webp"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/services-3
```
## Minimal cards
Use simple cards when a title and short description explain the offer.
```astro
---
import Services4Block from "@/components/blocks/services/services-4.astro"
import PlaceholderImage from "@/assets/placeholder.webp"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/services-4
```
## Icon grid
Give each service a small icon and a concise explanation.
```astro
---
import Services5Block from "@/components/blocks/services/services-5.astro"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/services-5
```
## Sticky sidebar
Keep the introduction beside the service cards as readers move down the section.
```astro
---
import Services6Block from "@/components/blocks/services/services-6.astro"
import PlaceholderImage from "@/assets/placeholder.webp"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/services-6
```
## Featured grid
Give one service more space than the supporting offers.
```astro
---
import Services7Block from "@/components/blocks/services/services-7.astro"
import PlaceholderImage from "@/assets/placeholder.webp"
---
```
```sh
bunx --bun shadcn@latest add @gnostic/services-7
```
## Services Portfolio
An independent section from the Portfolio template. Supply its content through props.
```astro
---
import Block from "@/components/blocks/services/services-portfolio.astro"
import asset0 from "../../../../../packages/templates/sable/site/src/assets/sable/salon-interior.png"
const content = {
eyebrow: "Time in the chair",
title: "A fresh start,\nor a small change.",
description:
"Every appointment begins with a conversation about your hair, your routine, and what you want to feel when you leave.",
image: {
src: asset0,
alt: "Warm daylight across the chairs and mirrors at Sable",
},
tags: ["Cuts", "Colour", "Styling"],
capabilities: [
"All textures welcome",
"Consultation first",
"Care you can keep up",
],
projectsLabel: "Explore the looks",
services: [
{
title: "Cut & finish",
description:
"A shape that works with your texture, finished with simple styling advice.",
icon: "scissors",
price: "From $65",
duration: "60 minutes",
},
{
title: "Colour & gloss",
description:
"A subtle refresh or a new direction. We plan the shade and upkeep together.",
icon: "palette",
price: "From $95",
duration: "90 minutes",
},
{
title: "Curls & texture",
description:
"Shape, definition, and a routine that makes room for your natural movement.",
icon: "waves",
price: "From $80",
duration: "75 minutes",
},
{
title: "Style & occasion",
description:
"A relaxed finish, a polished blow-dry, or a look for a day worth dressing up for.",
icon: "sparkles",
price: "From $45",
duration: "45 minutes",
},
],
contact: {
label: "Plan your visit",
href: "#visit",
email: "hello@example.com",
available: "Cuts · Colour · Care",
},
projectsHref: "#looks",
}
---
```
```sh
bunx --bun shadcn@latest add @gnostic/services-portfolio
```
## Visual service grid
Supply your own content. The section uses the selected project preset.
```astro
---
import Block from "@/components/blocks/services/services-visual-grid/services-visual-grid.astro"
import type { VisualServicesContent } from "@/components/blocks/services/services-visual-grid/types"
const content = {
label: "What we build",
title: "Practical AI for the Work That Slows You Down",
services: [
{
title: "Connected Workflows.",
description:
"Move requests, files, and updates between your tools without copying them by hand.",
visual: "workflow",
},
{
title: "Focused AI Agents.",
description:
"Give research and document tasks to an agent with a clear job and clear limits.",
visual: "agents",
},
{
title: "Voice Assistants.",
description:
"Handle routine call questions and booking requests, with a route to a real person.",
visual: "voice",
},
{
title: "Thoughtful Follow-up.",
description:
"Prepare useful reminders and draft replies while your team controls what goes out.",
visual: "marketing",
},
{
title: "Reports That Explain.",
description:
"Bring scattered numbers into a daily brief that shows what needs your attention.",
visual: "analytics",
},
{
title: "Knowledge Assistants.",
description:
"Help people find answers in your approved guides, with sources they can check.",
visual: "chat",
},
],
} satisfies VisualServicesContent
---
```
```sh
bunx --bun shadcn@latest add @gnostic/services-visual-grid
```
## Editorial services
Use this section for the services part of a studio site.
```astro
---
import Section from "@/components/blocks/services/services-agency.astro"
const section = {
label: "Made for spatial brands",
title: "Good work,",
accent: "clearly seen",
description:
"A considered identity, a useful website, and stories that let people see the care in your work.",
services: [
{
title: "Brand foundations",
description:
"Find the words, type, and visual language that make your practice feel like you.",
image: {
src: "/media/foldline/brand-foundations.svg",
alt: "",
},
},
{
title: "Studio websites",
description:
"Give your projects room to breathe, with clear navigation and an archive you can manage.",
image: {
src: "/media/foldline/studio-websites.svg",
alt: "",
},
},
{
title: "Project stories",
description:
"Bring drawings, photographs, and the thinking behind a space into one clear narrative.",
image: {
src: "/media/foldline/project-stories.svg",
alt: "",
},
},
{
title: "Launch support",
description:
"Put the details in place, from a project announcement to the first visitor enquiry.",
image: {
src: "/media/foldline/launch-support.svg",
alt: "",
},
},
],
}
---
```
```sh
bunx --bun shadcn@latest add @gnostic/services-agency
```
See [serif accent font setup](/docs/installation#serif-accent-fonts-for-editorial-blocks) when installing this section.
## Editorial expertise
Use this section for the expertise part of a studio site.
```astro
---
import Section from "@/components/blocks/experience/experience-agency.astro"
const section = {
label: "Our focus",
title: "Built around",
accent: "your world",
description:
"Different disciplines, connected by a belief that the details deserve to be seen.",
entries: [
{
title: "Architecture",
role: "Practices & project archives",
period: "01 / Places",
description:
"Help people understand a building through its setting, its decisions, and the way it is used.",
},
{
title: "Interiors & hospitality",
role: "Studios & places to stay",
period: "02 / Spaces",
description:
"Translate atmosphere into a clear digital experience, with useful detail alongside the images.",
},
{
title: "Furniture & objects",
role: "Makers & collections",
period: "03 / Objects",
description:
"Bring form, material, and craft into focus for the people who specify and live with your work.",
},
],
}
---
```
```sh
bunx --bun shadcn@latest add @gnostic/experience-agency
```
See [serif accent font setup](/docs/installation#serif-accent-fonts-for-editorial-blocks) when installing this section.
## Home services services
```astro
---
import Block from "@/components/blocks/services/services-remodify.astro"
const content = {
eyebrow: "Remodeling Services",
title: "Room to Grow.",
note: "[ Your home. Your next chapter. ]",
services: [
{
title: "Kitchen Remodeling",
description:
"Create a kitchen that works for busy mornings and long dinners. Plan cabinets, countertops, lighting, and storage around how you cook and gather.",
icon: "cooking-pot",
},
{
title: "Bathroom Remodeling",
description:
"Make daily routines easier with a better layout, practical storage, durable tile, and a shower or bath that suits your space.",
icon: "bath",
},
{
title: "Whole-Home Renovations",
description:
"Bring disconnected rooms together. Coordinate flooring, finishes, lighting, and layout changes with one plan for your home.",
icon: "house",
},
{
title: "Interior Updates",
description:
"Refresh the rooms you already enjoy with built-in storage, finish carpentry, new flooring, and carefully chosen fixtures.",
icon: "ruler",
},
],
action: {
label: "Talk through your ideas: (919) 555-0142",
href: "tel:+19195550142",
},
}
---
```
```sh
bunx --bun shadcn@latest add @gnostic/services-remodify
```
## Choose a services layout
Choose a services layout that matches how clients decide. A short grid can summarize a few services, while a larger image-led section can explain an involved engagement.
## Pass content from Astro
Pass service titles, descriptions, optional labels, links, and images supported by the variant. State the outcome and scope in the content. Keep contact destinations in the route data so they can change without editing the reusable block.
## Responsive layout and images
Check the order when images and text stack on small screens. Use project imagery that demonstrates the service and select a crop that preserves the useful detail. Long service names must remain readable beside any action.
## Compose the next section
Use [Content](/blocks/content) for the process, [Reviews](/blocks/reviews) for evidence, and [Contact](/blocks/contact) for the enquiry.
---
# Team Blocks for Astro
Source: https://ui.gnosticai.com/blocks/team
Introduce the people behind your work. Pass names, roles, images, and links as content props.
## Team grid
Supply your own content. The section uses the selected project preset.
```astro
---
import Block from "@/components/blocks/content/content-team-grid/content-team-grid.astro"
import type { TeamGridContent } from "@/components/blocks/content/content-team-grid/types"
const content = {
label: "The people behind the work",
title: "A Small Team. A Shared Standard.",
people: [
{
title: "Jules Mercer",
description: "Strategy & process",
image: {
src: "/media/gnotch/portrait-jules.webp",
alt: "Portrait of a smiling man in a gray sweater",
},
href: "/contact",
},
{
title: "Maya Chen",
description: "Automation & delivery",
image: {
src: "/media/gnotch/portrait-maya.webp",
alt: "Portrait of a smiling woman with her hair tied back",
},
href: "/contact",
},
{
title: "Theo Bennett",
description: "AI systems & engineering",
image: {
src: "/media/gnotch/portrait-theo.webp",
alt: "Portrait of a man in a dark knit shirt",
},
href: "/contact",
},
],
} satisfies TeamGridContent
---
```
```sh
bunx --bun shadcn@latest add @gnostic/content-team-grid
```
## Editorial team
Use this section for the team part of a studio site.
```astro
---
import Section from "@/components/blocks/team/team-agency.astro"
const section = {
label: "The studio",
title: "Different skills.",
accent: "Shared care.",
members: [
{
title: "Nora Vale",
role: "Strategy & Studio Lead",
department: "Direction",
image: {
src: "/media/foldline/nora-vale.webp",
alt: "Generated portrait of Nora Vale, a fictional Foldline team member",
},
},
{
title: "Elias Rowe",
role: "Design Director",
department: "Identity",
image: {
src: "/media/foldline/elias-rowe.webp",
alt: "Generated portrait of Elias Rowe, a fictional Foldline team member",
},
},
{
title: "Mina Park",
role: "Editorial Designer",
department: "Storytelling",
image: {
src: "/media/foldline/mina-park.webp",
alt: "Generated portrait of Mina Park, a fictional Foldline team member",
},
},
{
title: "Samir Chen",
role: "Creative Developer",
department: "Development",
image: {
src: "/media/foldline/samir-chen.webp",
alt: "Generated portrait of Samir Chen, a fictional Foldline team member",
},
},
{
title: "Jules Avery",
role: "Producer & Client Partner",
department: "Delivery",
image: {
src: "/media/foldline/jules-avery.webp",
alt: "Generated portrait of Jules Avery, a fictional Foldline team member",
},
},
],
}
---
```
```sh
bunx --bun shadcn@latest add @gnostic/team-agency
```
See [serif accent font setup](/docs/installation#serif-accent-fonts-for-editorial-blocks) when installing this section.
## Responsive layout and images
Use consistent portrait crops and supply image dimensions. Check long names,
roles, social links, and carousel controls in a narrow container. Keep focus
indicators visible when using a keyboard.
---
# UI components for Astro
Source: https://ui.gnosticai.com/components
Find a control for a task, a container for related content, or a part for page navigation. Each guide shows the Astro composition and the install command. The Preview and Code tabs use the same example file. Descriptive example names identify the feature each file demonstrates.
## Build a complete page
Start with the controls and content parts your page needs. Use [blocks](/blocks) for complete sections and [templates](/templates) for route and layout examples. Keep content in Astro props and slots so a reusable section does not depend on one site's collection or URL structure. Read the [Credits](/docs/credits) for the project foundation and design sources.
---
# Accordion for Astro
Source: https://ui.gnosticai.com/components/accordion
```astro
---
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion"
---
How do I open a question with the keyboard?
Use Tab to reach the question, then Enter or Space to open its answer.
Can the section use my site colors?
The section reads shared text, border, and focus colors from the active
theme.
How does the panel open?
The panel uses its measured height for the transition. Reduced-motion
settings shorten the animation.
```
## Installation
### Command
```sh
bunx --bun shadcn@latest add @gnostic/accordion
```
### Manual
Complete the [Installation guide](/docs/installation) first. Then copy the component files below.
Install the component packages:
```sh
bun add @data-slot/accordion
```
#### src/components/ui/accordion/accordion-content.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, hidden = true, ...props } = Astro.props
---
```
#### src/components/ui/accordion/accordion-item.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div"> & {
value: string
disabled?: boolean
}
const { class: className, value, disabled, ...props } = Astro.props
---
```
#### src/components/ui/accordion/accordion-trigger.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import ChevronDownIcon from "@lucide/astro/icons/chevron-down"
import { cn } from "cn"
type Props = HTMLAttributes<"button">
const { class: className, type = "button", ...props } = Astro.props
---
```
#### src/components/ui/accordion/accordion.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import type { AccordionProps } from "./types.ts"
type Props = HTMLAttributes<"div"> & AccordionProps
const {
class: className,
multiple,
defaultValue,
disabled,
orientation = "vertical",
loopFocus,
hiddenUntilFound,
...props
} = Astro.props
const serializedDefaultValue = Array.isArray(defaultValue)
? JSON.stringify(defaultValue)
: defaultValue
---
```
#### src/components/ui/accordion/index.ts
```ts
export { default as Accordion } from './accordion.astro'
export { default as AccordionContent } from './accordion-content.astro'
export { default as AccordionItem } from './accordion-item.astro'
export { default as AccordionTrigger } from './accordion-trigger.astro'
export type { AccordionProps } from './types.ts'
```
#### src/components/ui/accordion/types.ts
```ts
import type { AccordionOptions } from '@data-slot/accordion'
/**
* Accordion configuration rendered as data attributes.
*/
export type AccordionProps = Pick<
AccordionOptions,
| 'multiple'
| 'defaultValue'
| 'disabled'
| 'orientation'
| 'loopFocus'
| 'hiddenUntilFound'
>
```
Component classes use the preset configured during project setup. Select the same preset in the docs before copying Manual source. To change installed component classes, edit or reinstall their source. See [Theming](/docs/theming) for details.
## Usage
```ts
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion"
```
```astro
How do I open a question with the keyboard?
Use Tab to reach the question, then Enter or Space to open its answer.
```
## Composition
Arrange the parts as shown for an `Accordion`:
```text
Accordion
├── AccordionItem
│ ├── AccordionTrigger
│ └── AccordionContent
└── AccordionItem
├── AccordionTrigger
└── AccordionContent
```
## Examples
### Multiple
Add `multiple` when readers need to compare answers without closing the previous item.
```astro
---
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion"
---
Account
Manage your profile, billing details, and email preferences.
Security
Update your password, passkeys, and sign-in methods.
Notifications
Choose which product updates and alerts you want to receive.
```
### With Disabled
Set `disabled` on an `AccordionItem` when its trigger must be unavailable.
```astro
---
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion"
---
Available item
This item can be opened and closed normally.
Disabled item
This panel stays unavailable to keyboard and pointer interaction.
Another item
You can still interact with the other items in the list.
```
### With Borders
For this divided layout, put `border` on the root and `border-b last:border-b-0` on each item. The last item uses the root border as its lower edge.
```astro
---
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion"
---
Design system
Keep styles, spacing, and behavior consistent across your UI.
Accessibility
Ensure controls are readable and keyboard friendly.
Performance
Only reveal the content people need when they need it.
```
### In Card
Wrap the `Accordion` in a `Card` component.
```astro
---
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
---
FAQDo you offer support?
Yes. Support is included for all active subscriptions.
Can I cancel anytime?
Yes. You can cancel your subscription whenever you want.
Is there a free trial?
A trial is available for eligible plans and new accounts.
```
## API Reference
### AccordionProps
See the [data-slot docs](https://github.com/bejamas/data-slot/blob/main/packages/accordion/README.md) for more information on interactivity.
### Events
Dispatch these events on the accordion root. The root emits the outbound events.
#### Outbound events
| Event | Detail |
| ------------------ | --------------------- |
| `accordion:change` | `{ value: string[] }` |
#### Inbound events
| Event | Detail |
| --------------- | ------------------------------- |
| `accordion:set` | `{ value: string \| string[] }` |
Read the [installed source](/r/accordion.json) for the complete prop types.
## When to use Accordion
Group related questions with Accordion items. Give each trigger a clear question or topic and place its answer in the matching content part. Keep the item structure from the examples so the controller can connect each trigger to its panel.
## Keyboard and behavior
The data-slot controller handles trigger activation and expanded state. Use real trigger buttons so Enter and Space work. Keep essential instructions outside closed panels when the user needs them to complete a form. Test keyboard movement when items are disabled or added dynamically.
## Theme and layout
Borders separate items and the indicator rotates with `data-panel-open`. Panel height uses the controller variable, so long content can animate without a fixed height. Theme changes affect text, focus, and borders. Do not apply a second height animation to the content wrapper.
---
# Alert for Astro
Source: https://ui.gnosticai.com/components/alert
```astro
---
import CircleAlert from "@lucide/astro/icons/circle-exclamation-point"
import CircleCheck from "@lucide/astro/icons/circle-check"
import Info from "@lucide/astro/icons/info"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
const messages = [
{
variant: "default" as const,
title: "Review window opens Monday",
detail: "Add content notes to the project before the review starts.",
icon: Info,
},
{
variant: "info" as const,
title: "Preview link updated",
detail:
"Use the new link in the project summary to check the current pages.",
icon: Info,
},
{
variant: "success" as const,
title: "Content saved",
detail: "Your page changes are ready for the next review.",
icon: CircleCheck,
},
{
variant: "warning" as const,
title: "Two images need descriptions",
detail: "Add useful alt text before publishing the gallery.",
icon: CircleAlert,
},
{
variant: "error" as const,
title: "The draft could not be saved",
detail: "Keep this page open and try again when the connection returns.",
icon: CircleAlert,
},
{
variant: "destructive" as const,
title: "The upload was rejected",
detail: "Choose an image file smaller than the project limit.",
icon: CircleAlert,
},
]
---
```
#### src/components/ui/alert/alert-description.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/alert/alert-title.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/alert/alert.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import type { AlertVariants } from "./alert-variants"
import { alertVariants } from "./alert-variants"
type Props = AlertVariants & HTMLAttributes<"div">
const { class: className, variant, ...props } = Astro.props
---
```
#### src/components/ui/alert/index.ts
```ts
export { default as Alert } from "./alert.astro"
export { default as AlertAction } from "./alert-action.astro"
export { default as AlertTitle } from "./alert-title.astro"
export { default as AlertDescription } from "./alert-description.astro"
```
Component classes use the preset configured during project setup. Select the same preset in the docs before copying Manual source. To change installed component classes, edit or reinstall their source. See [Theming](/docs/theming) for details.
## Usage
```ts
import { Alert, AlertAction, AlertDescription, AlertTitle } from "@/components/ui/alert"
```
```astro
Content review is ready
Three pages have updated copy. Review the changes before publishing.
```
## Example
Use `AlertAction` when the alert should include a secondary control such as a
button.
```astro
---
import {
Alert,
AlertAction,
AlertDescription,
AlertTitle,
} from "@/components/ui/alert"
import { Button } from "@/components/ui/button"
---
Content review is ready
Three page descriptions changed since the last review.
```
## Composition
Arrange the parts as shown for an `Alert`:
```text
Alert
├── Icon
├── AlertTitle
├── AlertDescription
└── AlertAction
```
## Notes
- Use `Alert` for inline feedback inside the page flow.
- Use `variant="error"` for a failed action and `variant="warning"` for a
condition that needs attention. `destructive` uses the selected preset's
destructive recipe; `error` keeps the Gnostic status treatment.
- For destructive confirmation flows, use
[Alert Dialog](/components/alert-dialog) instead.
## API Reference
Read the [installed source](/r/alert.json) for the complete prop types.
## When to use Alert
Use an Alert near the content that needs attention. Put the main fact in `AlertTitle`, then put the cause or next step in `AlertDescription`. An optional icon is a direct child. Add `AlertAction` only when a short action helps the reader resolve the message. An Alert stays in the page layout; it is not a toast service.
## Keyboard and behavior
The root has `role="alert"` by default. Reserve an interrupting announcement for an urgent change. For an ordinary static note, pass an appropriate role such as `role="note"`. The component has no dismissal or notification queue script. A button inside an alert keeps its native keyboard behavior.
## Theme and layout
Choose `info`, `success`, `warning`, or `error` to match the message. `default` and `destructive` use the selected preset's recipes. Status variants keep their Gnostic treatment and use the shared semantic tokens. State the result in text as well as color. Shared semantic tokens control the border, icon, and tint in both color modes; the neutral variant suits general page guidance.
---
# Alert Dialog for Astro
Source: https://ui.gnosticai.com/components/alert-dialog
```astro
---
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
---
Review draft removal
Remove this draft?
Removing this draft deletes its saved content. Export a copy first if
you need to keep it.
CancelRemove draft
```
## Installation
### Command
```sh
bunx --bun shadcn@latest add @gnostic/alert-dialog
```
### Manual
Complete the [Installation guide](/docs/installation) first. Then copy the component files below.
Install the component packages:
```sh
bun add @data-slot/alert-dialog
```
#### src/components/ui/alert-dialog/alert-dialog-action.astro
```astro
---
import type { ComponentProps } from "astro/types"
import { Button } from "../button"
type Props = ComponentProps
const { ...props } = Astro.props
---
```
#### src/components/ui/alert-dialog/alert-dialog-cancel.astro
```astro
---
import type { ComponentProps } from "astro/types"
import { Button } from "../button/index.ts"
type Props = ComponentProps
const { variant = "outline", ...props } = Astro.props
---
```
#### src/components/ui/alert-dialog/alert-dialog-content.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import AlertDialogOverlay from "./alert-dialog-overlay.astro"
import AlertDialogPortal from "./alert-dialog-portal.astro"
import type { AlertDialogContentProps } from "./types.ts"
type Props = HTMLAttributes<"div"> & AlertDialogContentProps
const { class: className, size = "default", style, ...props } = Astro.props
---
```
#### src/components/ui/alert-dialog/alert-dialog-description.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"p">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/alert-dialog/alert-dialog-footer.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/alert-dialog/alert-dialog-header.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/alert-dialog/alert-dialog-media.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/alert-dialog/alert-dialog-overlay.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, style, ...props } = Astro.props
---
```
#### src/components/ui/alert-dialog/alert-dialog-portal.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/alert-dialog/alert-dialog-title.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"h2">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/alert-dialog/alert-dialog-trigger.astro
```astro
---
import type { ComponentProps } from "astro/types"
import { Button } from "../button/index.ts"
type Props = ComponentProps
const { ...props } = Astro.props
---
```
#### src/components/ui/alert-dialog/alert-dialog.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import type { AlertDialogProps } from "./types.ts"
type Props = HTMLAttributes<"div"> & AlertDialogProps
const {
class: className,
defaultOpen,
closeOnClickOutside,
closeOnEscape,
lockScroll,
...props
} = Astro.props
---
```
#### src/components/ui/alert-dialog/index.ts
```ts
export { default as AlertDialog } from './alert-dialog.astro'
export { default as AlertDialogAction } from './alert-dialog-action.astro'
export { default as AlertDialogCancel } from './alert-dialog-cancel.astro'
export { default as AlertDialogContent } from './alert-dialog-content.astro'
export { default as AlertDialogDescription } from './alert-dialog-description.astro'
export { default as AlertDialogFooter } from './alert-dialog-footer.astro'
export { default as AlertDialogHeader } from './alert-dialog-header.astro'
export { default as AlertDialogMedia } from './alert-dialog-media.astro'
export { default as AlertDialogOverlay } from './alert-dialog-overlay.astro'
export { default as AlertDialogPortal } from './alert-dialog-portal.astro'
export { default as AlertDialogTitle } from './alert-dialog-title.astro'
export { default as AlertDialogTrigger } from './alert-dialog-trigger.astro'
export type { AlertDialogProps, AlertDialogContentProps } from './types.ts'
```
#### src/components/ui/alert-dialog/types.ts
```ts
import type { AlertDialogOptions } from '@data-slot/alert-dialog'
/**
* Alert dialog configuration rendered as data attributes.
*/
export type AlertDialogProps = Pick<
AlertDialogOptions,
'defaultOpen' | 'closeOnClickOutside' | 'closeOnEscape' | 'lockScroll'
>
/**
* Width of the alert dialog panel.
*/
export type AlertDialogContentProps = {
/**
* Panel width.
*
* @default "default"
*/
size?: 'default' | 'sm'
}
```
Component classes use the preset configured during project setup. Select the same preset in the docs before copying Manual source. To change installed component classes, edit or reinstall their source. See [Theming](/docs/theming) for details.
## Usage
```ts
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
```
```astro
Review draft removalRemove this draft?
Removing this draft deletes its saved content. Export a copy first if you need to keep it.
CancelRemove draft
```
## Composition
Arrange the parts as shown for an `AlertDialog`:
```text
AlertDialog
├── AlertDialogTrigger
└── AlertDialogContent
├── AlertDialogHeader
│ ├── AlertDialogMedia
│ ├── AlertDialogTitle
│ └── AlertDialogDescription
└── AlertDialogFooter
├── AlertDialogCancel
└── AlertDialogAction
```
## Notes
- Use `AlertDialog` for irreversible or high-risk actions, not routine inline
confirmations.
- Keep `AlertDialogTitle` and `AlertDialogDescription` inside
`AlertDialogContent` so screen readers announce the dialog context clearly.
- Pair the destructive path with `AlertDialogAction` and the safe path with
`AlertDialogCancel`.
- Use `size="sm"` on `AlertDialogContent` for compact confirmations and
`AlertDialogMedia` when the dialog needs an icon or visual cue.
## API Reference
### AlertDialogProps
### AlertDialogContentProps
See the [data-slot docs](https://github.com/bejamas/data-slot/blob/main/packages/alert-dialog/README.md) for more information on interactivity.
### Events
Dispatch these events on the alert dialog root. The root emits the outbound events.
#### Outbound events
| Event | Detail |
| --------------------- | ------------------- |
| `alert-dialog:change` | `{ open: boolean }` |
#### Inbound events
| Event | Detail |
| ------------------ | ------------------- |
| `alert-dialog:set` | `{ open: boolean }` |
Read the [installed source](/r/alert-dialog.json) for the complete prop types.
## When to use Alert Dialog
Use Alert Dialog before an action whose effect is hard to reverse. Put the specific result in the title and explanation. Keep the cancel control available and label the action with a verb such as “Remove project”. The action button alone does not perform the operation.
## Keyboard and behavior
The existing alert-dialog controller manages modal focus and dismissal. Confirm that focus returns to the trigger after cancellation. Run the operation from your own form or script only after the user chooses the action. Test Escape and focus order in the finished page.
## Theme and layout
The surface shares dialog colors, border, and footer spacing. Keep copy short enough to fit a narrow screen and allow it to wrap. Destructive button color is useful, but the wording must still explain the outcome without color.
---
# Aspect Ratio for Astro
Source: https://ui.gnosticai.com/components/aspect-ratio
```astro
---
import { Image } from "astro:assets"
import { AspectRatio } from "@/components/ui/aspect-ratio"
import image from "@/assets/wizard/wizard-on-moon.jpeg"
---
```
## Installation
### Command
```sh
bunx --bun shadcn@latest add @gnostic/aspect-ratio
```
### Manual
Complete the [Installation guide](/docs/installation) first. Then copy the component files below.
No extra packages are required.
#### src/components/ui/aspect-ratio/aspect-ratio.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import type { AspectRatioProps } from "./types.ts"
/** Div attributes pass through. */
type Props = HTMLAttributes<"div"> & AspectRatioProps
const { class: className, ratio, style: styleProp, ...props } = Astro.props
if (!Number.isFinite(ratio) || ratio <= 0) {
throw new RangeError("AspectRatio needs a finite ratio greater than zero.")
}
const style =
typeof styleProp === "string"
? `--ratio: ${ratio}; ${styleProp}`
: {
"--ratio": ratio,
...(styleProp ? styleProp : {}),
}
---
```
#### src/components/ui/aspect-ratio/index.ts
```ts
export { default as AspectRatio } from './aspect-ratio.astro'
export type { AspectRatioProps } from './types.ts'
```
#### src/components/ui/aspect-ratio/types.ts
```ts
/**
* Props for a box that keeps a fixed width-to-height ratio.
* Div attributes such as `class` and `id` pass through on the component.
*/
export interface AspectRatioProps {
/**
* Width divided by height.
*
* Common values include `16 / 9`, `4 / 3`, `1`, `9 / 16`, and `21 / 9`.
*/
ratio: number
}
```
Component classes use the preset configured during project setup. Select the same preset in the docs before copying Manual source. To change installed component classes, edit or reinstall their source. See [Theming](/docs/theming) for details.
## Usage
```ts
import { AspectRatio } from "@/components/ui/aspect-ratio"
```
```astro
```
Pass width divided by height. Common values are `16 / 9`, `4 / 3`, `1`, `9 / 16`, and `21 / 9`.
## Example
### Aspect Ratio with Toggle Group
Pair the aspect ratio component with a toggle group to allow users to select different views of the same image.
```astro
---
import { Image } from "astro:assets"
import { AspectRatio } from "@/components/ui/aspect-ratio"
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"
import image from "@/assets/wizard/wizard-looking-out-of-cave.png"
const ratios = {
"16:9": 16 / 9,
"4:3": 4 / 3,
"1:1": 1,
"9:16": 9 / 16,
"21:9": 21 / 9,
} as const
---
```
## Notes
- Set `ratio` to width divided by height. Portrait frames use values below `1`.
- Give slotted media `size-full` and `object-cover` when it should fill the box.
- The container is `position: relative` so absolutely positioned children can fill it.
## API Reference
### AspectRatioProps
Read the [installed source](/r/aspect-ratio.json) for the complete prop types.
## When to use Aspect Ratio
Use Aspect Ratio when width is fluid but height must follow a known proportion. It reserves space before images load and keeps grids aligned.
## Keyboard and behavior
Aspect Ratio does not crop or scale content by itself. Pair it with `object-cover` or layout utilities on the child.
## Theme and layout
The box inherits width from its parent. Constrain width with utilities such as `max-w-md` when a portrait frame should stay narrow.
---
# Attachment for Astro
Source: https://ui.gnosticai.com/components/attachment
```astro
---
import FileText from "@lucide/astro/icons/file-text"
import X from "@lucide/astro/icons/x"
import {
Attachment,
AttachmentAction,
AttachmentActions,
AttachmentContent,
AttachmentDescription,
AttachmentMedia,
AttachmentTitle,
} from "@/components/ui/attachment"
---
sales-dashboard.pdfPDF · 2.4 MB
```
## Installation
### Command
```sh
bunx --bun shadcn@latest add @gnostic/attachment
```
### Manual
Complete the [Installation guide](/docs/installation) first. Then copy the component files below.
No extra packages are required.
#### src/components/ui/attachment/attachment-action.astro
```astro
---
/**
* Icon or text action on an attachment. Renders a ghost {@link Button} by default.
*/
import type { ComponentProps } from "astro/types"
import { cn } from "cn"
import { Button } from "../button/index.ts"
import type { AttachmentActionProps } from "./types.ts"
type Props = ComponentProps & AttachmentActionProps
const {
class: className,
variant = "ghost",
size = "icon-xs",
...props
} = Astro.props
---
```
#### src/components/ui/attachment/attachment-actions.astro
```astro
---
/**
* Aligns one or more attachment actions at the end of the card.
*/
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/attachment/attachment-content.astro
```astro
---
/**
* Groups the attachment title and description.
*/
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/attachment/attachment-description.astro
```astro
---
/**
* Secondary metadata for an attachment, such as type, size, or status text.
*/
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"span">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/attachment/attachment-group.astro
```astro
---
/**
* Horizontally scrollable row of attachments with snap points and edge fade.
*/
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/attachment/attachment-media.astro
```astro
---
/**
* Media slot for an icon, spinner, or image preview on an attachment.
*/
import type { HTMLAttributes } from "astro/types"
import type { VariantProps } from "class-variance-authority"
import { cn } from "cn"
import { attachmentMediaVariants } from "./attachment-variants.ts"
import type { AttachmentMediaProps } from "./types.ts"
type Props = HTMLAttributes<"div"> &
AttachmentMediaProps &
VariantProps
const { class: className, variant = "icon", ...props } = Astro.props
---
```
#### src/components/ui/attachment/attachment-title.astro
```astro
---
/**
* Primary label for an attachment, usually the file name.
* Shimmers while the root attachment is uploading or processing.
*/
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"span">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/attachment/attachment-trigger.astro
```astro
---
/**
* Full-card control behind attachment actions. Use `as` for a link or other element.
*/
import type { HTMLAttributes } from "astro/types"
import type { HTMLTag, Polymorphic } from "astro/types"
import { cn } from "cn"
type Props = Polymorphic<{ as: T }> &
HTMLAttributes
const {
as: Tag = "href" in Astro.props ? "a" : "button",
class: className,
...props
} = Astro.props
const elementProps: Record = { ...props }
elementProps.type = Tag === "button" ? elementProps.type || "button" : undefined
---
```
#### src/components/ui/attachment/attachment-variants.ts
```ts
import { cva } from 'class-variance-authority'
/** Root attachment layout, size, and orientation recipes. */
export const attachmentVariants = cva("relative flex w-fit max-w-full min-w-0 shrink-0 flex-wrap rounded-2xl border bg-card text-card-foreground transition-colors focus-within:ring-1 focus-within:ring-ring/30 has-[>a,>button]:hover:bg-muted/50 data-[state=error]:border-destructive/30 data-[state=idle]:border-dashed group/attachment", {
defaultVariants: {
orientation: 'horizontal',
size: 'default',
},
variants: {
orientation: {
horizontal: "min-w-40 items-center",
vertical: "w-24 has-data-[slot=attachment-content]:w-30 flex-col",
},
size: {
default: "gap-2 has-data-[slot=attachment-content]:px-2.5 has-data-[slot=attachment-content]:py-2 has-data-[slot=attachment-media]:p-2 text-sm",
sm: "gap-2.5 has-data-[slot=attachment-content]:px-2 has-data-[slot=attachment-content]:py-1.5 has-data-[slot=attachment-media]:p-1.5 text-xs",
xs: "gap-1.5 has-data-[slot=attachment-content]:px-1.5 has-data-[slot=attachment-content]:py-1 has-data-[slot=attachment-media]:p-1 text-xs rounded-xl",
},
},
})
/** Media slot recipes for icon and image attachments. */
export const attachmentMediaVariants = cva(
"bg-muted text-foreground w-10 rounded-lg group-data-[size=sm]/attachment:w-8 group-data-[size=xs]/attachment:w-7 group-data-[size=xs]/attachment:rounded-md [&_svg:not([class*='size-'])]:size-4 group-data-[size=xs]/attachment:[&_svg:not([class*='size-'])]:size-3.5 group-data-[orientation=vertical]/attachment:w-full group-data-[orientation=vertical]/attachment:[&_svg:not([class*='size-'])]:size-6 group-data-[orientation=vertical]/attachment:*:data-[slot=spinner]:size-6! group-data-[state=error]/attachment:bg-destructive/10 group-data-[state=error]/attachment:text-destructive relative flex aspect-square shrink-0 items-center justify-center overflow-hidden [&_svg]:pointer-events-none",
{
defaultVariants: {
variant: 'icon',
},
variants: {
variant: {
icon: '',
image: "opacity-60 group-data-[state=idle]/attachment:opacity-100 group-data-[state=done]/attachment:opacity-100 *:[img]:aspect-square *:[img]:w-full *:[img]:object-cover",
},
},
},
)
```
#### src/components/ui/attachment/attachment.astro
```astro
---
/**
* Root container for a file or image attachment.
* Compose media, content, actions, and an optional full-card trigger inside it.
*
* @see https://ui.shadcn.com/docs/components/base/attachment
*/
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import { attachmentVariants } from "./attachment-variants.ts"
import type { AttachmentProps } from "./types.ts"
type Props = HTMLAttributes<"div"> & AttachmentProps
const {
class: className,
state = "done",
size = "default",
orientation = "horizontal",
...props
} = Astro.props
---
```
#### src/components/ui/attachment/index.ts
```ts
/** Attachment parts follow https://ui.shadcn.com/docs/components/base/attachment */
export { default as Attachment } from './attachment.astro'
export { default as AttachmentAction } from './attachment-action.astro'
export { default as AttachmentActions } from './attachment-actions.astro'
export { default as AttachmentContent } from './attachment-content.astro'
export { default as AttachmentDescription } from './attachment-description.astro'
export { default as AttachmentGroup } from './attachment-group.astro'
export { default as AttachmentMedia } from './attachment-media.astro'
export { default as AttachmentTitle } from './attachment-title.astro'
export { default as AttachmentTrigger } from './attachment-trigger.astro'
export type {
AttachmentActionProps,
AttachmentMediaProps,
AttachmentProps,
AttachmentState,
} from './types.ts'
```
#### src/components/ui/attachment/types.ts
```ts
import type { ButtonProps } from '../button/types.ts'
/** Upload lifecycle state for an attachment card. */
export type AttachmentState =
| 'idle'
| 'uploading'
| 'processing'
| 'error'
| 'done'
/**
* Props for the root attachment container.
* HTML attributes such as `class` and `id` pass through on the element.
*/
export interface AttachmentProps {
/**
* Upload state. Drives border treatment and title shimmer while in progress.
*
* @default done
*/
state?: AttachmentState
/**
* Attachment density.
*
* @default default
*/
size?: 'default' | 'sm' | 'xs'
/**
* Lay media beside or above the text content.
*
* @default horizontal
*/
orientation?: 'horizontal' | 'vertical'
}
/**
* Props for the attachment media slot.
* HTML attributes such as `class` pass through on the element.
*/
export interface AttachmentMediaProps {
/**
* Whether the slot holds an icon or an image preview.
*
* @default icon
*/
variant?: 'icon' | 'image'
}
/**
* Props for an attachment action control.
* Button attributes such as `aria-label`, `variant`, and `disabled` pass through.
*/
export interface AttachmentActionProps {
/**
* Button size for the icon action.
*
* @default icon-xs
*/
size?: ButtonProps['size']
}
```
Component classes use the preset configured during project setup. Select the same preset in the docs before copying Manual source. To change installed component classes, edit or reinstall their source. See [Theming](/docs/theming) for details.
The `Attachment` parts display a file or image attachment, its media, name, and metadata, with optional actions and upload state. Use them for files and images in chat composers, message threads, and upload lists.
## Usage
```ts
import {
Attachment,
AttachmentAction,
AttachmentActions,
AttachmentContent,
AttachmentDescription,
AttachmentMedia,
AttachmentTitle,
} from "@/components/ui/attachment"
```
```astro
---
import FileText from "@lucide/astro/icons/file-text"
import X from "@lucide/astro/icons/x"
import {
Attachment,
AttachmentAction,
AttachmentActions,
AttachmentContent,
AttachmentDescription,
AttachmentMedia,
AttachmentTitle,
} from "@/components/ui/attachment"
---
sales-dashboard.pdfPDF · 2.4 MB
```
## Composition
```text
Attachment
├── AttachmentMedia
├── AttachmentContent
│ ├── AttachmentTitle
│ └── AttachmentDescription
├── AttachmentActions
│ └── AttachmentAction
└── AttachmentTrigger
```
Use `AttachmentGroup` to lay out multiple attachments in a scrollable row:
```text
AttachmentGroup
├── Attachment
└── Attachment
```
## Image
Set `variant="image"` on `AttachmentMedia` and render an `` or `Image` inside it. Use `orientation="vertical"` to stack the media above the content.
```astro
---
import X from "@lucide/astro/icons/x"
import { Image } from "astro:assets"
import {
Attachment,
AttachmentAction,
AttachmentActions,
AttachmentContent,
AttachmentGroup,
AttachmentDescription,
AttachmentMedia,
AttachmentTitle,
} from "@/components/ui/attachment"
import winterLandscapeOrion from "@/assets/images/winter-landscape-orion.png"
import winterLandcapeTheta from "@/assets/images/winter-landscape-theta.png"
import futuristicStorm from "@/assets/images/futuristic-storm.png"
const images = [
{
src: futuristicStorm,
alt: "Futuristic storm",
title: "futuristic-storm.png",
description: "PNG · 820 KB",
},
{
src: winterLandscapeOrion,
alt: "Winter landscape",
title: "winter-landscape-orion.png",
description: "PNG · 820 KB",
},
{
src: winterLandcapeTheta,
alt: "Winter landscape",
title: "winter-landscape-theta.png",
description: "PNG · 820 KB",
},
]
---
{images.map((image) => (
{image.title}{image.description}
))}
```
## States
Set `state` on `Attachment` to reflect the upload lifecycle. `uploading` and `processing` shimmer the title, and `error` switches to a destructive treatment. Keep the failure reason in `AttachmentDescription` so the state is not conveyed by color alone.
```astro
---
import FileCode from "@lucide/astro/icons/file-code"
import FileText from "@lucide/astro/icons/file-text"
import {
Attachment,
AttachmentContent,
AttachmentDescription,
AttachmentMedia,
AttachmentTitle,
} from "@/components/ui/attachment"
import { Spinner } from "@/components/ui/spinner"
---
```
## Sizes
Use `size` to switch between `default`, `sm`, and `xs`.
```astro
---
import FileText from "@lucide/astro/icons/file-text"
import {
Attachment,
AttachmentContent,
AttachmentDescription,
AttachmentMedia,
AttachmentTitle,
} from "@/components/ui/attachment"
---
```
## Group
Wrap attachments in `AttachmentGroup` to lay them out in a horizontally scrollable, snapping row with an edge fade.
```astro
---
import FileText from "@lucide/astro/icons/file-text"
import ImageIcon from "@lucide/astro/icons/image"
import {
Attachment,
AttachmentContent,
AttachmentDescription,
AttachmentGroup,
AttachmentMedia,
AttachmentTitle,
} from "@/components/ui/attachment"
---
workspace.pngPNG · 820 KBresearch-summary.pdfPDF · 1.8 MBrelease-notes.mdMarkdown · 24 KB
```
## Trigger
Add an `AttachmentTrigger` to make the whole card open a link or dialog. It fills the card behind the actions, so the actions stay clickable. Give icon-only actions and the trigger an `aria-label` that names the file and the action.
```astro
---
import FileText from "@lucide/astro/icons/file-text"
import X from "@lucide/astro/icons/x"
import {
Attachment,
AttachmentAction,
AttachmentActions,
AttachmentContent,
AttachmentDescription,
AttachmentMedia,
AttachmentTitle,
AttachmentTrigger,
} from "@/components/ui/attachment"
import { Lightbox, LightboxContent } from "@/components/ui/lightbox"
---
Attention is All You NeedPDF · arXiv:1706.03762
Attention Is All You Need
{" "}
(Vaswani et al., arXiv:1706.03762)
```
For a dialog or lightbox, put the attachment inside its root and set
`data-slot="dialog-trigger"` on `AttachmentTrigger`. The dialog controller binds
the trigger within that root. No ID lookup or custom click handler is needed.
```astro
```
## API Reference
### AttachmentProps
### AttachmentMediaProps
### AttachmentActionProps
Read the [installed source](/r/attachment.json) for the complete prop types.
## Theme and layout
Attachment uses shared component recipes and semantic colors. Choose the size and orientation that fit the surrounding form or file list. Keep file names readable and actions distinct from the preview. Use [Field](/components/field) for input labels and messages; the attachment view does not perform an upload.
---
# Avatar for Astro
Source: https://ui.gnosticai.com/components/avatar
```astro
---
import {
Avatar,
AvatarFallback,
AvatarGroup,
AvatarImage,
} from "@/components/ui/avatar"
import { agentAvatars } from "@/lib/agent-avatars"
---
SVSVMRSVSVSV
```
## Installation
### Command
```sh
bunx --bun shadcn@latest add @gnostic/avatar
```
### Manual
Complete the [Installation guide](/docs/installation) first. Then copy the component files below.
No extra packages are required.
#### src/components/ui/avatar/avatar-badge.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"span">
const { class: className, ...props } = Astro.props
---
svg]:hidden group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2 group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2", className)}
{...props}
>
```
#### src/components/ui/avatar/avatar-fallback.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/avatar/avatar-group-count.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/avatar/index.ts
```ts
export { default as Avatar } from "./avatar.astro"
export { default as AvatarBadge } from "./avatar-badge.astro"
export { default as AvatarFallback } from "./avatar-fallback.astro"
export { default as AvatarGroup } from "./avatar-group.astro"
export { default as AvatarGroupCount } from "./avatar-group-count.astro"
export { default as AvatarImage } from "./avatar-image.astro"
```
Component classes use the preset configured during project setup. Select the same preset in the docs before copying Manual source. To change installed component classes, edit or reinstall their source. See [Theming](/docs/theming) for details.
## Usage
```ts
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
```
```astro
TM
```
## Composition
Arrange the parts as shown for an `Avatar`:
```text
Avatar
├── AvatarImage
├── AvatarFallback
└── AvatarBadge
```
Arrange the parts as shown for an `AvatarGroup`:
```text
AvatarGroup
├── Avatar
│ ├── AvatarImage
│ ├── AvatarFallback
│ └── AvatarBadge
├── Avatar
│ ├── AvatarImage
│ ├── AvatarFallback
│ └── AvatarBadge
└── AvatarGroupCount
```
## Examples
### Fallback
Use `AvatarFallback` when an image is unavailable or intentionally omitted.
```astro
---
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
---
MR
```
### Group
Use `AvatarGroup` when you need overlapping participant or collaborator lists.
```astro
---
import {
Avatar,
AvatarFallback,
AvatarGroup,
AvatarGroupCount,
AvatarImage,
} from "@/components/ui/avatar"
import { agentAvatars } from "@/lib/agent-avatars"
---
SVTM+3
```
## Notes
- Always include `AvatarFallback` so initials or placeholder content remain
visible when the image fails to load.
- Use size variants on `Avatar` instead of custom width and height classes when
possible.
## API Reference
Read the [installed source](/r/avatar.json) for the complete prop types.
## When to use Avatar
Use Avatar beside a person or team name. Put AvatarImage and AvatarFallback inside the same root. Use initials or a short mark for the fallback, and choose one size for a row of related people.
## Keyboard and behavior
Supply meaningful image alternative text if the image conveys identity that is absent from nearby text. Use empty alt text when the adjacent name already supplies it. This Astro version does not include Base UI image loading state; a broken image URL does not automatically switch to the fallback.
## Theme and layout
The root clips content to its rounded shape and the fallback uses muted colors. Check long initials and transparent logos in both modes. Resolve an absent image in your data before rendering when you need a reliable fallback.
---
# Badge for Astro
Source: https://ui.gnosticai.com/components/badge
```astro
---
import BadgeCheck from "@lucide/astro/icons/badge-check"
import {
Badge,
type BadgeVariantProps,
badgeVariants,
} from "@/components/ui/badge"
const badgeSizes = [
"sm",
"default",
"lg",
] as const satisfies BadgeVariantProps["size"][]
const variants = [
"default",
"secondary",
"success",
"warning",
"info",
"destructive",
"error",
"outline",
"ghost",
"link",
] as const satisfies BadgeVariantProps["variant"][]
const badges = variants.flatMap((variant) =>
badgeSizes.map((size) => ({ size, variant })),
)
---
{badges.map(({ size, variant }) => (
{variant}
))}
```
## Installation
### Command
```sh
bunx --bun shadcn@latest add @gnostic/badge
```
### Manual
Complete the [Installation guide](/docs/installation) first. Then copy the component files below.
No extra packages are required.
#### src/components/ui/badge/badge-variants.ts
```ts
import { cva, type VariantProps } from 'class-variance-authority'
import { cn } from 'cn'
const badgeStyles = cva("font-sans focus-visible:ring-ring focus-visible:ring-offset-background relative inline-flex shrink-0 items-center justify-center gap-1 rounded-sm border border-transparent font-medium whitespace-nowrap transition-shadow outline-none focus-visible:ring-2 focus-visible:ring-offset-1 disabled:pointer-events-none disabled:opacity-64 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='opacity-'])]:opacity-80 [&_svg:not([class*='size-'])]:size-3.5 sm:[&_svg:not([class*='size-'])]:size-3 [button&,a&]:cursor-pointer [button&,a&]:pointer-coarse:after:absolute [button&,a&]:pointer-coarse:after:size-full [button&,a&]:pointer-coarse:after:min-h-11 [button&,a&]:pointer-coarse:after:min-w-11", {
defaultVariants: {
size: 'default',
variant: 'default',
},
variants: {
size: {
default: "h-5.5 min-w-5.5 px-[calc(--spacing(1)-1px)] text-sm sm:h-4.5 sm:min-w-4.5 sm:text-xs",
lg: "h-6.5 min-w-6.5 px-[calc(--spacing(1.5)-1px)] text-base sm:h-5.5 sm:min-w-5.5 sm:text-sm",
sm: "h-5 min-w-5 rounded-[.25rem] px-[calc(--spacing(1)-1px)] text-xs sm:h-4 sm:min-w-4 sm:text-[.625rem]",
},
variant: {
error: 'bg-destructive/8 text-destructive-foreground dark:bg-destructive/16',
info: 'bg-info/8 text-info-foreground dark:bg-info/16',
success: 'bg-success/8 text-success-foreground dark:bg-success/16',
warning: 'bg-warning/8 text-warning-foreground dark:bg-warning/16',
ghost: "text-foreground hover:bg-accent border-transparent",
link: "text-primary border-transparent underline-offset-4 hover:underline",
default: "bg-primary text-primary-foreground [button&,a&]:hover:bg-primary/90",
destructive: "bg-destructive [button&,a&]:hover:bg-destructive/90 text-white",
outline: "border-input bg-background text-foreground dark:bg-input/32 [button&,a&]:hover:bg-accent/50 dark:[button&,a&]:hover:bg-input/48",
secondary: "bg-secondary text-secondary-foreground [button&,a&]:hover:bg-secondary/90",
},
},
})
export const badgeVariants = (...args: Parameters) =>
cn(badgeStyles(...args))
export type BadgeVariantProps = VariantProps
```
#### src/components/ui/badge/badge.astro
```astro
---
import type { HTMLTag, Polymorphic } from "astro/types"
import { cn } from "cn"
import { badgeVariants, type BadgeVariantProps } from "./badge-variants"
type Props = Polymorphic<{ as: Tag }> & BadgeVariantProps
const {
as: Tag = "span",
class: className,
variant = "default",
size = "default",
...props
} = Astro.props
---
```
#### src/components/ui/badge/index.ts
```ts
export { badgeVariants, type BadgeVariantProps } from "./badge-variants"
export { default as Badge } from "./badge.astro"
```
Component classes use the preset configured during project setup. Select the same preset in the docs before copying Manual source. To change installed component classes, edit or reinstall their source. See [Theming](/docs/theming) for details.
## Usage
```ts
import { Badge } from "@/components/ui/badge"
```
```astro
Badge
```
### Link
Use the polymorphic `as` prop to render the badge as a link element.
```astro
---
import { Badge } from "@/components/ui/badge"
---
Badge
```
### Polymorphic
`Badge` is strict polymorphic. Pass `as` to change the rendered element and
use attributes for that element.
```astro
ActionDocs
```
## Notes
- Use variants first before adding custom classes.
- `Badge` works well for status labels, counts, and small inline metadata.
## With an icon
Put a check icon in the badge. The badge sets the icon size.
```astro
---
import Check from "@lucide/astro/icons/check"
import { Badge } from "@/components/ui/badge"
---
Verified
Verified
Verified
```
## With a count
Add `rounded-full` when the badge shows a notification count.
```astro
---
import { Badge } from "@/components/ui/badge"
---
8
3
12
```
## API Reference
Read the [installed source](/r/badge.json) for the complete prop types.
## When to use Badge
Use Badge for a short fact attached to another object. Keep the text brief and choose a semantic variant only when the meaning is clear. The size prop changes density without requiring a different component.
## Keyboard and behavior
A badge is a label, not an action by default. Do not depend on its color alone to communicate status. If you make it a link through its supported element props, use a clear destination label and keep the focus style.
## Theme and layout
The variants share semantic color tokens with alerts and buttons. Test the small size with the actual label text. Long sentences belong in a description or alert instead of a badge.
---
# Banner for Astro
Source: https://ui.gnosticai.com/components/banner
## Usage
```ts
import { Banner, BannerContainer } from "@/components/ui/banner"
```
```astro
Banner Title
Banner Description
```
`BannerContainer` renders a close button by default. Set `showClose={false}` to
hide it.
```astro
Browse the latest component examples and installation guides.
```
## Installation
### Command
```sh
bunx --bun shadcn@latest add @gnostic/banner
```
### Manual
Complete the [Installation guide](/docs/installation) first. Then copy the component files below.
No extra packages are required.
#### src/components/ui/banner/banner-container.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import XIcon from "@lucide/astro/icons/x"
import { cn } from "cn"
type Props = HTMLAttributes<"div"> & {
showClose?: boolean
}
const { class: className, showClose = true, ...props } = Astro.props
---
{showClose && (
)}
```
#### src/components/ui/banner/banner.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "cn"
type Props = HTMLAttributes<"aside"> &
VariantProps & {
storageKey?: string
}
const variants = cva("@container relative flex items-center py-2", {
variants: {
variant: {
default: "bg-foreground text-background w-full",
floating: "bg-background mx-auto my-2 w-[calc(100%-2rem)] max-w-[calc(var(--container,1280px)-2rem)] overflow-hidden rounded-lg border shadow-sm",
},
},
defaultVariants: {
variant: "default",
},
})
const { class: className, variant, storageKey, ...props } = Astro.props
---
```
#### src/components/ui/banner/index.ts
```ts
export { default as Banner } from "./banner.astro"
export { default as BannerContainer } from "./banner-container.astro"
```
Component classes use the preset configured during project setup. Select the same preset in the docs before copying Manual source. To change installed component classes, edit or reinstall their source. See [Theming](/docs/theming) for details.
```astro
---
import { Banner, BannerContainer } from "@/components/ui/banner"
---
Launch
New component docs are ready.
```
## Notes
- The default banner spans its available width.
- Set `variant="floating"` for a bar with an inset surface.
## API Reference
Read the [installed source](/r/banner.json) for the complete prop types.
## When to use Banner
Place a Banner near the top of the page for a service notice or current announcement. Use the default or floating layout to suit the page shell, then add message and action parts through slots.
## Keyboard and behavior
A dismissal control needs a clear accessible name. If you use `storageKey`, the client behavior can retain the dismissed state; change the key when the notice itself changes. Important information must also remain available elsewhere after dismissal.
## Theme and layout
Check long text beside the action at a narrow width. Shared background and border tokens keep the banner consistent with the page, but a persistent banner must not cover a focused control or heading.
---
# Breadcrumb for Astro
Source: https://ui.gnosticai.com/components/breadcrumb
```astro
---
import {
Breadcrumb,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbList,
BreadcrumbPage,
BreadcrumbSeparator,
} from "@/components/ui/breadcrumb"
---
HomeComponentsBreadcrumb
```
## Installation
### Command
```sh
bunx --bun shadcn@latest add @gnostic/breadcrumb
```
### Manual
Complete the [Installation guide](/docs/installation) first. Then copy the component files below.
No extra packages are required.
#### src/components/ui/breadcrumb/types.ts
````ts
export type BreadcrumbMenuProps = {
/**
* The items to display in the breadcrumb menu.
* @example
* ```ts
* [
* { label: "Home", href: "/" },
* { label: "Components", href: "/components" },
* { label: "Breadcrumb", href: "/components/breadcrumb" },
* ]
* ```
*/
items: {
label: string
href: string
}[]
}
````
#### src/components/ui/breadcrumb/breadcrum-menu.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import {
DropdownMenu,
DropdownMenuItem,
DropdownMenuContent,
DropdownMenuTrigger,
} from "../dropdown-menu"
import type { BreadcrumbMenuProps } from "./types"
import Ellipsis from "@lucide/astro/icons/ellipsis"
import { cn } from "cn"
import { buttonVariants } from "../button"
type Props = HTMLAttributes<"div"> & BreadcrumbMenuProps
const { items, class: className, ...props } = Astro.props satisfies Props
---
{items.map((item) => (
{item.label}
))}
```
#### src/components/ui/breadcrumb/breadcrumb-ellipsis.astro
```astro
---
import type { HTMLAttributes, HTMLTag, Polymorphic } from "astro/types"
import Ellipsis from "@lucide/astro/icons/ellipsis"
import { cn } from "cn"
type Props = Polymorphic<{ as: Tag }>
const { as: Tag = "span", class: className, ...props } = Astro.props
---
svg]:size-4", className)}
{...props}
>
More
```
#### src/components/ui/breadcrumb/breadcrumb-item.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"li">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/breadcrumb/breadcrumb-link.astro
```astro
---
import type { HTMLTag, Polymorphic } from "astro/types"
import { cn } from "cn"
type Props = Polymorphic<{ as: Tag }>
const { as: Tag = "a", class: className, ...props } = Astro.props
---
```
#### src/components/ui/breadcrumb/breadcrumb-list.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"ol">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/breadcrumb/breadcrumb-page.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"span">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/breadcrumb/breadcrumb-separator.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import ChevronRight from "@lucide/astro/icons/chevron-right"
import { cn } from "cn"
type Props = HTMLAttributes<"li">
const { class: className, ...props } = Astro.props
---
svg]:size-4", className)}
{...props}
>
```
#### src/components/ui/breadcrumb/breadcrumb.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
type Props = HTMLAttributes<"nav">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/breadcrumb/index.ts
```ts
export { default as Breadcrumb } from './breadcrumb.astro'
export { default as BreadcrumbEllipsis } from './breadcrumb-ellipsis.astro'
export { default as BreadcrumbItem } from './breadcrumb-item.astro'
export { default as BreadcrumbLink } from './breadcrumb-link.astro'
export { default as BreadcrumbList } from './breadcrumb-list.astro'
export { default as BreadcrumbPage } from './breadcrumb-page.astro'
export { default as BreadcrumbSeparator } from './breadcrumb-separator.astro'
export { default as BreadcrumbMenu } from './breadcrum-menu.astro'
export type { BreadcrumbMenuProps } from './types'
```
Component classes use the preset configured during project setup. Select the same preset in the docs before copying Manual source. To change installed component classes, edit or reinstall their source. See [Theming](/docs/theming) for details.
## Usage
```ts
import {
Breadcrumb,
BreadcrumbEllipsis,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbList,
BreadcrumbPage,
BreadcrumbSeparator,
} from "@/components/ui/breadcrumb"
```
```astro
HomeCurrent Page
```
## Composition
Arrange the parts as shown for a `Breadcrumb`:
```text
Breadcrumb
└── BreadcrumbList
├── BreadcrumbItem
│ └── BreadcrumbLink
├── BreadcrumbSeparator
├── BreadcrumbItem
│ └── BreadcrumbLink
├── BreadcrumbSeparator
└── BreadcrumbItem
└── BreadcrumbPage
```
## Examples
### Basic
```astro
---
import {
Breadcrumb,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbList,
BreadcrumbPage,
BreadcrumbSeparator,
} from "@/components/ui/breadcrumb"
---
Home/Components/Data
```
### With Menu
The ellipse can be a trigger for a [dropdown menu](/components/dropdown-menu), to truncate the breadcrumb trail, while preserving the full trail in a menu.
```astro
---
import {
Breadcrumb,
BreadcrumbMenu,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbList,
BreadcrumbPage,
BreadcrumbSeparator,
type BreadcrumbMenuProps,
} from "@/components/ui/breadcrumb"
const items = [
{ label: "Components", href: "#" },
{ label: "Subfolder", href: "#" },
{ label: "Links", href: "#" },
] satisfies BreadcrumbMenuProps["items"]
---
HomeBreadcrumb
```
## API Reference
### BreadcrumbMenuProps
## When to use Breadcrumb
Build a Breadcrumb from list items and links ordered from the parent section to the current page. Use BreadcrumbPage for the final item. The trail describes the site hierarchy; it does not need to reproduce browser history.
## Keyboard and behavior
Links retain native keyboard and browser behavior. Name multiple navigation regions so users can tell them apart. Separators are visual punctuation and should not add extra spoken content.
## Theme and layout
Muted text and hover styles follow the theme. Let long labels wrap or shorten them with meaningful wording. An ellipsis only displays a gap; add a menu yourself if hidden ancestors must be available.
---
# Button for Astro
Source: https://ui.gnosticai.com/components/button
```astro
---
import ArrowUpRight from "@lucide/astro/icons/arrow-up-right"
import { Button } from "@/components/ui/button"
---
```
## Installation
### Command
```sh
bunx --bun shadcn@latest add @gnostic/button
```
### Manual
Complete the [Installation guide](/docs/installation) first. Then copy the component files below.
No extra packages are required.
#### src/components/ui/button/button-variants.ts
```ts
import { cva, type VariantProps } from 'class-variance-authority'
export const buttonVariants = cva(
"font-sans focus-visible:ring-ring focus-visible:ring-offset-background relative inline-flex shrink-0 cursor-pointer items-center justify-center gap-2 rounded-lg border text-base font-medium whitespace-nowrap transition-shadow outline-none before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] focus-visible:ring-2 focus-visible:ring-offset-1 disabled:opacity-64 sm:text-sm pointer-coarse:after:absolute pointer-coarse:after:size-full pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 [&_svg]:pointer-events-none [&_svg]:-mx-0.5 [&_svg]:shrink-0 [&_svg:not([class*='opacity-'])]:opacity-80 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 group/button disabled:pointer-events-none data-loading:text-transparent data-loading:select-none",
{
compoundVariants: [
{
variant: 'outline',
size: ['icon', 'icon-xs', 'icon-sm', 'icon-lg', 'icon-xl'],
class: "",
},
],
defaultVariants: {
size: 'default',
variant: 'default',
},
variants: {
size: {
default: "h-9 px-[calc(--spacing(3)-1px)] sm:h-8",
icon: "size-9 sm:size-8",
'icon-lg': "size-10 sm:size-9",
'icon-sm': "size-8 sm:size-7",
'icon-xl': "size-11 sm:size-10 [&_svg:not([class*='size-'])]:size-5 sm:[&_svg:not([class*='size-'])]:size-4.5",
'icon-xs': "size-7 rounded-md before:rounded-[calc(var(--radius-md)-1px)] sm:size-6 not-in-data-[slot=input-group]:[&_svg:not([class*='size-'])]:size-4 sm:not-in-data-[slot=input-group]:[&_svg:not([class*='size-'])]:size-3.5",
lg: "h-10 px-[calc(--spacing(3.5)-1px)] sm:h-9",
sm: "h-8 gap-1.5 px-[calc(--spacing(2.5)-1px)] sm:h-7",
xl: "h-11 px-[calc(--spacing(4)-1px)] text-lg sm:h-10 sm:text-base [&_svg:not([class*='size-'])]:size-5 sm:[&_svg:not([class*='size-'])]:size-4.5",
xs: "h-7 gap-1 rounded-md px-[calc(--spacing(2)-1px)] text-sm before:rounded-[calc(var(--radius-md)-1px)] sm:h-6 sm:text-xs [&_svg:not([class*='size-'])]:size-4 sm:[&_svg:not([class*='size-'])]:size-3.5",
},
variant: {
glass: "border-white/24 border bg-white/14 text-white hover:bg-white/18 before:bg-white/0 relative backdrop-blur-sm before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:transition-[background-color] before:duration-300 before:ease-in-out hover:before:bg-white/8",
surface: "border-border bg-card text-card-foreground hover:bg-accent",
'destructive-outline':
"border-input bg-popover text-destructive-foreground hover:border-destructive/32 hover:bg-destructive/4 data-pressed:border-destructive/32 data-pressed:bg-destructive/4 *:data-[slot=button-loading-indicator]:text-foreground dark:bg-input/32 shadow-xs/5 not-dark:bg-clip-padding not-disabled:not-active:not-data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] dark:not-disabled:before:shadow-[0_-1px_--theme(--color-white/2%)] dark:not-disabled:not-active:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)] [:disabled,:active,[data-pressed]]:shadow-none",
default: "border-primary bg-primary text-primary-foreground shadow-primary/24 hover:bg-primary/90 data-pressed:bg-primary/90 *:data-[slot=button-loading-indicator]:text-primary-foreground shadow-xs not-disabled:inset-shadow-[0_1px_--theme(--color-white/16%)] [:active,[data-pressed]]:inset-shadow-[0_1px_--theme(--color-black/8%)] [:disabled,:active,[data-pressed]]:shadow-none",
destructive: "border-destructive bg-destructive shadow-destructive/24 hover:bg-destructive/90 data-pressed:bg-destructive/90 text-white shadow-xs not-disabled:inset-shadow-[0_1px_--theme(--color-white/16%)] *:data-[slot=button-loading-indicator]:text-white [:active,[data-pressed]]:inset-shadow-[0_1px_--theme(--color-black/8%)] [:disabled,:active,[data-pressed]]:shadow-none",
ghost: "text-foreground hover:bg-accent data-pressed:bg-accent *:data-[slot=button-loading-indicator]:text-foreground border-transparent",
link: "text-foreground *:data-[slot=button-loading-indicator]:text-foreground border-transparent underline-offset-4 hover:underline data-pressed:underline",
outline: "border-input bg-popover text-foreground hover:bg-accent/50 data-pressed:bg-accent/50 *:data-[slot=button-loading-indicator]:text-foreground dark:bg-input/32 dark:data-pressed:bg-input/64 dark:hover:bg-input/64 shadow-xs/5 not-dark:bg-clip-padding not-disabled:not-active:not-data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] dark:not-disabled:before:shadow-[0_-1px_--theme(--color-white/2%)] dark:not-disabled:not-active:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)] [:disabled,:active,[data-pressed]]:shadow-none",
secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/90 data-pressed:bg-secondary/90 *:data-[slot=button-loading-indicator]:text-secondary-foreground [:active,[data-pressed]]:bg-secondary/80 border-transparent",
},
},
},
)
export type ButtonVariantProps = VariantProps
```
#### src/components/ui/button/button.astro
```astro
---
import type { HTMLTag, Polymorphic } from "astro/types"
import { Spinner } from "../spinner"
import { cn } from "cn"
import { buttonVariants } from "./button-variants"
import type { ButtonProps } from "./types"
type Props = Polymorphic<{ as: Tag }> &
ButtonProps
const {
as: Tag = "href" in Astro.props ? "a" : "button",
class: className,
variant = "default",
size = "default",
withLoader = false,
...props
} = Astro.props
// Props validates the selected tag at the call site. The render tag is dynamic.
const elementProps: Record = {
...(Tag === "button" ? { type: "button" as const } : {}),
...props,
}
---
{withLoader && (
)}
```
#### src/components/ui/button/index.ts
```ts
export { buttonVariants, type ButtonVariantProps } from "./button-variants"
export { default as Button } from "./button.astro"
```
#### src/components/ui/button/types.ts
```ts
import type { HTMLTag } from 'astro/types'
import type { ButtonVariantProps } from './button-variants'
export interface ButtonProps extends ButtonVariantProps {
/**
* The HTML tag to render the button as.
*
* @default 'button'
*/
as?: HTMLTag
/**
* Add the built-in loading indicator. It will remain hidden until the button's `data-loading` attribute is set to `true`.
*
* @default false
*/
withLoader?: boolean
}
```
Component classes use the preset configured during project setup. Select the same preset in the docs before copying Manual source. To change installed component classes, edit or reinstall their source. See [Theming](/docs/theming) for details.
## Usage
```ts
import { Button } from "@/components/ui/button"
```
You can also import `buttonVariants` to reuse button styles on other HTML elements.
Pass `size` and `variant` to the helper. It supplies the classes for the
project preset selected during installation. No extra data attributes are
needed to select those styles.
Keep a trigger's existing `data-slot` when you style another component this way.
```astro
---
import { buttonVariants } from "@/components/ui/button"
---
```
### Link
Use [Link](/components/link) for a page path, an external URL, a phone number, or an email address. `Button` can render an anchor when you only need button styles on a simple href.
```astro
---
import { Button } from "@/components/ui/button"
---
```
### Polymorphic
`Button` is polymorphic via `as`. Pass `as` to change the rendered element and
use the relevant attributes for that element.
```astro
```
## Examples
### Sizes
```astro
---
import ArrowUpRight from "@lucide/astro/icons/arrow-up-right"
import { Button } from "@/components/ui/button"
---
```
### Default
```astro
---
import { Button } from "@/components/ui/button"
---
```
### Ghost
```astro
---
import { Button } from "@/components/ui/button"
---
```
### Outline
```astro
---
import { Button } from "@/components/ui/button"
---
```
### Glass
The glass variant uses a translucent fill and a backdrop blur. Put the button on a photo so the image shows through the control.
```astro
---
import { Image } from "astro:assets"
import { Button } from "@/components/ui/button"
import city from "@/assets/images/futuristic-city.png"
---
```
### Secondary
```astro
---
import { Button } from "@/components/ui/button"
---
```
### Destructive
```astro
---
import { Button } from "@/components/ui/button"
---
```
### Destructive Outline
```astro
---
import { Button } from "@/components/ui/button"
import Trash from "@lucide/astro/icons/trash"
---
```
### Link
```astro
---
import { Button } from "@/components/ui/button"
---
```
### With Icon
The spacing between the icon and the text is automatically adjusted based on the size of the button. You do not need any margin on the icon.
```astro
---
import GitBranch from "@lucide/astro/icons/git-branch"
import { Button } from "@/components/ui/button"
---
```
### Icon only
```astro
---
import Flame from "@lucide/astro/icons/flame"
import { Button } from "@/components/ui/button"
---
```
### Rounded
Use the `rounded-full` class to make the button rounded.
```astro
---
import ArrowUp from "@lucide/astro/icons/arrow-up"
import { Button } from "@/components/ui/button"
---
```
### Loading (Built-in)
Use the `withLoader` prop to show a built-in loading indicator. Then just set the `data-loading` attribute to show a loading indicator.
```astro
---
import { Button } from "@/components/ui/button"
---
```
### Loading (Custom)
Pass a custom loading indicator by adding the `button-loading-indicator` slot.
:::note
To show a loading indicator without replacing the content, don't set a slot name.
:::
```astro
---
import { Button } from "@/components/ui/button"
import LoaderIcon from "@lucide/astro/icons/loader"
---
```
## Sizes and states
```astro
---
import { Button, type ButtonVariantProps } from "@/components/ui/button"
const variants: ButtonVariantProps["variant"][] = [
"default",
"secondary",
"outline",
"ghost",
"destructive",
"destructive-outline",
"link",
"glass",
"surface",
]
---
{variants.map((variant) => (
))}
```
## API Reference
### ButtonProps
Read the [installed source](/r/button.json) for the complete prop types.
## When to use Button
Use a button for a page action, such as saving a form. Use [Link](/components/link) for a destination. The default slot holds the label and optional icon. Set `type="button"` for actions inside a form that must not submit it.
## Keyboard and behavior
A native button supports Enter and Space. A link supports Enter and normal browser link actions. Give an icon-only button an `aria-label`. The `withLoader` option and `data-loading` attribute change the display; your code must start the work, prevent repeat requests when needed, and report the result.
## Theme and layout
The variants use the shared primary, secondary, and destructive tokens. Keep the default variant for the main action and use outline or ghost for nearby controls. A class override can change one button without changing the site palette. The component does not require a client controller for normal form submission or navigation.
---
# Button Group for Astro
Source: https://ui.gnosticai.com/components/button-group
```astro
---
import { Button } from "@/components/ui/button"
import {
ButtonGroup,
ButtonGroupSeparator,
ButtonGroupText,
} from "@/components/ui/button-group"
---
100%
```
## Installation
### Command
```sh
bunx --bun shadcn@latest add @gnostic/button-group
```
### Manual
Complete the [Installation guide](/docs/installation) first. Then copy the component files below.
No extra packages are required.
#### src/components/ui/button-group/button-group-separator.astro
```astro
---
import type { ComponentProps } from "astro/types"
import { cn } from "cn"
import { Separator } from "../separator"
type Props = ComponentProps
const { class: className, orientation = "vertical", ...props } = Astro.props
---
```
#### src/components/ui/button-group/button-group-text.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/button-group/button-group-variants.ts
```ts
import { cva, type VariantProps } from 'class-variance-authority'
export const buttonGroupVariants = cva(
'dark:*:[[data-slot=separator]:has(~button:hover):not(:has(~[data-slot=separator]~[data-slot]:hover)),[data-slot=separator]:has(~[data-slot][aria-pressed=true]):not(:has(~[data-slot=separator]~[data-slot][aria-pressed=true]))]:before:bg-input/64 dark:*:[button:hover~[data-slot=separator]:not([data-slot]:hover~[data-slot=separator]~[data-slot=separator]),[data-slot][aria-pressed=true]~[data-slot=separator]:not([data-slot][aria-pressed=true]~[data-slot=separator]~[data-slot=separator])]:before:bg-input/64 flex w-fit *:focus-visible:z-1 *:has-focus-visible:z-1 has-[>[data-slot=button-group]]:gap-2',
{
defaultVariants: {
orientation: 'horizontal',
},
variants: {
orientation: {
horizontal:
'*:data-slot:has-[~[data-slot]]:rounded-e-none *:data-slot:has-[~[data-slot]]:border-e-0 *:data-slot:has-[~[data-slot]]:before:rounded-e-none *:data-slot:not-data-[slot=separator]:has-[~[data-slot]]:before:inset-e-[-0.5px] *:pointer-coarse:after:min-w-auto *:[[data-slot]~[data-slot]]:rounded-s-none *:[[data-slot]~[data-slot]]:border-s-0 *:[[data-slot]~[data-slot]]:before:rounded-s-none *:[[data-slot]~[data-slot]:not([data-slot=separator])]:before:inset-s-[-0.5px]',
vertical:
'flex-col *:data-slot:has-[~[data-slot]]:rounded-b-none *:data-slot:has-[~[data-slot]]:border-b-0 *:data-slot:has-[~[data-slot]]:before:rounded-b-none *:data-slot:not-data-[slot=separator]:has-[~[data-slot]]:before:bottom-[-0.5px] *:data-slot:not-data-[slot=separator]:has-[~[data-slot]]:before:hidden dark:*:first:before:block dark:*:last:before:hidden *:pointer-coarse:after:min-h-auto *:[[data-slot]~[data-slot]]:rounded-t-none *:[[data-slot]~[data-slot]]:border-t-0 *:[[data-slot]~[data-slot]]:before:rounded-t-none *:[[data-slot]~[data-slot]:not([data-slot=separator])]:before:top-[-0.5px]',
},
},
},
)
export type ButtonGroupVariantProps = VariantProps
```
#### src/components/ui/button-group/button-group.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import { buttonGroupVariants } from "./button-group-variants.ts"
import type { ButtonGroupProps } from "./types.ts"
/** Div attributes pass through. Give the group an accessible name. */
type Props = HTMLAttributes<"div"> & ButtonGroupProps
const { class: className, orientation = "horizontal", ...props } = Astro.props
---
```
#### src/components/ui/button-group/index.ts
```ts
export { default as ButtonGroup } from './button-group.astro'
export { default as ButtonGroupSeparator } from './button-group-separator.astro'
export { default as ButtonGroupText } from './button-group-text.astro'
export { buttonGroupVariants } from './button-group-variants.ts'
export type { ButtonGroupProps } from './types.ts'
```
#### src/components/ui/button-group/types.ts
```ts
/**
* Props for a joined set of buttons.
* Div attributes such as `class`, `id`, and `aria-label` pass through.
* Place each button directly inside the group.
*/
export interface ButtonGroupProps {
/**
* Direction of the joined controls.
*
* @default "horizontal"
*/
orientation?: 'horizontal' | 'vertical'
}
```
Component classes use the preset configured during project setup. Select the same preset in the docs before copying Manual source. To change installed component classes, edit or reinstall their source. See [Theming](/docs/theming) for details.
## Usage
```astro
---
import {
ButtonGroup,
ButtonGroupSeparator,
ButtonGroupText,
} from "@/components/ui/button-group"
import { Button } from "@/components/ui/button"
---
```
```astro index.astro wrap lineNumbers
```
Set `orientation="vertical"` for a column. `ButtonGroupText` adds a label. `ButtonGroupSeparator` adds a divider. A horizontal group uses a vertical separator.
## Composition
Place the parts directly inside `ButtonGroup`:
```text
ButtonGroup
├── Button
├── ButtonGroupSeparator
├── Button
└── ButtonGroupText
```
`ButtonGroupSeparator` is optional. Its default orientation is vertical, which fits a horizontal group. Set `orientation="horizontal"` on the separator when the group is vertical.
## API Reference
### ButtonGroupProps
Div attributes such as `class`, `id`, and `aria-label` pass through.
`ButtonGroupSeparator` accepts [Separator](/components/separator) attributes such as `class` and `orientation`. `ButtonGroupText` accepts div attributes such as `class`.
Read the [installed source](/r/button-group.json) for the component source.
## When to use Button Group
Use Button Group when several buttons act on the same content and should read as one control. Put the group label in `aria-label` when nearby text does not name the group. Each button keeps its own label. Give an icon-only button an accessible name.
## Keyboard and behavior
The group uses `role="group"`. Each button keeps its own native keyboard behavior. This layout does not add arrow-key navigation or a pressed state. Use [Toggle Group](/components/toggle-group) when the visitor keeps one option pressed.
## Theme and layout
The outer buttons keep rounded corners. The inner edges join. Keep button sizes equal so the shared border stays even. Check visible focus around the shared borders, especially when a button is disabled.
---
# Card for Astro
Source: https://ui.gnosticai.com/components/card
```astro
---
import { Button } from "@/components/ui/button"
import {
Card,
CardAction,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card"
---
Client site handoff
Review the content and access details before the site handoff.
The page copy is approved. Two image descriptions still need review.
```
## Installation
### Command
```sh
bunx --bun shadcn@latest add @gnostic/card
```
### Manual
Complete the [Installation guide](/docs/installation) first. Then copy the component files below.
No extra packages are required.
#### src/components/ui/card/card-action.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/card/card-content.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/card/card-frame-action.astro
```astro
---
/**
* Header action for a framed card. Place it after the title and description.
*/
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/card/card-frame-description.astro
```astro
---
/**
* Supporting text under a framed card title.
*/
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/card/card-frame-footer.astro
```astro
---
/**
* Footer band for a framed card. Body actions stay in CardFooter.
*/
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/card/card-frame-header.astro
```astro
---
/**
* Header grid for a framed card.
* An action in the third slot sits on the right.
*/
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/card/card-frame-title.astro
```astro
---
/**
* Title for a framed card header. Size matches the Coss frame title.
*/
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/card/card-frame.astro
```astro
---
/**
* Framed card shell from Coss UI.
* The muted fill sits on a pseudo-element so the inner card can clip into the border.
*/
import type { HTMLTag, Polymorphic } from "astro/types"
import { cn } from "cn"
import type { CardFrameProps } from "./types.ts"
type Props = Polymorphic<{ as: Tag }> &
CardFrameProps
const { as: Tag = "div", class: className, ...props } = Astro.props
---
```
#### src/components/ui/card/card-header.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/card/card-title.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/card/card.astro
```astro
---
import type { HTMLTag, Polymorphic } from "astro/types"
import { cn } from "cn"
import type { CardProps } from "./types.ts"
type Props = Polymorphic<{ as: Tag }> & CardProps
const {
as: Tag = "div",
class: className,
size = "default",
...props
} = Astro.props
---
img:first-child]:pt-0 data-[size=sm]:[--card-spacing:--spacing(4)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)] *:[img:first-child]:rounded-t-2xl *:[img:last-child]:rounded-b-2xl group/card", className)}
{...props}
>
```
#### src/components/ui/card/index.ts
```ts
export { default as Card } from './card.astro'
export type { CardFrameProps, CardProps } from './types.ts'
export { default as CardAction } from './card-action.astro'
export { default as CardContent } from './card-content.astro'
export { default as CardDescription } from './card-description.astro'
export { default as CardFooter } from './card-footer.astro'
export { default as CardFrame } from './card-frame.astro'
export { default as CardFrameAction } from './card-frame-action.astro'
export { default as CardFrameDescription } from './card-frame-description.astro'
export { default as CardFrameFooter } from './card-frame-footer.astro'
export { default as CardFrameHeader } from './card-frame-header.astro'
export { default as CardFrameTitle } from './card-frame-title.astro'
export { default as CardHeader } from './card-header.astro'
export { default as CardTitle } from './card-title.astro'
```
#### src/components/ui/card/types.ts
```ts
import type { HTMLTag } from 'astro/types'
/** Root card container spacing and polymorphic element. */
export interface CardProps {
/**
* The HTML tag for the card root.
*
* @default 'div'
*/
as?: HTMLTag
/**
* Section inset scale through `--card-spacing`.
*
* @default 'default'
*/
size?: 'default' | 'sm'
}
/** Framed card shell with optional polymorphic root. */
export interface CardFrameProps {
/**
* The HTML tag for the frame root.
*
* @default 'div'
*/
as?: HTMLTag
}
```
Component classes use the preset configured during project setup. Select the same preset in the docs before copying Manual source. To change installed component classes, edit or reinstall their source. See [Theming](/docs/theming) for details.
## Usage
```ts
import {
Card,
CardAction,
CardContent,
CardDescription,
CardFooter,
CardFrame,
CardHeader,
CardTitle,
} from "@/components/ui/card"
```
```astro
Card TitleCard DescriptionCard Action
Card Content
Card Footer
```
### Polymorphic props
:::note
`Card` and `CardFrame` accept an `as` prop to change their root HTML element.
Both use `div` by default. Use `as="article"` for an article or `as="a"` with
`href` to make the whole card a link without an extra wrapper.
These roots supply layout and styling, so they can use different tags. Their
inner parts keep their existing tags. See the [polymorphic props rule](/docs#polymorphic-props)
for components that require a specific element.
Pass the selected element's attributes directly to the component. `as` takes a
tag name, with no callback or child cloning. A card link must not contain other
links, buttons, or other interactive controls. Keep a container root when the
card has several actions.
:::
```astro
Project summary
Review the project scope and schedule.
View projects
```
## Spacing
`--card-spacing` controls the section insets in a
`Card`. Use `size="sm"` for less spacing, or set the variable on the card:
```astro
Card content
```
`CardFrame` uses the same variable for the horizontal padding in its header
and footer. Their vertical padding stays at `1rem`. The frame and its inner
card each have their own spacing value.
## Composition
Arrange the parts as shown for a `Card`:
```text
Card
├── CardHeader
│ ├── CardTitle
│ ├── CardDescription
│ └── CardAction
├── CardContent
└── CardFooter
CardFrame
├── CardFrameHeader
│ ├── CardFrameTitle
│ ├── CardFrameDescription
│ └── CardFrameAction
├── Card
│ ├── CardContent
│ └── CardFooter (inside frame)
└── CardFrameFooter (outside frame)
```
## Examples
### Card frame
`CardFrame` keeps its Gnostic frame styling with every preset. Its colors follow
the selected theme. The inner `Card` uses the selected preset’s Card styles.
`CardFrame` is the framed card shell. Put the title and the description in `CardFrameHeader`. The inner `Card` is the body.
```astro
---
import {
Card,
CardContent,
CardFrame,
CardFrameDescription,
CardFrameHeader,
CardFrameTitle,
} from "@/components/ui/card"
---
Create project
Check the page content and image notes before handoff.
Card content goes here.
```
### Card frame with footer
Put the title and the description in `CardFrameHeader`. Put the buttons in `CardFooter`.
```astro
---
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import {
Field,
FieldLabel,
FieldContent,
FieldGroup,
} from "@/components/ui/field"
import {
Card,
CardContent,
CardFooter,
CardFrame,
CardFrameDescription,
CardFrameHeader,
CardFrameTitle,
} from "@/components/ui/card"
---
Create project
Check the page content and image notes before handoff.
Project nameProject description
```
### Card frame with framed footer
Put the `CardFrameFooter` outside the `Card` to create a framed footer.
```astro
---
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import {
Field,
FieldLabel,
FieldContent,
FieldGroup,
} from "@/components/ui/field"
import {
Card,
CardContent,
CardFooter,
CardFrame,
CardFrameDescription,
CardFrameHeader,
CardFrameTitle,
CardFrameFooter,
} from "@/components/ui/card"
---
Create project
Check the page content and image notes before handoff.
Project nameProject description
```
### Image Card
Add an image before the card header to create a card with an image.
```astro
---
import { Image } from "astro:assets"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card"
import image from "@/assets/placeholder.webp"
---
Image CardCard with media in the top slot.
The first child image automatically gets top rounding behavior.
```
## Sizes and states
```astro
---
import {
Card,
CardHeader,
CardTitle,
CardDescription,
CardContent,
CardFooter,
} from "@/components/ui/card"
import { Button } from "@/components/ui/button"
---
{(["default", "sm"] as const).map((size) => (
Review {size === "sm" ? "summary" : "details"}A card with {size} spacing.
Keep the project files, content notes, and next action together.
))}
```
## API Reference
### CardProps
### CardFrameProps
Read the [installed source](/r/card.json) for the complete prop types.
## When to use Card
Use Card for one related unit of content, such as a project summary or account setting. Compose a header, content, and footer through Astro slots. `CardContent` is the body part. A `CardAction` belongs in the header when it acts on the whole card.
## Keyboard and behavior
Card adds no custom click or keyboard behavior. With `as="a"` and `href`, the root uses native link behavior. Give card links a visible keyboard focus style, as in the example above. For a card with several actions, keep the default container and use links and buttons inside it. A title does not make the entire surface interactive. Check the title element in your page heading order, and give each action a label that identifies its purpose.
## Theme and layout
The default surface uses shared card colors, a border, and a small shadow. Section parts own their padding. Use `size="sm"` or `--card-spacing` for a denser composition. A CardFrame adds a surrounding surface; its spacing is independent of the inner card. Long titles and footers with several buttons need a narrow-screen check.
---
# Carousel for Astro
Source: https://ui.gnosticai.com/components/carousel
```astro
---
import {
Carousel,
CarouselContent,
CarouselItem,
CarouselNext,
CarouselPrevious,
} from "@/components/ui/carousel"
---
1
2
3
4
5
```
## Installation
### Command
```sh
bunx --bun shadcn@latest add @gnostic/carousel
```
### Manual
Complete the [Installation guide](/docs/installation) first. Then copy the component files below.
Install the component packages:
```sh
bun add @data-slot/core embla-carousel
```
#### src/components/ui/carousel/carousel-content.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import type { CarouselContentProps } from "./types.ts"
type Props = HTMLAttributes<"div"> & CarouselContentProps
const {
class: className,
style: styleProp,
gap = "1rem",
viewportClass,
...props
} = Astro.props
const style =
typeof styleProp === "string"
? `--carousel-gap: ${gap}; ${styleProp}`
: {
"--carousel-gap": gap,
...styleProp,
}
---
```
#### src/components/ui/carousel/carousel-dots.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div"> & {
label?: string
}
const { class: className, label = "Slide navigation", ...props } = Astro.props
---
```
#### src/components/ui/carousel/carousel-item.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/carousel/carousel-layer.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/carousel/carousel-next.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import ChevronRightIcon from "@lucide/astro/icons/chevron-right"
import { cn } from "cn"
import { buttonVariants, type ButtonVariantProps } from "../button/index.ts"
type Props = Omit, "type"> & ButtonVariantProps
const {
class: className,
variant = "outline",
size = "icon-sm",
disabled,
...props
} = Astro.props
---
```
#### src/components/ui/carousel/carousel-parallax.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/carousel/carousel-previous.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import ChevronLeftIcon from "@lucide/astro/icons/chevron-left"
import { cn } from "cn"
import { buttonVariants, type ButtonVariantProps } from "../button/index.ts"
type Props = Omit, "type"> & ButtonVariantProps
const {
class: className,
variant = "outline",
size = "icon-sm",
disabled,
...props
} = Astro.props
---
```
#### src/components/ui/carousel/carousel.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import type { EmblaOptionsType } from "embla-carousel"
import { cn } from "cn"
import type { CarouselOptions } from "./types.ts"
type Props = CarouselOptions & HTMLAttributes<"div">
const {
class: className,
carouselOptions,
orientation = "horizontal",
effects,
...props
} = Astro.props
const resolvedOpts: EmblaOptionsType = {
loop: true,
...carouselOptions,
axis: orientation === "horizontal" ? "x" : "y",
}
---
```
#### src/components/ui/carousel/carousel.ts
```ts
import {
clearRootBinding,
getRootBinding,
getRoots,
hasRootBinding,
setRootBinding,
} from '@data-slot/core'
import EmblaCarousel, {
type EmblaCarouselType,
type EmblaOptionsType,
type EmblaPluginType,
} from 'embla-carousel'
import { setupCarouselEffects } from './effects.ts'
import type { CarouselEffects, CarouselOptions } from './types.ts'
const ROOT_SLOT = 'carousel'
/** Browser-only setup options. Plugin functions stay in the client script. */
export type CarouselControllerOptions = Omit<
CarouselOptions,
'carouselOptions'
> & {
/** Browser options can include callbacks and DOM elements. */
carouselOptions?: EmblaOptionsType
plugins?: EmblaPluginType[]
/** Optional ancestor that receives arrow keys, such as a dialog panel. */
keyboardTarget?: HTMLElement
}
export interface CarouselController {
readonly root: HTMLElement
readonly api: EmblaCarouselType
destroy(): void
}
/** Read an existing instance without private element or window properties. */
export function getCarouselApi(root: Element): EmblaCarouselType | undefined {
return getRootBinding(root, ROOT_SLOT)?.api
}
/** Bind each unbound carousel in the scope. */
export function create(scope: ParentNode = document): CarouselController[] {
return getRoots(scope, ROOT_SLOT)
.filter((root) => !hasRootBinding(root, ROOT_SLOT))
.map((root) => createCarousel(root))
}
function readOptions(value: string | undefined): T {
try {
const parsed = JSON.parse(value ?? '{}')
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
? parsed
: ({} as T)
} catch {
return {} as T
}
}
const getDetails = (api: EmblaCarouselType) => ({
api,
canScrollPrev: api.canScrollPrev(),
canScrollNext: api.canScrollNext(),
selectedScrollSnap: api.selectedScrollSnap(),
scrollSnapList: api.scrollSnapList(),
})
const emit = (
root: HTMLElement,
type: 'carousel:init' | 'carousel:select',
api: EmblaCarouselType,
) => {
root.dispatchEvent(
new CustomEvent(type, {
detail: getDetails(api),
}),
)
}
const syncButton = (button: Element | null, enabled: boolean) => {
if (!(button instanceof HTMLButtonElement)) {
return
}
if (button.dataset.manualDisabled === 'true') {
button.disabled = true
return
}
button.disabled = !enabled
}
/** Bind one carousel. Repeated calls return its existing controller. */
export function createCarousel(
root: HTMLElement,
options: CarouselControllerOptions = {},
): CarouselController {
const existing = getRootBinding(root, ROOT_SLOT)
if (existing) return existing
const ownedElements = (selector: string) =>
Array.from(root.querySelectorAll(selector)).filter(
(element) => element.closest('[data-slot="carousel"]') === root,
)
const viewport = ownedElements(
'[data-slot="carousel-content"]',
)[0]
const prevButtons = ownedElements(
'[data-slot="carousel-previous"]',
)
const nextButtons = ownedElements(
'[data-slot="carousel-next"]',
)
const dotGroups = ownedElements('[data-slot="carousel-dots"]')
if (!(viewport instanceof HTMLElement)) {
throw new Error('Carousel requires CarouselContent.')
}
const orientation =
options.orientation ?? root.dataset.orientation ?? 'horizontal'
root.dataset.orientation = orientation
const api = EmblaCarousel(
viewport,
{
loop: true,
...readOptions(root.dataset.carouselOptions),
...options.carouselOptions,
axis: orientation === 'vertical' ? 'y' : 'x',
},
options.plugins,
)
const reducedMotion = root.ownerDocument.defaultView!.matchMedia(
'(prefers-reduced-motion: reduce)',
)
const syncDots = (count: number, selected: number) => {
for (const group of dotGroups) {
let buttons = Array.from(
group.querySelectorAll(
'[data-slot="carousel-dot"]',
),
)
if (buttons.length !== count) {
const template =
group.querySelector('template')
const prototype = template?.content.querySelector('button')
if (!prototype) continue
const focusedIndex = buttons.findIndex(
(button) => button === document.activeElement,
)
buttons.forEach((button) => button.remove())
buttons = Array.from({ length: count }, (_, index) => {
const button = prototype.cloneNode(
true,
) as HTMLButtonElement
button.dataset.carouselSnap = String(index)
button.setAttribute(
'aria-label',
`Go to slide ${index + 1}`,
)
group.append(button)
return button
})
if (focusedIndex >= 0) {
buttons[Math.min(focusedIndex, count - 1)]?.focus({
preventScroll: true,
})
}
}
group.dataset.snapCount = String(count)
buttons.forEach((button, index) => {
if (index === selected)
button.setAttribute('aria-current', 'true')
else button.removeAttribute('aria-current')
button.disabled = count < 2
})
}
}
const sync = () => {
const details = getDetails(api)
root.dataset.canScrollPrev = details.canScrollPrev ? 'true' : 'false'
root.dataset.canScrollNext = details.canScrollNext ? 'true' : 'false'
root.dataset.selectedScrollSnap = String(details.selectedScrollSnap)
prevButtons.forEach((button) =>
syncButton(button, details.canScrollPrev),
)
nextButtons.forEach((button) =>
syncButton(button, details.canScrollNext),
)
syncDots(details.scrollSnapList.length, details.selectedScrollSnap)
// A scroll snap can contain several slides. Use Embla's group mapping.
const selectedSlides = new Set(
api.internalEngine().slideRegistry[details.selectedScrollSnap],
)
api.slideNodes().forEach((slide, index) => {
const selected = selectedSlides.has(index)
slide.dataset.selected = String(selected)
})
emit(root, 'carousel:select', api)
}
const onPrevClick = () => {
api.scrollPrev(reducedMotion.matches)
}
const onNextClick = () => {
api.scrollNext(reducedMotion.matches)
}
const onClick = (event: MouseEvent) => {
if (!(event.target instanceof Element)) return
const button = event.target.closest(
'[data-slot="carousel-dot"], [data-carousel-select]',
)
if (!button || button.closest('[data-slot="carousel"]') !== root) return
if (
button instanceof HTMLElement &&
button.dataset.carouselSnap !== undefined
) {
api.scrollTo(
Number(button.dataset.carouselSnap),
reducedMotion.matches,
)
return
}
const slide = button.closest('[data-slot="carousel-item"]')
if (!slide) return
const slideIndex = api.slideNodes().indexOf(slide)
const snapIndex = api
.internalEngine()
.slideRegistry.findIndex((group) => group.includes(slideIndex))
if (snapIndex >= 0) api.scrollTo(snapIndex, reducedMotion.matches)
}
const keyboardTarget = options.keyboardTarget ?? root
const onKeyDown = (event: KeyboardEvent) => {
if (
!(event.target instanceof Element) ||
(event.target.closest('[data-slot="carousel"]') !== root &&
(keyboardTarget === root ||
event.target.closest('[data-slot="carousel"]')))
)
return
if (
event.defaultPrevented ||
event.altKey ||
event.ctrlKey ||
event.metaKey
)
return
if (
event.target.closest(
'input, textarea, select, [contenteditable="true"]',
)
)
return
const isVertical = api.internalEngine().options.axis === 'y'
const rtl = api.internalEngine().options.direction === 'rtl'
if (!isVertical && event.key === 'ArrowLeft') {
event.preventDefault()
const scroll = rtl ? api.scrollNext : api.scrollPrev
scroll(reducedMotion.matches)
}
if (!isVertical && event.key === 'ArrowRight') {
event.preventDefault()
const scroll = rtl ? api.scrollPrev : api.scrollNext
scroll(reducedMotion.matches)
}
if (isVertical && event.key === 'ArrowUp') {
event.preventDefault()
api.scrollPrev(reducedMotion.matches)
}
if (isVertical && event.key === 'ArrowDown') {
event.preventDefault()
api.scrollNext(reducedMotion.matches)
}
}
prevButtons.forEach((button) =>
button.addEventListener('click', onPrevClick),
)
nextButtons.forEach((button) =>
button.addEventListener('click', onNextClick),
)
root.addEventListener('click', onClick)
keyboardTarget.addEventListener('keydown', onKeyDown, true)
api.on('reInit', sync)
api.on('select', sync)
const cleanupEffects = setupCarouselEffects(
api,
options.effects ??
readOptions(root.dataset.carouselEffects),
reducedMotion,
)
let destroyed = false
const view = root.ownerDocument.defaultView!
const frame = view.requestAnimationFrame(() => {
if (!destroyed) emit(root, 'carousel:init', api)
})
const controller: CarouselController = {
root,
api,
destroy() {
if (destroyed) return
destroyed = true
view.cancelAnimationFrame(frame)
api.off('reInit', sync)
api.off('select', sync)
api.off('destroy', controller.destroy)
prevButtons.forEach((button) =>
button.removeEventListener('click', onPrevClick),
)
nextButtons.forEach((button) =>
button.removeEventListener('click', onNextClick),
)
root.removeEventListener('click', onClick)
keyboardTarget.removeEventListener('keydown', onKeyDown, true)
cleanupEffects()
clearRootBinding(root, ROOT_SLOT, controller)
api.destroy()
},
}
setRootBinding(root, ROOT_SLOT, controller)
api.on('destroy', controller.destroy)
sync()
return controller
}
```
#### src/components/ui/carousel/effects.ts
```ts
import type { EmblaCarouselType } from 'embla-carousel'
import type {
CarouselArcOptions,
CarouselEffects,
CarouselFadeOptions,
CarouselParallaxOptions,
CarouselScaleOptions,
} from './types.ts'
const clamp = (value: number, min: number, max: number) =>
Math.min(max, Math.max(min, value))
const finite = (value: number | undefined, fallback: number) =>
typeof value === 'number' && Number.isFinite(value) ? value : fallback
const positive = (value: number | undefined, fallback: number) => {
const result = finite(value, fallback)
return result > 0 ? result : fallback
}
/** Interpolate from one at the center to a minimum at the given distance. */
const tween = (distance: number, min: number, range: number) =>
1 - (1 - min) * clamp(Math.abs(distance) / range, 0, 1)
/** Select the equivalent loop position nearest the viewport center. */
const wrap = (offset: number, length: number) =>
length > 0 ? offset - Math.floor(offset / length + 0.5) * length : offset
/** Arc geometry only. The renderer owns loop compensation and style writes. */
function createArc(options: CarouselArcOptions = {}) {
const radius = positive(options.radius, 2.4)
const angle = clamp(finite(options.angle, 18), 1, 45)
return (distance: number, width: number) => {
const rotation = clamp(distance * angle, -90, 90)
const radians = (rotation * Math.PI) / 180
return {
x: radius * width * Math.sin(radians),
y: radius * width * (1 - Math.cos(radians)),
rotation,
}
}
}
/** Opacity interpolation adapted from Embla's tween example. */
function createFade(options: CarouselFadeOptions = {}) {
const min = clamp(finite(options.min, 0), 0, 1)
const distance = positive(options.distance, 2.5)
return (position: number) => tween(position, min, distance)
}
/** Scale interpolation adapted from Embla's tween example. */
function createScale(options: CarouselScaleOptions = {}) {
const min = clamp(finite(options.min, 0.8), 0, 1)
const distance = positive(options.distance, 1)
return (position: number) => tween(position, min, distance)
}
/** Translation and overscan for clipped content, adapted from Embla's example. */
function createParallax(options: CarouselParallaxOptions = {}) {
const amount = clamp(finite(options.amount, 0.2), 0, 1)
return (distance: number, size: number) => ({
offset: -clamp(distance, -1, 1) * amount * size,
scale: 1 + amount * 2,
})
}
const bindings = new WeakMap void>()
const config = (value: boolean | T): T | undefined =>
typeof value === 'boolean' ? undefined : value
type StyleProperty =
| 'transform'
| 'opacity'
| 'z-index'
| 'position'
| 'transition'
type SavedStyle = { value: string; priority: string }
/**
* Bind one effect renderer to an Embla instance. Calling it again replaces the
* previous effects. Return a cleanup function; destroy also runs it.
* The scroll interpolation follows Embla's v8 tween examples:
* https://www.embla-carousel.com/docs/v8/examples/predefined
*/
export function setupCarouselEffects(
api: EmblaCarouselType,
options: CarouselEffects = {},
reducedMotion = api
.internalEngine()
.ownerWindow.matchMedia('(prefers-reduced-motion: reduce)'),
): () => void {
bindings.get(api)?.()
if (!options.arc && !options.scale && !options.fade && !options.parallax)
return () => {}
const arc = options.arc ? createArc(config(options.arc)) : undefined
const scale = options.scale ? createScale(config(options.scale)) : undefined
const fade = options.fade ? createFade(config(options.fade)) : undefined
const parallax = options.parallax
? createParallax(config(options.parallax))
: undefined
let engine = api.internalEngine()
let destroyed = false
let slides: ReturnType[] = []
let loopOffsets = new Map number>()
const styles = new Map>()
const write = (
node: HTMLElement,
property: StyleProperty,
value: string,
) => {
let saved = styles.get(node)
if (!saved) styles.set(node, (saved = new Map()))
if (!saved.has(property))
saved.set(property, {
value: node.style.getPropertyValue(property),
priority: node.style.getPropertyPriority(property),
})
if (node.style.getPropertyValue(property) !== value)
node.style.setProperty(property, value)
}
const clear = () => {
for (const [node, properties] of styles) {
for (const [property, saved] of properties) {
if (saved.value)
node.style.setProperty(
property,
saved.value,
saved.priority,
)
else node.style.removeProperty(property)
}
}
styles.clear()
for (const { layer, inert } of slides) {
if (layer && layer.inert !== inert) layer.inert = inert
}
}
const ownPart = (slide: HTMLElement, slot: string) =>
Array.from(
slide.querySelectorAll(`[data-slot="${slot}"]`),
).find((node) => node.closest('[data-slot="carousel-item"]') === slide)
function measure(slide: HTMLElement) {
const layer = ownPart(slide, 'carousel-layer')
const content = ownPart(slide, 'carousel-parallax-content')
return {
slide,
layer,
content,
width: layer?.offsetWidth ?? 0,
contentSize:
engine.options.axis === 'x'
? (content?.offsetWidth ?? 0)
: (content?.offsetHeight ?? 0),
inert: layer?.inert ?? false,
}
}
const update = () => {
if (destroyed || reducedMotion.matches) return
const { axis, containerRect, slideRects, offsetLocation } = engine
const viewSize = axis.measureSize(containerRect)
if (!viewSize) return
const hasArc = !!arc && engine.options.axis === 'x'
const loopLength = engine.options.loop ? engine.limit.length : 0
const location = offsetLocation.get()
slides.forEach(
({ slide, layer, content, width, contentSize, inert }, index) => {
const rect = slideRects[index]
if (!rect) return
const size = axis.measureSize(rect)
if (!size) return
const offset =
axis.direction(
rect[axis.startEdge] - containerRect[axis.startEdge],
) +
size / 2 +
location -
viewSize / 2
const renderedOffset = axis.direction(
offset + (loopOffsets.get(index)?.() ?? 0),
)
// The nearest visual copy is independent of Embla's flat loop boundary.
// Compensate on the inner layer when Embla relocates the outer slide.
const visualOffset =
hasArc && loopLength
? axis.direction(wrap(offset, loopLength))
: renderedOffset
const distance = visualOffset / size
if (layer && (hasArc || scale || fade)) {
const transforms: string[] = []
let opacity = fade?.(distance) ?? 1
if (hasArc) {
const point = arc!(distance, width)
transforms.push(
`translate3d(${point.x - renderedOffset}px, ${point.y}px, 0) rotate(${point.rotation}deg)`,
)
write(slide, 'position', 'relative')
write(
slide,
'z-index',
String(Math.round(100 - Math.abs(distance) * 10)),
)
// Hide the seam before the nearest copy switches sides. This
// also covers small radii where both ends fit in the viewport.
if (loopLength)
opacity *= clamp(
(loopLength / 2 - Math.abs(visualOffset)) /
size,
0,
1,
)
}
if (scale) transforms.push(`scale(${scale(distance)})`)
if (transforms.length) {
write(layer, 'transition', 'none')
write(layer, 'transform', transforms.join(' '))
}
if (fade || (hasArc && loopLength)) {
write(layer, 'transition', 'none')
write(layer, 'opacity', String(opacity))
const hidden = inert || opacity === 0
if (layer.inert !== hidden) layer.inert = hidden
}
}
if (content && parallax) {
const value = parallax(distance, contentSize)
const x = engine.options.axis === 'x' ? value.offset : 0
const y = engine.options.axis === 'y' ? value.offset : 0
write(content, 'transition', 'none')
write(
content,
'transform',
`translate3d(${x}px, ${y}px, 0) scale(${value.scale})`,
)
}
},
)
}
const refresh = () => {
clear()
engine = api.internalEngine()
slides = api.slideNodes().map(measure)
loopOffsets = new Map(
engine.options.loop
? engine.slideLooper.loopPoints.map((point) => [
point.index,
point.target,
])
: [],
)
update()
}
const onMotionChange = () => {
clear()
update()
}
const cleanup = () => {
if (destroyed) return
destroyed = true
api.off('scroll', update)
api.off('settle', update)
api.off('slideFocus', update)
api.off('reInit', refresh)
api.off('destroy', cleanup)
reducedMotion.removeEventListener('change', onMotionChange)
clear()
if (bindings.get(api) === cleanup) bindings.delete(api)
}
bindings.set(api, cleanup)
api.on('scroll', update)
api.on('settle', update)
api.on('slideFocus', update)
api.on('reInit', refresh)
api.on('destroy', cleanup)
reducedMotion.addEventListener('change', onMotionChange)
refresh()
return cleanup
}
```
#### src/components/ui/carousel/index.ts
```ts
export type {
EmblaCarouselType as CarouselApi,
EmblaPluginType as CarouselPlugin,
} from 'embla-carousel'
export type {
CarouselArcOptions,
CarouselContentProps,
CarouselEffects,
CarouselEmblaOptions,
CarouselFadeOptions,
CarouselOptions,
CarouselParallaxOptions,
CarouselScaleOptions,
} from './types.ts'
export { create, createCarousel, getCarouselApi } from './carousel.ts'
export type {
CarouselController,
CarouselControllerOptions,
} from './carousel.ts'
export { setupCarouselEffects } from './effects.ts'
export { default as Carousel } from './carousel.astro'
export { default as CarouselContent } from './carousel-content.astro'
export { default as CarouselItem } from './carousel-item.astro'
export { default as CarouselLayer } from './carousel-layer.astro'
export { default as CarouselParallax } from './carousel-parallax.astro'
export { default as CarouselDots } from './carousel-dots.astro'
export { default as CarouselPrevious } from './carousel-previous.astro'
export { default as CarouselNext } from './carousel-next.astro'
```
#### src/components/ui/carousel/types.ts
```ts
import type { EmblaOptionsType } from 'embla-carousel'
type CarouselAlign = Extract
type SerializableEmblaOptions = Pick<
EmblaOptionsType,
| 'active'
| 'containScroll'
| 'direction'
| 'slidesToScroll'
| 'dragFree'
| 'dragThreshold'
| 'inViewThreshold'
| 'loop'
| 'skipSnaps'
| 'duration'
| 'startIndex'
>
interface CarouselEmblaBaseOptions extends SerializableEmblaOptions {
/** Enable the carousel's controls. @default true */
active?: boolean
/** Prevent the carousel from scrolling outside of its container. @default true */
containScroll?: NonNullable
/** The direction of the carousel. @default 'ltr' (left to right) */
direction?: 'ltr' | 'rtl'
/** The number of slides to scroll on a single previous/next button click. @default 1 */
slidesToScroll?: NonNullable
/** Allow the user to drag the carousel freely. @default false */
dragFree?: boolean
/** The percentage of the slide that must be dragged to be considered a drag. @default 0.5 */
dragThreshold?: number
/** The percentage of the slide that must be visible to be considered in view. @default 0.5 */
inViewThreshold?: NonNullable
/** Return to the starting slide when the end is reached. @default false */
loop?: boolean
/** Skip the snap points when the carousel is at the start or end. @default false */
skipSnaps?: boolean
/** The duration of the animation in milliseconds. @default 1000 */
duration?: number
/** The index of the first slide to show. @default 0 */
startIndex?: number
/** Slide alignment. Callback functions require browser setup. */
align?: CarouselAlign
/** Enable drag handling. @default true */
watchDrag?: boolean
/** Observe carousel size changes. @default true */
watchResize?: boolean
/** Observe added or removed slides. @default true */
watchSlides?: boolean
/** Scroll to focused slide content. @default true */
watchFocus?: boolean
}
/** Embla options that can pass through JSON from Astro to the browser. */
export type CarouselEmblaOptions = CarouselEmblaBaseOptions & {
/** Media queries with the same options, without nested breakpoints. */
breakpoints?: Record
}
/** Geometry for a horizontal arc. Scale and fade are separate effects. */
export type CarouselArcOptions = {
/** Circle radius in layer widths. Must be positive. @default 2.4 */
radius?: number
/** Rotation per slide width, in degrees. Range: 1–45. @default 18 */
angle?: number
}
/** Scale of a layer as it moves away from the viewport center. */
export type CarouselScaleOptions = {
/** Smallest scale. Range: 0–1. @default 0.8 */
min?: number
/** Distance to the smallest scale, in slide widths. @default 1 */
distance?: number
}
/** Opacity of a layer as it moves away from the viewport center. */
export type CarouselFadeOptions = {
/** Lowest opacity. Range: 0–1. @default 0 */
min?: number
/** Distance to the lowest opacity, in slide widths. @default 2.5 */
distance?: number
}
/** Movement of content inside a clipped CarouselParallax part. */
export type CarouselParallaxOptions = {
/** Maximum translation as a fraction of the content size. Range: 0–1. @default 0.2 */
amount?: number
}
/** Optional effects. `true` uses the defaults; omitted effects stay off. */
export type CarouselEffects = {
/** Position and rotate CarouselLayer parts on a horizontal arc. */
arc?: boolean | CarouselArcOptions
/** Scale CarouselLayer parts. */
scale?: boolean | CarouselScaleOptions
/** Fade CarouselLayer parts. Fully transparent layers become inert. */
fade?: boolean | CarouselFadeOptions
/** Move content inside CarouselParallax parts. Supports either axis. */
parallax?: boolean | CarouselParallaxOptions
}
/** Props for the carousel root, minus HTML attributes. */
export type CarouselOptions = {
/** JSON-compatible Embla options. Orientation and Astro parts control the axis and elements. */
carouselOptions?: CarouselEmblaOptions
/** Scroll axis for the carousel. @default "horizontal" */
orientation?: 'horizontal' | 'vertical'
/** Independent effects applied to the optional inner parts. */
effects?: CarouselEffects
}
/** Layout props for the carousel track and its clipping viewport. */
export type CarouselContentProps = {
/** CSS gap value for space between items. @default "1rem" */
gap?: string
/** Classes for the clipping viewport, such as padding for an arc. */
viewportClass?: string
}
```
Component classes use the preset configured during project setup. Select the same preset in the docs before copying Manual source. To change installed component classes, edit or reinstall their source. See [Theming](/docs/theming) for details.
## About
The carousel is built with
[Embla Carousel](https://www.embla-carousel.com/) for motion and swipe. The
Astro components follow the same composition as shadcn/ui.
## Usage
```astro
---
import {
Carousel,
CarouselContent,
CarouselDots,
CarouselItem,
CarouselNext,
CarouselPrevious,
} from "@/components/ui/carousel"
---
.........
```
## Composition
Arrange the parts as shown for a `Carousel`:
```text
Carousel
├── CarouselContent
│ ├── CarouselItem
│ └── CarouselItem
├── CarouselPrevious
└── CarouselNext
```
## Examples
### Sizes
To set the size of the items, use the `basis` utility classes on
``.
```astro
---
import {
Carousel,
CarouselContent,
CarouselItem,
CarouselNext,
CarouselPrevious,
} from "@/components/ui/carousel"
const items = Array.from({ length: 5 }, (_, index) => index + 1)
---
{items.map((item) => (
))}
```
```astro
.........
```
```astro
.........
```
### Spacing
Set `gap` on `` to set the space between items. The default is
`1rem`. This prop sets `--carousel-gap`, which the content and items use for
their spacing.
```astro
---
import {
Carousel,
CarouselContent,
CarouselItem,
CarouselNext,
CarouselPrevious,
} from "@/components/ui/carousel"
---
Slide 1
Slide 2
Slide 3
Slide 4
```
```astro
.........
```
Use a CSS value such as `clamp()` when the gap must change with the viewport:
```astro
.........
```
### Scale and fade
Effects are optional. A normal `CarouselItem` has one default slot and accepts
any content. Put content inside `CarouselLayer` to apply scale, fade, or arc
movement. This works with text, cards, buttons, and images.
```astro
---
import { Card, CardContent } from "@/components/ui/card"
import {
Carousel,
CarouselContent,
CarouselDots,
CarouselItem,
CarouselLayer,
CarouselNext,
CarouselPrevious,
} from "@/components/ui/carousel"
const steps = ["Plan", "Sketch", "Build", "Test", "Refine", "Share", "Review"]
---
{steps.map((step, index) => (
Step {index + 1}
{step}
))}
```
```astro
Any slide content
```
Each effect can be `true` for its defaults, an options object, or `false`.
Omitted effects stay off. `scale.distance` and `fade.distance` are distances from
the viewport center in slide widths. They work on both axes, including grouped
slides and slides with different widths.
### Parallax
Use `effects.parallax` with `CarouselParallax`. This part clips its inner content.
The renderer translates and enlarges that content to keep the edges covered.
It uses the carousel's axis and direction. Put it inside `CarouselLayer` to
combine parallax with scale, fade, or arc movement.
```astro
---
import {
Carousel,
CarouselContent,
CarouselDots,
CarouselItem,
CarouselParallax,
CarouselNext,
CarouselPrevious,
} from "@/components/ui/carousel"
import { Image } from "astro:assets"
import water from "@/assets/wizard/wizard-overlooking-water.png"
import moon from "@/assets/wizard/wizard-on-moon.jpeg"
import clouds from "@/assets/wizard/wizard-above-clouds.jpeg"
import wizard from "@/assets/wizard/automation-design.png"
import portal from "@/assets/images/the-portal.png"
const images = [
{ image: water, alt: "A wizard looks out over the water." },
{ image: moon, alt: "A wizard stands on the moon." },
{ image: clouds, alt: "A wizard stands above the clouds." },
{ image: wizard, alt: "A wizard performing automations" },
{ image: portal, alt: "A glowing portal in the distance" },
]
---
{images.map(({ image, alt }, index) => (
))}
```
```astro
```
`amount` is the maximum translation as a fraction of the content size. Its
default is `0.2`. The part can contain any content; it has no image slot.
### Arc
Use `effects.arc` for a curved row. The arc changes position and rotation.
Scale and fade remain separate options.
```astro
---
import {
Carousel,
CarouselContent,
CarouselItem,
CarouselLayer,
CarouselNext,
CarouselPrevious,
} from "@/components/ui/carousel"
import street from "@/assets/wizard/wizard-small-street.png"
import moon from "@/assets/wizard/wizard-on-moon.jpeg"
import clouds from "@/assets/wizard/wizard-above-clouds.jpeg"
import town from "@/assets/wizard/wizard-overlooking-town.png"
import future from "@/assets/images/taking-in-the-future.png"
import beach from "@/assets/images/beach-on-alien-planet.png"
import planet from "@/assets/wizard/wizard-in-field-looking-at-planet.png"
import { Image } from "astro:assets"
const images = [
{ image: street, alt: "A wizard on a narrow street between tall buildings." },
{ image: moon, alt: "A wizard stands on the moon." },
{ image: clouds, alt: "A robot stands above the clouds." },
{ image: town, alt: "A wizard looks over a town." },
{ image: future, alt: "A figure taking in a distant future skyline." },
{ image: beach, alt: "A beach on an alien planet under a bright sky." },
{ image: planet, alt: "A wizard looks at a planet." },
]
---
{images.map(({ image, alt }, index) => (
))}
```
```astro
```
The radius is in layer widths. The angle is in degrees per slide width.
The defaults are `2.4` and `18`. The radius must be positive; the angle is limited
to 1–45 degrees. Increase viewport padding for a deeper arc.
The renderer keeps the visible arc position continuous when Embla relocates a
slide for looping. At the opposite end of the loop, it fades a layer over one
slide width before that layer switches sides. This prevents a visible jump,
including when a small radius puts both ends inside the viewport.
Arc movement supports horizontal carousels. On a vertical carousel, other enabled
effects still work. Reduced motion removes all effects and makes button and
keyboard navigation instant. Fully transparent layers become inert. Cleanup
restores the caller's inline styles and original inert state.
### Selection styling and overlays
Items expose `data-selected` and the `group/carousel-item` class. Compose an
overlay as ordinary content inside `CarouselLayer`. For example, use
`group-data-[selected=false]/carousel-item:invisible` to hide an overlay and its
controls on unselected slides. Blur, dimming, rounding, and overlay placement
belong in this composition.
See [Projects Carousel](/blocks/gallery) for a complete section with these styles.
The old `variant`, root `arc` prop, and item `image` and `overlay` slots have been
replaced by `effects` and the optional parts.
### Dot navigation and selection
Put `CarouselDots` inside `Carousel`. It creates one labelled button for each
scroll position and sets `aria-current="true"` on the selected button. The dots
update after a resize or a slide change. They also support grouped slides.
Set `label` to change the navigation group's accessible name.
The active dot expands into a pill. Its width and color change over 300 ms.
Reduced motion makes this change instant. The button grows with the dot and
keeps padding around it for pointer input and keyboard focus.
The client script sets `data-selected="true"` on items in the selected group.
To select a slide from a button, put `data-carousel-select` on that button
inside the item. Keep overlay links separate from that button.
## API Reference
Read the [installed source](/r/carousel.json) and the
[Embla v8 API](https://www.embla-carousel.com/docs/v8/api/methods).
### Embla options in Astro
`carouselOptions` accepts JSON-compatible values, including `loop`, `duration`,
`slidesToScroll`, and media-query `breakpoints`. Set `align` to `"start"`, `"center"`,
or `"end"` inside this object. The `watchDrag`, `watchFocus`, `watchResize`, and
`watchSlides` options accept booleans. Breakpoints use the same options and cannot
contain another `breakpoints` object.
Callbacks and DOM elements cannot pass through the HTML data attribute. Use
`orientation` for the axis and the Astro parts for the container and slides.
Keep callback options in a browser script through the client API below.
### Image loading
Use `loading="lazy"` on images outside the initial view. Astro's `Image` uses
this value by default. Use `priority` for an important image visible when the
page opens. The browser can load nearby slides before they become visible;
lazy loading does not limit downloads to the selected slide.
### Client setup
The Astro component calls `create()` from `carousel/carousel.ts`. It binds each
unbound root once and destroys its controllers on removal or an Astro page swap.
There is no carousel state on `window`.
For manually rendered markup, `createCarousel(root, options)` returns
`{ root, api, destroy }`. A repeated call returns the existing controller.
Client options accept `carouselOptions`, `orientation`, `effects`, and Embla
`plugins`. Browser `carouselOptions` accepts the full `EmblaOptionsType`, including
callbacks and DOM elements. The root `orientation` still sets the base axis.
Plugin functions stay in the client script; do not pass them through Astro
frontmatter props. Call `destroy()` before binding new controller options.
`getCarouselApi(root)` reads an existing Embla instance. The same shared effects
setup is available to client scripts:
```ts
import { setupCarouselEffects } from "@/components/ui/carousel/effects.ts"
// api is an initialized Embla instance, for example from carousel:init.
const cleanup = setupCarouselEffects(api, {
arc: { radius: 2.4, angle: 18 },
scale: { min: 0.8 },
})
```
Calling this setup again replaces the earlier effects. Its cleanup removes
listeners and restores styles. Destroying Embla also cleans up the effects.
Keep caller transforms on another element: the effect renderer owns transforms
on `CarouselLayer` and the inner `CarouselParallax` content while active.
### Events
The carousel root emits these events. Both events use the same detail.
#### Outbound events
| Event | Detail |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `carousel:init` | `{ api: EmblaCarouselType, canScrollPrev: boolean, canScrollNext: boolean, selectedScrollSnap: number, scrollSnapList: number[] }` |
| `carousel:select` | `{ api: EmblaCarouselType, canScrollPrev: boolean, canScrollNext: boolean, selectedScrollSnap: number, scrollSnapList: number[] }` |
## When to use Carousel
Put related slides inside CarouselContent and keep each slide in a CarouselItem. Pass Embla options through the `carouselOptions` prop. Choose an orientation and slide width that match the content rather than forcing all content into one layout.
## Keyboard and behavior
The client script starts Embla for drag and swipe behavior. Provide labelled previous and next controls for people who cannot drag. Essential content should remain understandable without swiping through an unexplained sequence.
## Theme and layout
Set image dimensions to reduce layout movement and check the last slide at narrow widths. Theme tokens style the controls; slide composition stays in your Astro markup. Autoplay is not supplied by the base component.
---
# Checkbox for Astro
Source: https://ui.gnosticai.com/components/checkbox
```astro
---
import { Checkbox } from "@/components/ui/checkbox"
import { Label } from "@/components/ui/label"
---
Attach the current review notes when you share this project.
```
## Installation
### Command
```sh
bunx --bun shadcn@latest add @gnostic/checkbox
```
### Manual
Complete the [Installation guide](/docs/installation) first. Then copy the component files below.
No extra packages are required.
#### src/components/ui/checkbox/checkbox.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = Omit, "type">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/checkbox/index.ts
```ts
export { default as Checkbox } from "./checkbox.astro"
```
Component classes use the preset configured during project setup. Select the same preset in the docs before copying Manual source. To change installed component classes, edit or reinstall their source. See [Theming](/docs/theming) for details.
## Usage
```ts
import { Checkbox } from "@/components/ui/checkbox"
```
```astro
```
## Notes
- Pair `Checkbox` with `Label` for simple cases, or use
[Field](/components/field) when you need descriptions, validation, or
grouped controls.
- Use the native `disabled` attribute to prevent interaction and
`aria-invalid` when the control should display an error state.
- For multi-line rows, wrap the label and supporting text together so the
control stays easy to scan.
## API Reference
Read the [installed source](/r/checkbox.json) for the complete prop types.
## When to use Checkbox
Pair each Checkbox with a Label using matching `id` and `for` values. Give submitted controls a name and value. Use separate checkboxes when several choices can be selected together.
## Keyboard and behavior
The rendered input uses native form submission, focus, Space activation, and disabled behavior. Set the DOM `indeterminate` property from your script for a mixed selection; an HTML attribute alone cannot set that property. A parent “select all” checkbox does not manage child values automatically.
## Theme and layout
Checked, invalid, and disabled styles use the shared tokens. The check mark is a CSS mask on the input. Keep a text label visible and use FieldError for an explanation of invalid input.
---
# Code Block for Astro
Source: https://ui.gnosticai.com/components/code-block
```astro
---
import { Terminal } from "@lucide/astro"
import {
CodeBlock,
CodeBlockHeader,
CodeBlockTitle,
CodeBlockActions,
CodeBlockCopyButton,
CodeBlockContent,
} from "@/components/ui/code-block"
const output = "$ bun run build\n\n✓ Build complete.\n✓ 12 pages generated."
---
Terminal
```
## Installation
### Command
```sh
bunx --bun shadcn@latest add @gnostic/code-block
```
### Manual
Complete the [Installation guide](/docs/installation) first. Then copy the component files below.
Install the component packages:
```sh
bun add shiki
```
#### src/components/ui/code-block/code-block-actions.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/code-block/highlight-code.ts
```ts
// Server-only Astro port of shadcn/ui's highlighter (MIT).
import { createHighlighterCore, type HighlighterCore } from 'shiki/core'
import { createJavaScriptRegexEngine } from 'shiki/engine/javascript'
const languages = {
astro: () => import('shiki/langs/astro.mjs'),
bash: () => import('shiki/langs/shellscript.mjs'),
css: () => import('shiki/langs/css.mjs'),
diff: () => import('shiki/langs/diff.mjs'),
html: () => import('shiki/langs/html.mjs'),
javascript: () => import('shiki/langs/javascript.mjs'),
json: () => import('shiki/langs/json.mjs'),
jsx: () => import('shiki/langs/jsx.mjs'),
markdown: () => import('shiki/langs/markdown.mjs'),
python: () => import('shiki/langs/python.mjs'),
sql: () => import('shiki/langs/sql.mjs'),
tsx: () => import('shiki/langs/tsx.mjs'),
typescript: () => import('shiki/langs/typescript.mjs'),
yaml: () => import('shiki/langs/yaml.mjs'),
}
const aliases: Record = {
js: 'javascript',
md: 'markdown',
py: 'python',
sh: 'bash',
shell: 'bash',
shellscript: 'bash',
ts: 'typescript',
yml: 'yaml',
zsh: 'bash',
}
let highlighter: Promise | undefined
function getHighlighter() {
highlighter ??= createHighlighterCore({
themes: [
import('shiki/themes/github-light.mjs'),
import('shiki/themes/github-dark.mjs'),
],
langs: [],
engine: createJavaScriptRegexEngine({ forgiving: true }),
})
return highlighter
}
function getLanguage(language: string) {
const name = language.toLowerCase()
if (name === 'ansi') {
return name
}
if (Object.hasOwn(languages, name)) {
return name as keyof typeof languages
}
return Object.hasOwn(aliases, name) ? aliases[name]! : null
}
/** Escape source and token styles before insertion into an Astro HTML slot. */
function escapeHtml(value: string) {
return value
.replace(/&/g, '&')
.replace(//g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
}
/** Return safe HTML for each line. Unknown languages return escaped plain lines. */
export async function highlightCode(
code: string,
language: string,
): Promise {
const source = code.replace(/\r?\n$/, '')
const lang = getLanguage(language)
if (!lang) return source.split(/\r?\n/).map(escapeHtml)
const shiki = await getHighlighter()
if (lang !== 'ansi' && !shiki.getLoadedLanguages().includes(lang)) {
await shiki.loadLanguage(languages[lang])
}
const tokenize = (text: string) =>
shiki.codeToTokens(text, {
lang,
themes: { light: 'github-light', dark: 'github-dark' },
defaultColor: false,
}).tokens
const tokens =
lang === 'ansi'
? source.split(/\r?\n/).flatMap(tokenize)
: tokenize(source)
return tokens.map((line) =>
line
.map((token) => {
const style = Object.entries(token.htmlStyle ?? {})
.map(([key, value]) => `${key}:${value}`)
.join(';')
return `${escapeHtml(token.content)}`
})
.join(''),
)
}
```
#### src/components/ui/code-block/index.ts
```ts
export { default as CodeBlock } from './code-block.astro'
export { default as CodeBlockHeader } from './code-block-header.astro'
export { default as CodeBlockTitle } from './code-block-title.astro'
export { default as CodeBlockActions } from './code-block-actions.astro'
export { default as CodeBlockCopyButton } from './code-block-copy-button.astro'
export { default as CodeBlockContent } from './code-block-content.astro'
export { default as CodeBlockLine } from './code-block-line.astro'
export { default as CodeBlockFooter } from './code-block-footer.astro'
export type {
CodeBlockProps,
CodeBlockContentProps,
CodeBlockLineProps,
CodeBlockCopyButtonProps,
} from './types.ts'
```
#### src/components/ui/code-block/types.ts
```ts
import type { ButtonVariantProps } from '../button/button-variants.ts'
/** The surface around a code sample or terminal output. */
export interface CodeBlockProps {
/** The tone of the block. @default 'default' */
variant?: 'default' | 'destructive'
/** The spacing and text size. @default 'default' */
size?: 'default' | 'sm'
}
/** Code content. Use the default slot for composed CodeBlockLine parts. */
export interface CodeBlockContentProps {
/** Plain source text. Takes precedence over the default slot. */
code?: string
/** Highlight `code` on the server with Shiki. Unknown languages stay plain. */
language?: string
/** Wrap long lines. @default false */
wrap?: boolean
/** Show line numbers outside the selectable text. @default false */
lineNumbers?: boolean
/** The first line number. @default 1 */
startLine?: number
}
/** A single line with an optional diff or highlight state. */
export interface CodeBlockLineProps {
/** The state of the line. @default 'default' */
variant?: 'default' | 'added' | 'removed' | 'highlighted'
}
/** A Button that copies the supplied source text. */
export interface CodeBlockCopyButtonProps extends ButtonVariantProps {
/** The exact text to copy, without line numbers or diff markers. */
value: string
}
```
Component classes use the preset configured during project setup. Select the same preset in the docs before copying Manual source. To change installed component classes, edit or reinstall their source. See [Theming](/docs/theming) for details.
## Usage
```astro
---
import {
CodeBlock,
CodeBlockHeader,
CodeBlockTitle,
CodeBlockActions,
CodeBlockCopyButton,
CodeBlockContent,
} from "@/components/ui/code-block"
const output = "bun run build"
---
Terminal
```
## Composition
```text
CodeBlock
├── CodeBlockHeader
│ ├── CodeBlockTitle
│ └── CodeBlockActions
│ └── CodeBlockCopyButton
├── CodeBlockActions (floating, without a header)
├── CodeBlockContent
│ └── CodeBlockLine
└── CodeBlockFooter
```
Pass plain text through `code` or the default slot. Use `CodeBlockLine` parts
in the slot for individual line states. Header, title, actions, and footer
accept HTML attributes and default slots. Wrap the title in an anchor to link
to a file. Place each block in a `TabsContent` to show multiple files.
## Tabs
Show several files with one `CodeBlock` in each `TabsContent`. Each panel has its
own title, highlighted source, line numbers, and copy button. This ports the
[shadcn tabs example](https://ui.shadcn.com/docs/components/base/code-block#tabs)
to Astro. The React and API code shown in the panels is sample text.
```astro
---
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockTitle,
} from "@/components/ui/code-block"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
const files = [
{
id: "route",
title: "app/api/chat/route.ts",
language: "ts",
code: `import { streamText } from "ai"
export async function POST(request: Request) {
const { messages } = await request.json()
const result = streamText({ model: "anthropic/claude-sonnet-4.5", messages })
return result.toUIMessageStreamResponse()
}`,
},
{
id: "chat",
title: "components/chat.tsx",
language: "tsx",
code: `"use client"
import { useChat } from "@ai-sdk/react"
export function Chat() {
const { messages } = useChat()
return
}`,
},
{
id: "env",
title: ".env.local",
language: "bash",
code: "AI_GATEWAY_API_KEY=your-api-key",
},
]
---
{files.map((file) => (
{file.title.split("/").at(-1)}
))}
{files.map((file) => (
{file.title}
))}
```
## Floating actions
Put actions directly inside the root to show them on hover or keyboard focus.
They stay visible on touch screens.
```astro
---
import {
CodeBlock,
CodeBlockActions,
CodeBlockCopyButton,
CodeBlockContent,
} from "@/components/ui/code-block"
const output = "bun add astro\nbun run dev"
---
{output}
```
## Line numbers and syntax highlighting
Set `lineNumbers` and use `startLine` for a sample from the middle of a file.
The line number column grows to fit its content. Use `language` with `code`
for server-side syntax highlighting. Shiki does not enter the browser bundle.
```astro
---
import {
CodeBlock,
CodeBlockHeader,
CodeBlockTitle,
CodeBlockContent,
} from "@/components/ui/code-block"
const code =
'const project = {\n name: "Atlas",\n private: true,\n}\n\nexport default project'
---
project.ts
```
## Diff and highlighted lines
Use `added`, `removed`, or `highlighted` on each `CodeBlockLine`. Diff markers
use a symbol and a color. Line numbers and markers are not part of the copied
source. Empty lines retain their height and selectable newline.
For highlighted lines, import `highlightCode` from
`@/components/ui/code-block/highlight-code` in Astro frontmatter. It returns
an array of escaped HTML strings. Put each result in a `CodeBlockLine` with
``.
```astro
---
import {
CodeBlock,
CodeBlockHeader,
CodeBlockTitle,
CodeBlockContent,
CodeBlockLine,
} from "@/components/ui/code-block"
import { highlightCode } from "@/components/ui/code-block/highlight-code"
const code =
"export const config = {\n retries: 1,\n retries: 3,\n timeout: 5000,\n}"
const lines = await highlightCode(code, "ts")
---
config.ts
{lines.map((line, index) => (
))}
```
## Wrap, small size, and errors
Use `wrap` to wrap long lines, `size="sm"` for compact output, and
`variant="destructive"` for errors. A caller-owned button can change the
content's `data-wrap` attribute. Keep its `aria-pressed` state in sync.
```astro
---
import {
CodeBlock,
CodeBlockHeader,
CodeBlockTitle,
CodeBlockActions,
CodeBlockCopyButton,
CodeBlockContent,
} from "@/components/ui/code-block"
import { Button } from "@/components/ui/button"
const output =
"Error: The request exceeds the configured size limit. Reduce the number of records, then send the request again."
---
Error
```
## Height and footer
Limit the content height with a `max-h-*` class. Use the footer for a Show More
button. Keep `aria-expanded` in sync and point `aria-controls` at the content.
```astro
---
import {
CodeBlock,
CodeBlockHeader,
CodeBlockTitle,
CodeBlockContent,
CodeBlockFooter,
} from "@/components/ui/code-block"
import { Button } from "@/components/ui/button"
const id = `code-log-${crypto.randomUUID()}`
const output = Array.from(
{ length: 20 },
(_, index) => `[${String(index + 1).padStart(2, "0")}] GET /api/projects 200`,
).join("\n")
---
Request log
```
## Terminal colors
Use `language="ansi"` to show terminal colors. Each line starts with fresh
ANSI state, as in the shadcn component.
```astro
---
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block"
const output =
"$ bun test\n\u001b[32m✓\u001b[39m parser.test.ts (4 tests)\n\u001b[31m✗\u001b[39m format.test.ts (1 failed)"
---
```
## Inside Typeset
Typeset leaves elements with `data-slot` and their contents unchanged. A direct
child component gets the same space above it as a paragraph. Code Block needs
no `data-not-typeset` attribute. Plain `pre` and `code` elements keep their text
styles.
```astro
---
import {
CodeBlock,
CodeBlockHeader,
CodeBlockTitle,
CodeBlockActions,
CodeBlockCopyButton,
CodeBlockContent,
} from "@/components/ui/code-block"
const code = 'const message = "Hello, Astro"\nconsole.log(message)'
---
Run the example
Save this code in hello.ts.
hello.ts
Then run the file in your terminal.
bun hello.ts
```
## Astro port notes
This component follows the [shadcn Code Block](https://ui.shadcn.com/docs/components/base/code-block)
composition. Coss does not supply this component. The shared Gnostic recipe
uses the same layout with semantic success and destructive colors. Shadcn presets
use their upstream Code Block recipes. Gnostic, Soft, and Glow use the shared
Gnostic recipe with their own color, font, and radius tokens.
Use Astro `class`, slots, and scripts. There are no React hooks or render props.
Rendering and highlighting run on the server. Incremental client highlighting
and Streamdown integration are not included. Native scrolling is used; the
upstream scroll-fade utilities are not included.
Supported languages are Astro, Bash, CSS, diff, HTML, JavaScript, JSON, JSX,
Markdown, Python, SQL, TSX, TypeScript, YAML, and ANSI. Common short names such
as `ts`, `js`, `sh`, and `yml` work. Unknown languages render as plain text.
One final newline is omitted when text is split into lines. The copy button
always copies its exact `value`, including final newlines.
## Accessibility
Code always reads left to right. The header follows the page direction.
Content has `tabindex="0"` so keyboard users can scroll it. Set
`tabindex={-1}` to remove this tab stop. Line numbers use CSS counters with
empty alternative text where the browser supports it.
The copy button uses the shared [Copy Button controller](/components/copy-button).
It has an accessible label and a polite status message. It reports
copy failure if the Clipboard API is unavailable or permission is denied.
Clipboard access requires a secure context, such as HTTPS or localhost.
Native button attributes, including `disabled`, pass through.
## API Reference
### CodeBlockProps
### CodeBlockContentProps
### CodeBlockLineProps
### CodeBlockCopyButtonProps
Accepts the shared Button `variant` and `size` props. Defaults are `ghost` and
`icon-xs`. Use the default slot to replace the copy and check icons.
Read the [installed source](/r/code-block.json) for the complete prop types.
## Theme and layout
Code Block uses the project preset for its frame and controls. Set a maximum content height for long examples, and choose wrapping or scrolling to suit the code. Keep copy controls reachable at narrow widths. Use [Tabs](/components/tabs) for related code samples and [Typeset](/docs/theming#text-and-headings) for the surrounding guide.
---
# Collapsible for Astro
Source: https://ui.gnosticai.com/components/collapsible
```astro
---
import ChevronsUpDown from "@lucide/astro/icons/chevrons-up-down"
import { cn } from "cn"
import { buttonVariants } from "@/components/ui/button"
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible"
---
Order #4189
StatusShipped
Shipping address
14 Sample Lane, Example City
Items
2x Agency Headphones
```
## Installation
### Command
```sh
bunx --bun shadcn@latest add @gnostic/collapsible
```
### Manual
Complete the [Installation guide](/docs/installation) first. Then copy the component files below.
Install the component packages:
```sh
bun add @data-slot/collapsible
```
#### src/components/ui/collapsible/collapsible-content.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, hidden: _hidden, ...props } = Astro.props
---
```
#### src/components/ui/collapsible/collapsible-trigger.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"button">
const { class: className, type = "button", ...props } = Astro.props
---
```
#### src/components/ui/collapsible/collapsible.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import type { CollapsibleProps } from "./types.ts"
type Props = HTMLAttributes<"div"> & CollapsibleProps
const {
class: className,
defaultOpen,
hiddenUntilFound,
closeOnEscape,
closeOnClickOutside,
...props
} = Astro.props
---
```
#### src/components/ui/collapsible/index.ts
```ts
export { default as Collapsible } from './collapsible.astro'
export { default as CollapsibleContent } from './collapsible-content.astro'
export { default as CollapsibleTrigger } from './collapsible-trigger.astro'
export type { CollapsibleProps } from './types.ts'
```
#### src/components/ui/collapsible/types.ts
```ts
import type { CollapsibleOptions } from '@data-slot/collapsible'
/**
* Collapsible props.
*/
export type CollapsibleProps = Pick<
CollapsibleOptions,
'defaultOpen' | 'hiddenUntilFound' | 'closeOnEscape' | 'closeOnClickOutside'
>
```
Component classes use the preset configured during project setup. Select the same preset in the docs before copying Manual source. To change installed component classes, edit or reinstall their source. See [Theming](/docs/theming) for details.
## Usage
```ts
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"
```
```astro
Can I use this in my project?
Yes. Free to use for personal and commercial projects. No attribution
required.
```
## Composition
Arrange the parts as shown for a `Collapsible`:
```text
Collapsible
├── CollapsibleTrigger
└── CollapsibleContent
```
## Default Open
Use `defaultOpen` to render a collapsible expanded on first load.
```astro
ToggleContent
```
## Examples
### Basic
```astro
---
import ChevronDown from "@lucide/astro/icons/chevron-down"
import { cn } from "cn"
import { Button, buttonVariants } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible"
---
Product details
Read the visit notes before choosing an appointment time.
```
### Settings Panel
Use a trigger button to reveal additional settings.
```astro
---
import Maximize from "@lucide/astro/icons/maximize"
import { buttonVariants } from "@/components/ui/button"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card"
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible"
import { Field, FieldGroup, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
---
Radius
Choose how round the draft preview corners appear.
Top left radius
Top right radius
Bottom left radius
Bottom right radius
```
### File Tree
Use nested collapsibles to build a file tree.
```astro
---
import ChevronRight from "@lucide/astro/icons/chevron-right"
import File from "@lucide/astro/icons/file"
import Folder from "@lucide/astro/icons/folder"
import { cn } from "cn"
import { Button, buttonVariants } from "@/components/ui/button"
import { Card, CardContent, CardHeader } from "@/components/ui/card"
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible"
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
---
FilesAssets
pages
images
```
## Notes
- Use `Collapsible` for progressive disclosure inside an existing layout.
- Keep `CollapsibleTrigger` as the single control that opens and closes the
content.
- For stacked FAQ patterns with multiple items, prefer
[Accordion](/components/accordion).
## API Reference
### CollapsibleProps
### Events
Dispatch these events on the collapsible root. The root emits the outbound events.
#### Outbound events
| Event | Detail |
| -------------------- | ------------------- |
| `collapsible:change` | `{ open: boolean }` |
#### Inbound events
| Event | Detail |
| ----------------- | ------------------- |
| `collapsible:set` | `{ open: boolean }` |
## When to use Collapsible
Use Collapsible when a single piece of supporting content can be hidden. Place its trigger and content under the same root. Keep the trigger text useful in both open and closed states.
## Keyboard and behavior
The data-slot script changes expanded state and panel visibility. A button trigger supports keyboard activation. Do not hide the only route to an essential action behind an unexplained icon.
## Theme and layout
The panel reads its height from the controller for the open and close transition. Put padding on an inner child if clipping during motion affects the layout. Theme styles come from the content you place inside it.
---
# Color Picker for Astro
Source: https://ui.gnosticai.com/components/color-picker
```astro
---
import {
ColorPicker,
ColorPickerContent,
ColorPickerTrigger,
} from "@/components/ui/color-picker"
---
```
## Installation
### Command
```sh
bunx --bun shadcn@latest add @gnostic/color-picker
```
### Manual
Complete the [Installation guide](/docs/installation) first. Then copy the component files below.
Install the component packages:
```sh
bun add @data-slot/core @data-slot/popover
```
#### src/components/ui/color-picker/color-picker-area.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---
```
#### src/components/ui/color-picker/color-picker-channel-input.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import { InputGroupInput } from "../input-group/index.ts"
import type { ColorPickerChannelInputProps } from "./types.ts"
type Props = Omit, "type" | "value" | "name"> &
ColorPickerChannelInputProps
const { class: className, channel = "hex", colorSpace, ...props } = Astro.props
---
```
#### src/components/ui/color-picker/color-picker-color.ts
```ts
/** Color parsing and conversion adapted from the ReUI source supplied for this port.
* Channels stay in their source color space until a control changes them.
*/
import type {
ColorPickerColor,
ColorPickerColorSpace,
ColorPickerChannel,
ColorPickerFormat,
} from './types.ts'
type Triple = [number, number, number]
const SPACE_CHANNELS: Record<
ColorPickerColorSpace,
[ColorPickerChannel, ColorPickerChannel, ColorPickerChannel]
> = {
rgb: ['red', 'green', 'blue'],
hsl: ['hue', 'saturation', 'lightness'],
hsv: ['hue', 'saturation', 'brightness'],
oklch: ['lightness', 'chroma', 'hue'],
}
export const COLOR_PICKER_FORMATS: ColorPickerFormat[] = [
'hex',
'rgb',
'hsl',
'hsb',
'oklch',
]
export const FORMAT_LABELS: Record = {
hex: 'HEX',
rgb: 'RGB',
hsl: 'HSL',
hsb: 'HSB',
oklch: 'OKLCH',
}
/* -------------------------------------------------------------------------- */
/* Color math */
/* -------------------------------------------------------------------------- */
export const clamp = (value: number, min: number, max: number) =>
Math.min(max, Math.max(min, value))
export const wrapHue = (hue: number) => ((hue % 360) + 360) % 360
/* Round output only. Drop trailing zeros and never write "-0". */
export const fixed = (value: number, digits = 3) =>
String(Number(value.toFixed(digits)) + 0)
function rgbToHsv([red, green, blue]: Triple, fallbackHue = 0): Triple {
const r = red / 255
const g = green / 255
const b = blue / 255
const max = Math.max(r, g, b)
const delta = max - Math.min(r, g, b)
let hue = fallbackHue
if (delta > 1e-9) {
hue =
max === r
? ((g - b) / delta) % 6
: max === g
? (b - r) / delta + 2
: (r - g) / delta + 4
hue = wrapHue(hue * 60)
}
return [hue, max === 0 ? 0 : (delta / max) * 100, max * 100]
}
function hsvToRgb([hue, saturation, brightness]: Triple): Triple {
const s = saturation / 100
const v = brightness / 100
const channel = (n: number) => {
const k = (n + hue / 60) % 6
return (v - v * s * Math.max(0, Math.min(k, 4 - k, 1))) * 255
}
return [channel(5), channel(3), channel(1)]
}
/* HSL and HSB share a hue, carried over as is, so a gray keeps it. */
function hsvToHsl([hue, saturation, brightness]: Triple): Triple {
const s = saturation / 100
const v = brightness / 100
const l = v * (1 - s / 2)
const sl = l === 0 || l === 1 ? 0 : (v - l) / Math.min(l, 1 - l)
return [hue, sl * 100, l * 100]
}
function hslToHsv([hue, saturation, lightness]: Triple): Triple {
const s = saturation / 100
const l = lightness / 100
const v = l + s * Math.min(l, 1 - l)
return [hue, v === 0 ? 0 : 2 * (1 - l / v) * 100, v * 100]
}
const toLinear = (channel: number) => {
const c = channel / 255
return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
}
const fromLinear = (channel: number) =>
255 *
(channel <= 0.0031308
? 12.92 * channel
: 1.055 * channel ** (1 / 2.4) - 0.055)
/* OKLab by Björn Ottosson, the matrices CSS Color 4 uses. Linear sRGB in,
unbounded, so a wide-gamut color converts without clipping. */
function linearToOklab([r, g, b]: Triple): Triple {
const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b)
const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b)
const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b)
return [
0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,
1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,
0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s,
]
}
/* OKLab, or polar a and b, to OKLCH in the picker's units: L 0 to 100. */
function oklabToOklch([lightness, a, b]: Triple, fallbackHue = 0): Triple {
const chroma = Math.sqrt(a * a + b * b)
const hue =
chroma < 1e-4
? fallbackHue
: wrapHue((Math.atan2(b, a) * 180) / Math.PI)
return [lightness * 100, chroma, hue]
}
function rgbToOklch(rgb: Triple, fallbackHue = 0): Triple {
return oklabToOklch(linearToOklab(rgb.map(toLinear) as Triple), fallbackHue)
}
function oklchToLinear([lightness, chroma, hue]: Triple): Triple {
const angle = (hue * Math.PI) / 180
const L = lightness / 100
const a = chroma * Math.cos(angle)
const b = chroma * Math.sin(angle)
const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3
const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3
const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3
return [
4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,
]
}
const inSrgb = (linear: Triple) =>
linear.every((channel) => channel >= -1e-4 && channel <= 1 + 1e-4)
const clipLinear = (linear: Triple) =>
linear.map((channel) => clamp(channel, 0, 1)) as Triple
/* How far a clipped color lands from the OKLCH it stands for, in OKLab. */
function clipError(clipped: Triple, [lightness, chroma, hue]: Triple) {
const [l, a, b] = linearToOklab(clipped)
const angle = (hue * Math.PI) / 180
return Math.hypot(
l - lightness / 100,
a - chroma * Math.cos(angle),
b - chroma * Math.sin(angle),
)
}
/* CSS Color 4 gamut mapping: lower chroma at the same lightness and hue
until clipping the rest moves the color less than a just-noticeable
difference (0.02 in OKLab), then clip. Pure chroma reduction drifted up to
27 units in hex from what a browser paints for Tailwind's P3 shades. */
function oklchToRgb([lightness, chroma, hue]: Triple): Triple {
const encode = (linear: Triple) =>
linear.map((channel) => fromLinear(channel)) as Triple
if (lightness >= 100) return [255, 255, 255]
if (lightness <= 0) return [0, 0, 0]
const target: Triple = [lightness, Math.max(0, chroma), hue]
const origin = oklchToLinear(target)
if (inSrgb(origin)) return encode(clipLinear(origin))
let clipped = clipLinear(origin)
if (clipError(clipped, target) < 0.02) return encode(clipped)
let low = 0
let high = target[1]
let lowInGamut = true
while (high - low > 1e-4) {
const mid = (low + high) / 2
const current: Triple = [lightness, mid, hue]
const linear = oklchToLinear(current)
if (lowInGamut && inSrgb(linear)) {
low = mid
continue
}
clipped = clipLinear(linear)
const error = clipError(clipped, current)
if (error < 0.02) {
if (0.02 - error < 1e-4) break
lowInGamut = false
low = mid
} else {
high = mid
}
}
return encode(clipped)
}
function toRgb(color: ColorPickerColor): Triple {
const { space, channels } = color
if (space === 'rgb') return channels
if (space === 'hsv') return hsvToRgb(channels)
if (space === 'hsl') return hsvToRgb(hslToHsv(channels))
return oklchToRgb(channels)
}
/** A color's channels in another space. */
export function toSpace(
color: ColorPickerColor,
space: ColorPickerColorSpace,
): Triple {
const { space: from, channels } = color
if (from === space) return channels
if (from === 'hsv' && space === 'hsl') return hsvToHsl(channels)
if (from === 'hsl' && space === 'hsv') return hslToHsv(channels)
const rgb = toRgb(color)
const hue = from === 'rgb' ? 0 : channels[from === 'oklch' ? 2 : 0]
if (space === 'rgb') return rgb
if (space === 'hsv') return rgbToHsv(rgb, hue)
if (space === 'hsl') return hsvToHsl(rgbToHsv(rgb, hue))
return rgbToOklch(rgb, hue)
}
/** Whether a color fits sRGB. OKLCH can reach past it; the picker then maps it into sRGB the way CSS does. */
export function isColorInSrgb(color: ColorPickerColor) {
return color.space !== 'oklch' || inSrgb(oklchToLinear(color.channels))
}
const HEX_PATTERN = /^#?([\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/
/* [\s\S], not ".", so a function pretty-printed over several lines reads. */
const FUNCTION_PATTERN = /^([a-z][a-z\d-]*)\(([\s\S]*)\)$/
const NUMBER_PATTERN =
/^([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)(%|deg|rad|grad|turn)?$/
/* The 148 CSS named colors, each name then its hex: about 2.3 KB, checked
against Chrome, and safe to read on the server unlike a canvas. */
const NAMED_COLORS =
'alicebluef0f8ff antiquewhitefaebd7 aqua00ffff aquamarine7fffd4 ' +
'azuref0ffff beigef5f5dc bisqueffe4c4 black000000 blanchedalmondffebcd ' +
'blue0000ff blueviolet8a2be2 browna52a2a burlywooddeb887 ' +
'cadetblue5f9ea0 chartreuse7fff00 chocolated2691e coralff7f50 ' +
'cornflowerblue6495ed cornsilkfff8dc crimsondc143c cyan00ffff ' +
'darkblue00008b darkcyan008b8b darkgoldenrodb8860b darkgraya9a9a9 ' +
'darkgreen006400 darkgreya9a9a9 darkkhakibdb76b darkmagenta8b008b ' +
'darkolivegreen556b2f darkorangeff8c00 darkorchid9932cc darkred8b0000 ' +
'darksalmone9967a darkseagreen8fbc8f darkslateblue483d8b ' +
'darkslategray2f4f4f darkslategrey2f4f4f darkturquoise00ced1 ' +
'darkviolet9400d3 deeppinkff1493 deepskyblue00bfff dimgray696969 ' +
'dimgrey696969 dodgerblue1e90ff firebrickb22222 floralwhitefffaf0 ' +
'forestgreen228b22 fuchsiaff00ff gainsborodcdcdc ghostwhitef8f8ff ' +
'goldffd700 goldenroddaa520 gray808080 green008000 greenyellowadff2f ' +
'grey808080 honeydewf0fff0 hotpinkff69b4 indianredcd5c5c indigo4b0082 ' +
'ivoryfffff0 khakif0e68c lavendere6e6fa lavenderblushfff0f5 ' +
'lawngreen7cfc00 lemonchiffonfffacd lightblueadd8e6 lightcoralf08080 ' +
'lightcyane0ffff lightgoldenrodyellowfafad2 lightgrayd3d3d3 ' +
'lightgreen90ee90 lightgreyd3d3d3 lightpinkffb6c1 lightsalmonffa07a ' +
'lightseagreen20b2aa lightskyblue87cefa lightslategray778899 ' +
'lightslategrey778899 lightsteelblueb0c4de lightyellowffffe0 lime00ff00 ' +
'limegreen32cd32 linenfaf0e6 magentaff00ff maroon800000 ' +
'mediumaquamarine66cdaa mediumblue0000cd mediumorchidba55d3 ' +
'mediumpurple9370db mediumseagreen3cb371 mediumslateblue7b68ee ' +
'mediumspringgreen00fa9a mediumturquoise48d1cc mediumvioletredc71585 ' +
'midnightblue191970 mintcreamf5fffa mistyroseffe4e1 moccasinffe4b5 ' +
'navajowhiteffdead navy000080 oldlacefdf5e6 olive808000 olivedrab6b8e23 ' +
'orangeffa500 orangeredff4500 orchidda70d6 palegoldenrodeee8aa ' +
'palegreen98fb98 paleturquoiseafeeee palevioletreddb7093 ' +
'papayawhipffefd5 peachpuffffdab9 perucd853f pinkffc0cb plumdda0dd ' +
'powderblueb0e0e6 purple800080 rebeccapurple663399 redff0000 ' +
'rosybrownbc8f8f royalblue4169e1 saddlebrown8b4513 salmonfa8072 ' +
'sandybrownf4a460 seagreen2e8b57 seashellfff5ee siennaa0522d ' +
'silverc0c0c0 skyblue87ceeb slateblue6a5acd slategray708090 ' +
'slategrey708090 snowfffafa springgreen00ff7f steelblue4682b4 tand2b48c ' +
'teal008080 thistled8bfd8 tomatoff6347 turquoise40e0d0 violetee82ee ' +
'wheatf5deb3 whiteffffff whitesmokef5f5f5 yellowffff00 ' +
'yellowgreen9acd32'
let namedColors: Map | null = null
function namedColor(name: string) {
namedColors ??= new Map(
NAMED_COLORS.split(' ').map((entry) => [
entry.slice(0, -6),
entry.slice(-6),
]),
)
return namedColors.get(name)
}
/* One CSS number: 100% is worth `percentOf`, computed as value * percentOf
/ 100 so 50% of 255 is exactly 127.5; angles only where allowed. */
function readNumber(token: string, percentOf: number, angle = false) {
if (token === 'none') return 0
const match = NUMBER_PATTERN.exec(token)
if (!match) return null
const value = Number(match[1])
if (!Number.isFinite(value)) return null
const unit = match[2]
if (!unit) return value
if (unit === '%') return angle ? null : (value * percentOf) / 100
if (!angle) return null
if (unit === 'rad') return (value * 180) / Math.PI
if (unit === 'grad') return value * 0.9
if (unit === 'turn') return value * 360
return value
}
type Matrix = [Triple, Triple, Triple]
const multiply = (matrix: Matrix, [x, y, z]: Triple): Triple =>
matrix.map((row) => row[0] * x + row[1] * y + row[2] * z) as Triple
const compose = (outer: Matrix, inner: Matrix): Matrix =>
outer.map((row) =>
[0, 1, 2].map(
(column) =>
row[0] * inner[0][column] +
row[1] * inner[1][column] +
row[2] * inner[2][column],
),
) as Matrix
/* CSS Color 4's matrices: XYZ D65 to linear sRGB, each RGB space to XYZ,
and Bradford from D50, the white of lab(), lch() and ProPhoto. */
const XYZ_TO_SRGB: Matrix = [
[12831 / 3959, -329 / 214, -1974 / 3959],
[-851781 / 878810, 1648619 / 878810, 36519 / 878810],
[705 / 12673, -2585 / 12673, 705 / 667],
]
const D50_TO_D65: Matrix = [
[0.955473421488075, -0.02309845494876471, 0.06325924320057072],
[-0.0283697093338637, 1.0099953980813041, 0.021041441191917323],
[0.012314014864481998, -0.020507649298898964, 1.330365926242124],
]
const D50_TO_SRGB = compose(XYZ_TO_SRGB, D50_TO_D65)
/* sRGB's curve, carried past 0 and 1 by symmetry, as color() allows. */
const decodeSrgb = (value: number) => {
const size = Math.abs(value)
return (
Math.sign(value) *
(size <= 0.04045 ? size / 12.92 : ((size + 0.055) / 1.055) ** 2.4)
)
}
const RGB_SPACES: Record<
string,
{ decode: (value: number) => number; toSrgb: Matrix | null }
> = {
srgb: { decode: decodeSrgb, toSrgb: null },
'srgb-linear': { decode: (value) => value, toSrgb: null },
'display-p3': {
decode: decodeSrgb,
toSrgb: compose(XYZ_TO_SRGB, [
[0.4865709486482162, 0.26566769316909306, 0.1982172852343625],
[0.2289745640697488, 0.6917385218365064, 0.079286914093745],
[0, 0.04511338185890264, 1.043944368900976],
]),
},
'a98-rgb': {
decode: (value) => Math.sign(value) * Math.abs(value) ** (563 / 256),
toSrgb: compose(XYZ_TO_SRGB, [
[573536 / 994567, 263643 / 1420810, 187206 / 994567],
[591459 / 1989134, 6239551 / 9945670, 374412 / 4972835],
[53769 / 1989134, 351524 / 4972835, 4929758 / 4972835],
]),
},
'prophoto-rgb': {
decode: (value) => {
const size = Math.abs(value)
return size <= 16 / 512
? value / 16
: Math.sign(value) * size ** 1.8
},
toSrgb: compose(D50_TO_SRGB, [
[0.7977666449006423, 0.13518129740053308, 0.0313477341283922],
[0.2880748288194013, 0.711835234241873, 0.00008993693872564],
[0, 0, 0.8251046025104602],
]),
},
rec2020: {
decode: (value) => {
const size = Math.abs(value)
return size < 0.018053968510807 * 4.5
? value / 4.5
: Math.sign(value) *
((size + 0.09929682680944) / 1.09929682680944) **
(1 / 0.45)
},
toSrgb: compose(XYZ_TO_SRGB, [
[0.6369580483012914, 0.14461690358620832, 0.1688809751641721],
[0.2627002120112671, 0.6779980715188708, 0.05930171646986196],
[0, 0.028072693049087428, 1.060985057710791],
]),
},
xyz: { decode: (value) => value, toSrgb: XYZ_TO_SRGB },
'xyz-d65': { decode: (value) => value, toSrgb: XYZ_TO_SRGB },
'xyz-d50': { decode: (value) => value, toSrgb: D50_TO_SRGB },
}
/* CIE Lab, D50 white, to XYZ D50, as CSS Color 4 writes it. */
function labToXyz([lightness, a, b]: Triple): Triple {
const kappa = 24389 / 27
const epsilon = 216 / 24389
const fy = (lightness + 16) / 116
const fx = a / 500 + fy
const fz = fy - b / 200
const x = fx ** 3 > epsilon ? fx ** 3 : (116 * fx - 16) / kappa
const y = lightness > kappa * epsilon ? fy ** 3 : lightness / kappa
const z = fz ** 3 > epsilon ? fz ** 3 : (116 * fz - 16) / kappa
return [x * (0.3457 / 0.3585), y, z * ((1 - 0.3457 - 0.3585) / 0.3585)]
}
/* A color that can reach past sRGB is kept as OKLCH, so nothing is clipped
until a format or a screen needs sRGB. */
const fromLinearSrgb = (linear: Triple): Triple =>
oklabToOklch(linearToOklab(linear))
const isUnit = (channels: Triple) =>
channels.every((channel) => channel >= -1e-6 && channel <= 1 + 1e-6)
/* The channels of one function, as a color in the picker's spaces. */
export function readChannels(
name: string,
parts: string[],
): { space: ColorPickerColorSpace; channels: Triple } | null {
if (name === 'rgb') {
const rgb = parts.map((part) => readNumber(part, 255))
if (rgb.some((value) => value === null)) return null
return {
space: 'rgb',
channels: rgb.map((value) => clamp(value!, 0, 255)) as Triple,
}
}
if (name === 'hsl' || name === 'hsv' || name === 'hsb' || name === 'hwb') {
const hue = readNumber(parts[0], 1, true)
const first = readNumber(parts[1], 100)
const second = readNumber(parts[2], 100)
if (hue === null || first === null || second === null) return null
const x = clamp(first, 0, 100)
const y = clamp(second, 0, 100)
if (name === 'hsl') return { space: 'hsl', channels: [hue, x, y] }
if (name !== 'hwb') return { space: 'hsv', channels: [hue, x, y] }
/* hwb(): whiteness and blackness are HSB's saturation and brightness
read from the other end; summing past 100% gives their gray. */
const total = x + y
if (total >= 100) {
return { space: 'hsv', channels: [hue, 0, (x / total) * 100] }
}
const brightness = 100 - y
return {
space: 'hsv',
channels: [hue, (1 - x / brightness) * 100, brightness],
}
}
if (name === 'oklch' || name === 'oklab') {
const lightness = readNumber(parts[0], 1)
const second = readNumber(parts[1], 0.4)
const third =
name === 'oklch'
? readNumber(parts[2], 1, true)
: readNumber(parts[2], 0.4)
if (lightness === null || second === null || third === null) return null
const l = clamp(lightness, 0, 1)
if (name === 'oklch') {
return {
space: 'oklch',
channels: [l * 100, Math.max(0, second), third],
}
}
return {
space: 'oklch',
channels: oklabToOklch([l, second, third]),
}
}
if (name === 'lab' || name === 'lch') {
const lightness = readNumber(parts[0], 100)
const second = readNumber(parts[1], name === 'lab' ? 125 : 150)
const third =
name === 'lch'
? readNumber(parts[2], 1, true)
: readNumber(parts[2], 125)
if (lightness === null || second === null || third === null) return null
const l = clamp(lightness, 0, 100)
const angle = (third * Math.PI) / 180
const [a, b] =
name === 'lab'
? [second, third]
: [
Math.max(0, second) * Math.cos(angle),
Math.max(0, second) * Math.sin(angle),
]
return {
space: 'oklch',
channels: fromLinearSrgb(
multiply(D50_TO_SRGB, labToXyz([l, a, b])),
),
}
}
if (name === 'color') {
if (!Object.hasOwn(RGB_SPACES, parts[0])) return null
const target = RGB_SPACES[parts[0]]
if (!target || parts.length !== 4) return null
const values = parts.slice(1).map((part) => readNumber(part, 1))
if (values.some((value) => value === null)) return null
const channels = values as Triple
if (parts[0] === 'srgb' && isUnit(channels)) {
return {
space: 'rgb',
channels: channels.map(
(value) => clamp(value, 0, 1) * 255,
) as Triple,
}
}
const linear = channels.map(target.decode) as Triple
return {
space: 'oklch',
channels: fromLinearSrgb(
target.toSrgb ? multiply(target.toSrgb, linear) : linear,
),
}
}
return null
}
/**
* Reads a CSS color: hex with 3, 4, 6 or 8 digits, `#` optional; the 148
* named colors and `transparent`; `rgb()`, `hsl()`, `hwb()`, `lab()`,
* `lch()`, `oklab()`, `oklch()` and `color()` in any of CSS Color 4's RGB
* and XYZ spaces, plus `hsb()` or `hsv()`; modern or comma syntax, with or
* without alpha. A color that can fall outside sRGB is kept as OKLCH.
* Anything else, `var()` and `currentColor` included, is `null`.
*/
export function parseColor(
input: string | null | undefined,
): ColorPickerColor | null {
if (typeof input !== 'string') return null
const text = input.trim().toLowerCase()
if (!text) return null
if (text === 'transparent') {
return { space: 'rgb', channels: [0, 0, 0], alpha: 0 }
}
const hex = HEX_PATTERN.exec(namedColor(text) ?? text)
if (hex) {
let digits = hex[1]
if (digits.length <= 4) {
digits = [...digits].map((digit) => digit + digit).join('')
}
const byte = (index: number) =>
parseInt(digits.slice(index, index + 2), 16)
return {
space: 'rgb',
channels: [byte(0), byte(2), byte(4)],
alpha: digits.length === 8 ? byte(6) / 255 : 1,
}
}
const call = FUNCTION_PATTERN.exec(text)
if (!call) return null
const name = call[1].replace(/a$/, '')
const [main, slash, ...rest] = call[2].split('/')
if (rest.length > 0) return null
const parts = main.split(/[\s,]+/).filter(Boolean)
/* color() names its space first, and takes alpha only after a slash. */
const count = name === 'color' ? 4 : 3
/* Alpha follows a slash, or is the fourth value of the comma syntax. */
const alphaToken =
slash?.trim() ?? (name === 'color' ? undefined : parts[3])
if (
parts.length !== count &&
!(name !== 'color' && parts.length === 4 && slash === undefined)
) {
return null
}
const alpha = alphaToken === undefined ? 1 : readNumber(alphaToken, 1)
const read = readChannels(name, parts.slice(0, count))
if (alpha === null || !read) return null
const channels = read.channels
if (channels.some((channel) => !Number.isFinite(channel))) return null
if (read.space !== 'rgb') {
const hueIndex = read.space === 'oklch' ? 2 : 0
channels[hueIndex] = wrapHue(channels[hueIndex])
}
return { space: read.space, channels, alpha: clamp(alpha, 0, 1) }
}
const CSS_WIDE = /^(inherit|initial|unset|revert|revert-layer|currentcolor)$/
/* Whatever else the browser paints (color-mix(), relative colors,
light-dark(), system colors), resolved by its computed style, which
serializes as a function parseColor reads. Two parents of different
colors expose anything that inherits (var() with no value, a CSS-wide
keyword); a canvas would have read those as black. Only typing reaches
this, never a render. */
export function parseWithBrowser(text: string): ColorPickerColor | null {
if (
typeof document === 'undefined' ||
CSS_WIDE.test(text.toLowerCase()) ||
!CSS.supports?.('color', text)
) {
return null
}
const parent = document.createElement('div')
const probe = document.createElement('div')
parent.style.display = 'none'
probe.style.color = text
parent.append(probe)
document.body.append(parent)
parent.style.color = 'rgb(1, 2, 3)'
const first = getComputedStyle(probe).color
parent.style.color = 'rgb(4, 5, 6)'
const second = getComputedStyle(probe).color
parent.remove()
return first === second ? parseColor(first) : null
}
/**
* Writes a color in a format. HEX gains a fourth byte and the others a
* `/ alpha` only when the color is translucent; OKLCH keeps channels outside
* sRGB, every other format maps the color into sRGB the way CSS does.
*/
export function formatColor(
color: ColorPickerColor,
format: ColorPickerFormat,
): string {
const alpha = clamp(color.alpha, 0, 1)
const opacityText = fixed(alpha)
const tail = opacityText !== '1' ? ` / ${opacityText}` : ''
if (format === 'hex' || format === 'rgb') {
const rgb = toRgb(color).map((channel) =>
Math.round(clamp(channel, 0, 255)),
)
if (format === 'rgb') return `rgb(${rgb.join(' ')}${tail})`
const opacity = Math.round(alpha * 255)
const bytes = opacity < 255 ? [...rgb, opacity] : rgb
return `#${bytes.map((byte) => byte.toString(16).padStart(2, '0')).join('')}`
}
if (format === 'oklch') {
const [l, c, h] = toSpace(color, 'oklch')
/* Chroma is never below 0, and a hue that rounds to 360 is 0. */
const hue = fixed(wrapHue(Number(fixed(h))))
return `oklch(${fixed(l)}% ${fixed(Math.max(0, c))} ${hue}${tail})`
}
const [h, s, third] = toSpace(color, format === 'hsl' ? 'hsl' : 'hsv')
return `${format}(${fixed(wrapHue(Number(fixed(h))))} ${fixed(s)}% ${fixed(third)}%${tail})`
}
/* What CSS paints: OKLCH as itself, so a wide-gamut screen shows it. */
export const toCss = (color: ColorPickerColor) =>
formatColor(color, color.space === 'oklch' ? 'oklch' : 'rgb')
const DEFAULT_SPACE: Record = {
hue: 'hsv',
saturation: 'hsv',
brightness: 'hsv',
lightness: 'hsl',
chroma: 'oklch',
red: 'rgb',
green: 'rgb',
blue: 'rgb',
alpha: 'rgb',
}
/* A space that has no such channel falls back to the channel's own. */
export const resolveSpace = (
channel: ColorPickerChannel,
space: ColorPickerColorSpace | undefined,
) =>
channel !== 'alpha' && space && SPACE_CHANNELS[space].includes(channel)
? space
: DEFAULT_SPACE[channel]
/**
* Get the range and step for a given channel and space.
*/
export function channelRange(
space: ColorPickerColorSpace,
channel: ColorPickerChannel,
) {
if (channel === 'alpha') return { max: 1, step: 0.01 }
if (channel === 'hue') return { max: 360, step: 1 }
if (channel === 'chroma') return { max: 0.4, step: 0.004 }
return { max: space === 'rgb' ? 255 : 100, step: 1 }
}
export function readChannel(
color: ColorPickerColor,
space: ColorPickerColorSpace,
channel: ColorPickerChannel,
) {
if (channel === 'alpha') return color.alpha
return toSpace(color, space)[SPACE_CHANNELS[space].indexOf(channel)]
}
export function withChannel(
color: ColorPickerColor,
space: ColorPickerColorSpace,
channel: ColorPickerChannel,
value: number,
): ColorPickerColor {
if (channel === 'alpha') return { ...color, alpha: clamp(value, 0, 1) }
const channels = [...toSpace(color, space)] as Triple
channels[SPACE_CHANNELS[space].indexOf(channel)] = value
return { space, channels, alpha: color.alpha }
}
/* The colors a track runs through: the full spectrum for hue, so a gray
still shows where it would go, and sampled stops elsewhere, since OKLCH
and HSL lightness do not run straight in sRGB. */
export function trackStops(
color: ColorPickerColor,
space: ColorPickerColorSpace,
channel: ColorPickerChannel,
) {
const opaque = { ...color, alpha: 1 }
if (channel === 'alpha') return ['transparent', toCss(opaque)]
let base = opaque
if (channel === 'hue') {
base =
space === 'oklch'
? withChannel(
opaque,
'oklch',
'chroma',
Math.max(readChannel(opaque, 'oklch', 'chroma'), 0.12),
)
: { space: 'hsv', channels: [0, 100, 100], alpha: 1 }
}
const count =
channel === 'hue' || space === 'oklch'
? 13
: space === 'hsl' && channel === 'lightness'
? 3
: 2
const { max } = channelRange(space, channel)
const target = channel === 'hue' && space !== 'oklch' ? 'hsv' : space
return Array.from({ length: count }, (_, index) =>
formatColor(
withChannel(base, target, channel, (max * index) / (count - 1)),
'rgb',
),
)
}
type FieldChannel = ColorPickerChannel | 'hex'
export const FORMAT_FIELDS: Record<
ColorPickerFormat,
{ space: ColorPickerColorSpace; channels: FieldChannel[] }
> = {
hex: { space: 'rgb', channels: ['hex'] },
rgb: { space: 'rgb', channels: ['red', 'green', 'blue'] },
hsl: { space: 'hsl', channels: ['hue', 'saturation', 'lightness'] },
hsb: { space: 'hsv', channels: ['hue', 'saturation', 'brightness'] },
oklch: { space: 'oklch', channels: ['lightness', 'chroma', 'hue'] },
}
export function channelText(
color: ColorPickerColor,
space: ColorPickerColorSpace,
channel: FieldChannel,
) {
if (channel === 'hex') {
return formatColor({ ...color, alpha: 1 }, 'hex')
.slice(1)
.toUpperCase()
}
if (channel === 'alpha') return `${Math.round(color.alpha * 100)}%`
const value = readChannel(color, space, channel)
if (channel === 'chroma') return fixed(value, 3)
return space === 'oklch' ? fixed(value, 1) : String(Math.round(value))
}
const FIELD_NUMBER =
/^([+-]?(?:\d+(?:[.,]\d*)?|[.,]\d+))\s*(%|°|deg|grad|rad|turn)?$/
/* A typed channel. Hex keeps the current opacity unless it carries its own.
A number takes a comma decimal; % is a share of the channel's range, as in
CSS (50% red is 127.5, 50% chroma 0.2), and a hue takes an angle unit and
wraps, so -30 is 330. Anything else is rejected. */
export function readChannelText(
text: string,
color: ColorPickerColor,
space: ColorPickerColorSpace,
channel: FieldChannel,
): ColorPickerColor | null {
if (channel === 'hex') {
const digits = text.trim().replace(/^#/, '')
const parsed = /^[\da-f]+$/i.test(digits) ? parseColor(digits) : null
if (!parsed) return null
return digits.length === 4 || digits.length === 8
? parsed
: { ...parsed, alpha: color.alpha }
}
const match = FIELD_NUMBER.exec(text.trim().toLowerCase())
if (!match) return null
const value = Number(match[1].replace(',', '.'))
const unit = match[2]
if (!Number.isFinite(value)) return null
if (channel === 'hue') {
if (unit === '%') return null
const degrees =
unit === 'rad'
? (value * 180) / Math.PI
: unit === 'grad'
? value * 0.9
: unit === 'turn'
? value * 360
: value
return withChannel(color, space, channel, wrapHue(degrees))
}
if (unit && unit !== '%') return null
if (channel === 'alpha')
return { ...color, alpha: clamp(value / 100, 0, 1) }
const { max } = channelRange(space, channel)
const scaled = unit === '%' ? (value * max) / 100 : value
return withChannel(color, space, channel, clamp(scaled, 0, max))
}
export const CHECKER =
'repeating-conic-gradient(var(--color-muted) 0 25%, var(--color-background) 0 50%) 50% / 8px 8px'
export const EMPTY_COLOR: ColorPickerColor = {
space: 'hsv',
channels: [0, 0, 0],
alpha: 1,
}
```
#### src/components/ui/color-picker/color-picker-content.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import { PopoverContent } from "../popover/index.ts"
import ColorPickerPanel from "./color-picker-panel.astro"
import type { ColorPickerContentProps } from "./types.ts"
type Props = HTMLAttributes<"div"> & ColorPickerContentProps
const { class: className, align = "start", ...props } = Astro.props
---
```
#### src/components/ui/color-picker/color-picker-fields.astro
```astro
---
import type { HTMLAttributes } from "astro/types"
import ChevronDownIcon from "@lucide/astro/icons/chevron-down"
import { cn } from "cn"
import { InputGroup } from "../input-group/index.ts"
import ColorPickerChannelInput from "./color-picker-channel-input.astro"
import {
COLOR_PICKER_FORMATS,
FORMAT_FIELDS,
FORMAT_LABELS,
} from "./color-picker-color.ts"
import type { ColorPickerFieldsProps } from "./types.ts"
type Props = HTMLAttributes<"div"> & ColorPickerFieldsProps
const {
class: className,
defaultFormat = "hex",
formats = COLOR_PICKER_FORMATS,
...props
} = Astro.props
const available = formats.length ? [...new Set(formats)] : [defaultFormat]
const selected = available.includes(defaultFormat)
? defaultFormat
: available[0]!
---