Repository: withastro/starlight Branch: main Commit: d87102166683 Files: 874 Total size: 3.8 MB Directory structure: gitextract_q6rx5rxj/ ├── .changeset/ │ ├── README.md │ └── config.json ├── .devcontainer/ │ ├── Dockerfile │ ├── devcontainer.json │ └── welcome-message.txt ├── .git-blame-ignore-revs ├── .github/ │ ├── DISCUSSION_TEMPLATE/ │ │ ├── docs-suggestions.yml │ │ └── feature-requests.yml │ ├── ISSUE_TEMPLATE/ │ │ ├── ---01-bug-report.yml │ │ ├── ---02-docs-issue.yml │ │ └── config.yml │ ├── PULL_REQUEST_TEMPLATE.md │ ├── labeler.yml │ ├── renovate.json5 │ └── workflows/ │ ├── ci.yml │ ├── congratsbot.yml │ ├── file-icons.yml │ ├── format.yml │ ├── lunaria.yml │ ├── pr-labeler.yml │ ├── preview-release.yml │ ├── release.yml │ ├── size-limit.yml │ └── welcome-bot.yml ├── .gitignore ├── .npmrc ├── .prettierignore ├── .prettierrc ├── .vscode/ │ ├── extensions.json │ └── launch.json ├── CONTRIBUTING.md ├── LICENSE ├── docs/ │ ├── .gitignore │ ├── README.md │ ├── __a11y__/ │ │ ├── docs.test.ts │ │ └── test-utils.ts │ ├── astro.config.mjs │ ├── grammars/ │ │ ├── README.md │ │ ├── generate.mjs │ │ └── markdoc.tmLanguage.json │ ├── lunaria/ │ │ ├── components.ts │ │ ├── renderer.config.ts │ │ └── styles.css │ ├── lunaria.config.json │ ├── package.json │ ├── playwright.config.ts │ ├── public/ │ │ ├── _headers │ │ └── _redirects │ ├── src/ │ │ ├── assets/ │ │ │ ├── landing.css │ │ │ └── robots.txt │ │ ├── components/ │ │ │ ├── about-astro.astro │ │ │ ├── component-preview.astro │ │ │ ├── fluid-grid.astro │ │ │ ├── icons-list.astro │ │ │ ├── languages-list.astro │ │ │ ├── media-card.astro │ │ │ ├── showcase-card.astro │ │ │ ├── showcase-sites.astro │ │ │ ├── sidebar-preview.astro │ │ │ ├── social-links-type.astro │ │ │ ├── testimonial-grid.astro │ │ │ ├── testimonial.astro │ │ │ ├── theme-designer/ │ │ │ │ ├── atom.ts │ │ │ │ ├── color-editor.astro │ │ │ │ ├── color-lib.ts │ │ │ │ ├── contrast-level.astro │ │ │ │ ├── palette.astro │ │ │ │ ├── presets.astro │ │ │ │ ├── preview.astro │ │ │ │ ├── store.ts │ │ │ │ └── value-slider.astro │ │ │ ├── theme-designer.astro │ │ │ ├── theme-grid.astro │ │ │ ├── theme-image.astro │ │ │ ├── ui-strings-list.astro │ │ │ ├── youtube-card.astro │ │ │ └── youtube-grid.astro │ │ ├── content/ │ │ │ ├── docs/ │ │ │ │ ├── 404.md │ │ │ │ ├── components/ │ │ │ │ │ ├── asides.mdx │ │ │ │ │ ├── badges.mdx │ │ │ │ │ ├── card-grids.mdx │ │ │ │ │ ├── cards.mdx │ │ │ │ │ ├── code.mdx │ │ │ │ │ ├── file-tree.mdx │ │ │ │ │ ├── icons.mdx │ │ │ │ │ ├── link-buttons.mdx │ │ │ │ │ ├── link-cards.mdx │ │ │ │ │ ├── steps.mdx │ │ │ │ │ ├── tabs.mdx │ │ │ │ │ └── using-components.mdx │ │ │ │ ├── da/ │ │ │ │ │ ├── 404.md │ │ │ │ │ └── index.mdx │ │ │ │ ├── de/ │ │ │ │ │ ├── 404.md │ │ │ │ │ ├── components/ │ │ │ │ │ │ ├── asides.mdx │ │ │ │ │ │ ├── badges.mdx │ │ │ │ │ │ ├── card-grids.mdx │ │ │ │ │ │ ├── cards.mdx │ │ │ │ │ │ ├── code.mdx │ │ │ │ │ │ ├── file-tree.mdx │ │ │ │ │ │ ├── icons.mdx │ │ │ │ │ │ ├── link-buttons.mdx │ │ │ │ │ │ ├── link-cards.mdx │ │ │ │ │ │ ├── steps.mdx │ │ │ │ │ │ ├── tabs.mdx │ │ │ │ │ │ └── using-components.mdx │ │ │ │ │ ├── environmental-impact.md │ │ │ │ │ ├── getting-started.mdx │ │ │ │ │ ├── guides/ │ │ │ │ │ │ ├── authoring-content.mdx │ │ │ │ │ │ ├── css-and-tailwind.mdx │ │ │ │ │ │ ├── customization.mdx │ │ │ │ │ │ ├── i18n.mdx │ │ │ │ │ │ ├── overriding-components.mdx │ │ │ │ │ │ ├── pages.mdx │ │ │ │ │ │ ├── project-structure.mdx │ │ │ │ │ │ ├── route-data.mdx │ │ │ │ │ │ ├── sidebar.mdx │ │ │ │ │ │ └── site-search.mdx │ │ │ │ │ ├── index.mdx │ │ │ │ │ ├── manual-setup.mdx │ │ │ │ │ ├── reference/ │ │ │ │ │ │ ├── configuration.mdx │ │ │ │ │ │ ├── frontmatter.md │ │ │ │ │ │ ├── icons.mdx │ │ │ │ │ │ ├── overrides.md │ │ │ │ │ │ ├── plugins.md │ │ │ │ │ │ └── route-data.mdx │ │ │ │ │ └── resources/ │ │ │ │ │ ├── community-content.mdx │ │ │ │ │ ├── plugins.mdx │ │ │ │ │ ├── showcase.mdx │ │ │ │ │ └── themes.mdx │ │ │ │ ├── environmental-impact.md │ │ │ │ ├── es/ │ │ │ │ │ ├── 404.md │ │ │ │ │ ├── components/ │ │ │ │ │ │ ├── asides.mdx │ │ │ │ │ │ ├── badges.mdx │ │ │ │ │ │ ├── card-grids.mdx │ │ │ │ │ │ ├── cards.mdx │ │ │ │ │ │ ├── code.mdx │ │ │ │ │ │ ├── file-tree.mdx │ │ │ │ │ │ ├── icons.mdx │ │ │ │ │ │ ├── link-buttons.mdx │ │ │ │ │ │ ├── link-cards.mdx │ │ │ │ │ │ ├── steps.mdx │ │ │ │ │ │ ├── tabs.mdx │ │ │ │ │ │ └── using-components.mdx │ │ │ │ │ ├── environmental-impact.md │ │ │ │ │ ├── getting-started.mdx │ │ │ │ │ ├── guides/ │ │ │ │ │ │ ├── authoring-content.mdx │ │ │ │ │ │ ├── css-and-tailwind.mdx │ │ │ │ │ │ ├── customization.mdx │ │ │ │ │ │ ├── i18n.mdx │ │ │ │ │ │ ├── overriding-components.mdx │ │ │ │ │ │ ├── pages.mdx │ │ │ │ │ │ ├── project-structure.mdx │ │ │ │ │ │ ├── route-data.mdx │ │ │ │ │ │ ├── sidebar.mdx │ │ │ │ │ │ └── site-search.mdx │ │ │ │ │ ├── index.mdx │ │ │ │ │ ├── manual-setup.mdx │ │ │ │ │ ├── reference/ │ │ │ │ │ │ ├── configuration.mdx │ │ │ │ │ │ ├── frontmatter.md │ │ │ │ │ │ ├── icons.mdx │ │ │ │ │ │ ├── overrides.md │ │ │ │ │ │ ├── plugins.md │ │ │ │ │ │ └── route-data.mdx │ │ │ │ │ └── resources/ │ │ │ │ │ ├── community-content.mdx │ │ │ │ │ ├── plugins.mdx │ │ │ │ │ ├── showcase.mdx │ │ │ │ │ └── themes.mdx │ │ │ │ ├── fr/ │ │ │ │ │ ├── 404.md │ │ │ │ │ ├── components/ │ │ │ │ │ │ ├── asides.mdx │ │ │ │ │ │ ├── badges.mdx │ │ │ │ │ │ ├── card-grids.mdx │ │ │ │ │ │ ├── cards.mdx │ │ │ │ │ │ ├── code.mdx │ │ │ │ │ │ ├── file-tree.mdx │ │ │ │ │ │ ├── icons.mdx │ │ │ │ │ │ ├── link-buttons.mdx │ │ │ │ │ │ ├── link-cards.mdx │ │ │ │ │ │ ├── steps.mdx │ │ │ │ │ │ ├── tabs.mdx │ │ │ │ │ │ └── using-components.mdx │ │ │ │ │ ├── environmental-impact.md │ │ │ │ │ ├── getting-started.mdx │ │ │ │ │ ├── guides/ │ │ │ │ │ │ ├── authoring-content.mdx │ │ │ │ │ │ ├── css-and-tailwind.mdx │ │ │ │ │ │ ├── customization.mdx │ │ │ │ │ │ ├── i18n.mdx │ │ │ │ │ │ ├── overriding-components.mdx │ │ │ │ │ │ ├── pages.mdx │ │ │ │ │ │ ├── project-structure.mdx │ │ │ │ │ │ ├── route-data.mdx │ │ │ │ │ │ ├── sidebar.mdx │ │ │ │ │ │ └── site-search.mdx │ │ │ │ │ ├── index.mdx │ │ │ │ │ ├── manual-setup.mdx │ │ │ │ │ ├── reference/ │ │ │ │ │ │ ├── configuration.mdx │ │ │ │ │ │ ├── frontmatter.md │ │ │ │ │ │ ├── icons.mdx │ │ │ │ │ │ ├── overrides.md │ │ │ │ │ │ ├── plugins.md │ │ │ │ │ │ └── route-data.mdx │ │ │ │ │ └── resources/ │ │ │ │ │ ├── community-content.mdx │ │ │ │ │ ├── plugins.mdx │ │ │ │ │ ├── showcase.mdx │ │ │ │ │ └── themes.mdx │ │ │ │ ├── getting-started.mdx │ │ │ │ ├── guides/ │ │ │ │ │ ├── authoring-content.mdx │ │ │ │ │ ├── css-and-tailwind.mdx │ │ │ │ │ ├── customization.mdx │ │ │ │ │ ├── i18n.mdx │ │ │ │ │ ├── overriding-components.mdx │ │ │ │ │ ├── pages.mdx │ │ │ │ │ ├── project-structure.mdx │ │ │ │ │ ├── route-data.mdx │ │ │ │ │ ├── sidebar.mdx │ │ │ │ │ └── site-search.mdx │ │ │ │ ├── hi/ │ │ │ │ │ ├── 404.md │ │ │ │ │ ├── environmental-impact.md │ │ │ │ │ ├── getting-started.mdx │ │ │ │ │ └── index.mdx │ │ │ │ ├── id/ │ │ │ │ │ ├── 404.md │ │ │ │ │ ├── environmental-impact.md │ │ │ │ │ ├── getting-started.mdx │ │ │ │ │ └── index.mdx │ │ │ │ ├── index.mdx │ │ │ │ ├── it/ │ │ │ │ │ ├── 404.md │ │ │ │ │ ├── environmental-impact.md │ │ │ │ │ ├── getting-started.mdx │ │ │ │ │ ├── index.mdx │ │ │ │ │ └── resources/ │ │ │ │ │ ├── community-content.mdx │ │ │ │ │ ├── plugins.mdx │ │ │ │ │ └── showcase.mdx │ │ │ │ ├── ja/ │ │ │ │ │ ├── 404.md │ │ │ │ │ ├── components/ │ │ │ │ │ │ ├── asides.mdx │ │ │ │ │ │ ├── badges.mdx │ │ │ │ │ │ ├── card-grids.mdx │ │ │ │ │ │ ├── cards.mdx │ │ │ │ │ │ ├── code.mdx │ │ │ │ │ │ ├── file-tree.mdx │ │ │ │ │ │ ├── icons.mdx │ │ │ │ │ │ ├── link-buttons.mdx │ │ │ │ │ │ ├── link-cards.mdx │ │ │ │ │ │ ├── steps.mdx │ │ │ │ │ │ ├── tabs.mdx │ │ │ │ │ │ └── using-components.mdx │ │ │ │ │ ├── environmental-impact.md │ │ │ │ │ ├── getting-started.mdx │ │ │ │ │ ├── guides/ │ │ │ │ │ │ ├── authoring-content.mdx │ │ │ │ │ │ ├── css-and-tailwind.mdx │ │ │ │ │ │ ├── customization.mdx │ │ │ │ │ │ ├── i18n.mdx │ │ │ │ │ │ ├── overriding-components.mdx │ │ │ │ │ │ ├── pages.mdx │ │ │ │ │ │ ├── project-structure.mdx │ │ │ │ │ │ ├── route-data.mdx │ │ │ │ │ │ ├── sidebar.mdx │ │ │ │ │ │ └── site-search.mdx │ │ │ │ │ ├── index.mdx │ │ │ │ │ ├── manual-setup.mdx │ │ │ │ │ ├── reference/ │ │ │ │ │ │ ├── configuration.mdx │ │ │ │ │ │ ├── frontmatter.md │ │ │ │ │ │ ├── icons.mdx │ │ │ │ │ │ ├── overrides.md │ │ │ │ │ │ ├── plugins.md │ │ │ │ │ │ └── route-data.mdx │ │ │ │ │ └── resources/ │ │ │ │ │ ├── community-content.mdx │ │ │ │ │ ├── plugins.mdx │ │ │ │ │ ├── showcase.mdx │ │ │ │ │ └── themes.mdx │ │ │ │ ├── ko/ │ │ │ │ │ ├── 404.md │ │ │ │ │ ├── components/ │ │ │ │ │ │ ├── asides.mdx │ │ │ │ │ │ ├── badges.mdx │ │ │ │ │ │ ├── card-grids.mdx │ │ │ │ │ │ ├── cards.mdx │ │ │ │ │ │ ├── code.mdx │ │ │ │ │ │ ├── file-tree.mdx │ │ │ │ │ │ ├── icons.mdx │ │ │ │ │ │ ├── link-buttons.mdx │ │ │ │ │ │ ├── link-cards.mdx │ │ │ │ │ │ ├── steps.mdx │ │ │ │ │ │ ├── tabs.mdx │ │ │ │ │ │ └── using-components.mdx │ │ │ │ │ ├── environmental-impact.md │ │ │ │ │ ├── getting-started.mdx │ │ │ │ │ ├── guides/ │ │ │ │ │ │ ├── authoring-content.mdx │ │ │ │ │ │ ├── css-and-tailwind.mdx │ │ │ │ │ │ ├── customization.mdx │ │ │ │ │ │ ├── i18n.mdx │ │ │ │ │ │ ├── overriding-components.mdx │ │ │ │ │ │ ├── pages.mdx │ │ │ │ │ │ ├── project-structure.mdx │ │ │ │ │ │ ├── route-data.mdx │ │ │ │ │ │ ├── sidebar.mdx │ │ │ │ │ │ └── site-search.mdx │ │ │ │ │ ├── index.mdx │ │ │ │ │ ├── manual-setup.mdx │ │ │ │ │ ├── reference/ │ │ │ │ │ │ ├── configuration.mdx │ │ │ │ │ │ ├── frontmatter.md │ │ │ │ │ │ ├── icons.mdx │ │ │ │ │ │ ├── overrides.md │ │ │ │ │ │ ├── plugins.md │ │ │ │ │ │ └── route-data.mdx │ │ │ │ │ └── resources/ │ │ │ │ │ ├── community-content.mdx │ │ │ │ │ ├── plugins.mdx │ │ │ │ │ ├── showcase.mdx │ │ │ │ │ └── themes.mdx │ │ │ │ ├── manual-setup.mdx │ │ │ │ ├── pt-br/ │ │ │ │ │ ├── 404.md │ │ │ │ │ ├── environmental-impact.md │ │ │ │ │ ├── getting-started.mdx │ │ │ │ │ ├── index.mdx │ │ │ │ │ └── resources/ │ │ │ │ │ ├── community-content.mdx │ │ │ │ │ ├── plugins.mdx │ │ │ │ │ └── showcase.mdx │ │ │ │ ├── pt-pt/ │ │ │ │ │ ├── 404.md │ │ │ │ │ ├── environmental-impact.md │ │ │ │ │ ├── getting-started.mdx │ │ │ │ │ ├── index.mdx │ │ │ │ │ └── resources/ │ │ │ │ │ ├── community-content.mdx │ │ │ │ │ ├── plugins.mdx │ │ │ │ │ └── showcase.mdx │ │ │ │ ├── reference/ │ │ │ │ │ ├── configuration.mdx │ │ │ │ │ ├── frontmatter.md │ │ │ │ │ ├── icons.mdx │ │ │ │ │ ├── overrides.md │ │ │ │ │ ├── plugins.md │ │ │ │ │ └── route-data.mdx │ │ │ │ ├── resources/ │ │ │ │ │ ├── community-content.mdx │ │ │ │ │ ├── plugins.mdx │ │ │ │ │ ├── showcase.mdx │ │ │ │ │ └── themes.mdx │ │ │ │ ├── ru/ │ │ │ │ │ ├── 404.md │ │ │ │ │ ├── components/ │ │ │ │ │ │ ├── asides.mdx │ │ │ │ │ │ ├── badges.mdx │ │ │ │ │ │ ├── card-grids.mdx │ │ │ │ │ │ ├── cards.mdx │ │ │ │ │ │ ├── code.mdx │ │ │ │ │ │ ├── file-tree.mdx │ │ │ │ │ │ ├── icons.mdx │ │ │ │ │ │ ├── link-buttons.mdx │ │ │ │ │ │ ├── link-cards.mdx │ │ │ │ │ │ ├── steps.mdx │ │ │ │ │ │ ├── tabs.mdx │ │ │ │ │ │ └── using-components.mdx │ │ │ │ │ ├── environmental-impact.md │ │ │ │ │ ├── getting-started.mdx │ │ │ │ │ ├── guides/ │ │ │ │ │ │ ├── authoring-content.mdx │ │ │ │ │ │ ├── css-and-tailwind.mdx │ │ │ │ │ │ ├── customization.mdx │ │ │ │ │ │ ├── i18n.mdx │ │ │ │ │ │ ├── overriding-components.mdx │ │ │ │ │ │ ├── pages.mdx │ │ │ │ │ │ ├── project-structure.mdx │ │ │ │ │ │ ├── route-data.mdx │ │ │ │ │ │ ├── sidebar.mdx │ │ │ │ │ │ └── site-search.mdx │ │ │ │ │ ├── index.mdx │ │ │ │ │ ├── manual-setup.mdx │ │ │ │ │ ├── reference/ │ │ │ │ │ │ ├── configuration.mdx │ │ │ │ │ │ ├── frontmatter.md │ │ │ │ │ │ ├── icons.mdx │ │ │ │ │ │ ├── overrides.md │ │ │ │ │ │ ├── plugins.md │ │ │ │ │ │ └── route-data.mdx │ │ │ │ │ └── resources/ │ │ │ │ │ ├── community-content.mdx │ │ │ │ │ ├── plugins.mdx │ │ │ │ │ ├── showcase.mdx │ │ │ │ │ └── themes.mdx │ │ │ │ ├── tr/ │ │ │ │ │ ├── 404.md │ │ │ │ │ ├── environmental-impact.md │ │ │ │ │ ├── getting-started.mdx │ │ │ │ │ ├── index.mdx │ │ │ │ │ └── resources/ │ │ │ │ │ ├── community-content.mdx │ │ │ │ │ └── showcase.mdx │ │ │ │ ├── uk/ │ │ │ │ │ ├── 404.md │ │ │ │ │ ├── getting-started.mdx │ │ │ │ │ ├── index.mdx │ │ │ │ │ └── manual-setup.mdx │ │ │ │ └── zh-cn/ │ │ │ │ ├── 404.md │ │ │ │ ├── components/ │ │ │ │ │ ├── asides.mdx │ │ │ │ │ ├── badges.mdx │ │ │ │ │ ├── card-grids.mdx │ │ │ │ │ ├── cards.mdx │ │ │ │ │ ├── code.mdx │ │ │ │ │ ├── file-tree.mdx │ │ │ │ │ ├── icons.mdx │ │ │ │ │ ├── link-buttons.mdx │ │ │ │ │ ├── link-cards.mdx │ │ │ │ │ ├── steps.mdx │ │ │ │ │ ├── tabs.mdx │ │ │ │ │ └── using-components.mdx │ │ │ │ ├── environmental-impact.md │ │ │ │ ├── getting-started.mdx │ │ │ │ ├── guides/ │ │ │ │ │ ├── authoring-content.mdx │ │ │ │ │ ├── css-and-tailwind.mdx │ │ │ │ │ ├── customization.mdx │ │ │ │ │ ├── i18n.mdx │ │ │ │ │ ├── overriding-components.mdx │ │ │ │ │ ├── pages.mdx │ │ │ │ │ ├── project-structure.mdx │ │ │ │ │ ├── route-data.mdx │ │ │ │ │ ├── sidebar.mdx │ │ │ │ │ └── site-search.mdx │ │ │ │ ├── index.mdx │ │ │ │ ├── manual-setup.mdx │ │ │ │ ├── reference/ │ │ │ │ │ ├── configuration.mdx │ │ │ │ │ ├── frontmatter.md │ │ │ │ │ ├── icons.mdx │ │ │ │ │ ├── overrides.md │ │ │ │ │ ├── plugins.md │ │ │ │ │ └── route-data.mdx │ │ │ │ └── resources/ │ │ │ │ ├── community-content.mdx │ │ │ │ ├── plugins.mdx │ │ │ │ ├── showcase.mdx │ │ │ │ └── themes.mdx │ │ │ └── i18n/ │ │ │ ├── de.json │ │ │ ├── en.json │ │ │ ├── fr.json │ │ │ ├── ja.json │ │ │ ├── ko.json │ │ │ ├── ru.json │ │ │ └── zh-CN.json │ │ └── content.config.ts │ └── tsconfig.json ├── eslint.config.mjs ├── examples/ │ ├── basics/ │ │ ├── .gitignore │ │ ├── .vscode/ │ │ │ ├── extensions.json │ │ │ └── launch.json │ │ ├── README.md │ │ ├── astro.config.mjs │ │ ├── package.json │ │ ├── src/ │ │ │ ├── content/ │ │ │ │ └── docs/ │ │ │ │ ├── guides/ │ │ │ │ │ └── example.md │ │ │ │ ├── index.mdx │ │ │ │ └── reference/ │ │ │ │ └── example.md │ │ │ └── content.config.ts │ │ └── tsconfig.json │ ├── markdoc/ │ │ ├── .gitignore │ │ ├── .vscode/ │ │ │ ├── extensions.json │ │ │ └── launch.json │ │ ├── README.md │ │ ├── astro.config.mjs │ │ ├── markdoc.config.mjs │ │ ├── package.json │ │ ├── src/ │ │ │ ├── content/ │ │ │ │ └── docs/ │ │ │ │ ├── guides/ │ │ │ │ │ └── example.mdoc │ │ │ │ ├── index.mdoc │ │ │ │ └── reference/ │ │ │ │ └── example.mdoc │ │ │ └── content.config.ts │ │ └── tsconfig.json │ └── tailwind/ │ ├── .gitignore │ ├── .vscode/ │ │ ├── extensions.json │ │ └── launch.json │ ├── README.md │ ├── astro.config.mjs │ ├── package.json │ ├── src/ │ │ ├── content/ │ │ │ └── docs/ │ │ │ ├── guides/ │ │ │ │ └── example.md │ │ │ ├── index.mdx │ │ │ └── reference/ │ │ │ └── example.md │ │ ├── content.config.ts │ │ └── styles/ │ │ └── global.css │ └── tsconfig.json ├── package.json ├── packages/ │ ├── docsearch/ │ │ ├── CHANGELOG.md │ │ ├── DocSearch.astro │ │ ├── README.md │ │ ├── index.ts │ │ ├── package.json │ │ ├── schema.ts │ │ ├── variables.css │ │ └── virtual.d.ts │ ├── file-icons-generator/ │ │ ├── config.ts │ │ ├── index.ts │ │ ├── package.json │ │ └── utils/ │ │ ├── file.ts │ │ ├── font.ts │ │ └── seti.ts │ ├── markdoc/ │ │ ├── .npmignore │ │ ├── CHANGELOG.md │ │ ├── Code.astro │ │ ├── README.md │ │ ├── __tests__/ │ │ │ └── markdoc.test-d.ts │ │ ├── components.ts │ │ ├── html.mjs │ │ ├── index.mjs │ │ └── package.json │ ├── starlight/ │ │ ├── .gitignore │ │ ├── .npmignore │ │ ├── CHANGELOG.md │ │ ├── README.md │ │ ├── __e2e__/ │ │ │ ├── .gitignore │ │ │ ├── basics.test.ts │ │ │ ├── collection-config.test.ts │ │ │ ├── fixtures/ │ │ │ │ ├── basics/ │ │ │ │ │ ├── astro.config.mjs │ │ │ │ │ ├── package.json │ │ │ │ │ └── src/ │ │ │ │ │ ├── components/ │ │ │ │ │ │ ├── PurpleCard.astro │ │ │ │ │ │ └── Test.astro │ │ │ │ │ ├── content/ │ │ │ │ │ │ ├── comments/ │ │ │ │ │ │ │ └── bob.mdx │ │ │ │ │ │ ├── docs/ │ │ │ │ │ │ │ ├── anchor-heading-component.mdx │ │ │ │ │ │ │ ├── anchor-heading.md │ │ │ │ │ │ │ ├── head-propagation.mdx │ │ │ │ │ │ │ ├── headings-banner.md │ │ │ │ │ │ │ ├── headings.md │ │ │ │ │ │ │ ├── tabs-nested.mdx │ │ │ │ │ │ │ ├── tabs-unsynced.mdx │ │ │ │ │ │ │ ├── tabs-variable-height.mdx │ │ │ │ │ │ │ ├── tabs.mdx │ │ │ │ │ │ │ ├── whitespaces.mdx │ │ │ │ │ │ │ └── اللُّغَةُ-الْعَرَبِيَّةُ.md │ │ │ │ │ │ └── reviews/ │ │ │ │ │ │ └── alice.mdx │ │ │ │ │ ├── content.config.ts │ │ │ │ │ └── pages/ │ │ │ │ │ ├── [...param].astro │ │ │ │ │ ├── comments/ │ │ │ │ │ │ └── [...comment].astro │ │ │ │ │ ├── markdown-page.md │ │ │ │ │ ├── reviews/ │ │ │ │ │ │ └── [...review].astro │ │ │ │ │ └── starlight-page-css-layer-order.astro │ │ │ │ ├── custom src-dir/ │ │ │ │ │ ├── astro.config.mjs │ │ │ │ │ ├── package.json │ │ │ │ │ └── www/ │ │ │ │ │ ├── content.config.ts │ │ │ │ │ └── pages/ │ │ │ │ │ └── custom.astro │ │ │ │ ├── git/ │ │ │ │ │ ├── .gitignore │ │ │ │ │ ├── astro.config.mjs │ │ │ │ │ ├── package.json │ │ │ │ │ └── src/ │ │ │ │ │ ├── content/ │ │ │ │ │ │ └── docs/ │ │ │ │ │ │ └── index.md │ │ │ │ │ └── content.config.ts │ │ │ │ ├── legacy-collections-backwards-compat/ │ │ │ │ │ ├── astro.config.mjs │ │ │ │ │ ├── package.json │ │ │ │ │ └── src/ │ │ │ │ │ ├── content/ │ │ │ │ │ │ └── config.ts │ │ │ │ │ └── pages/ │ │ │ │ │ └── custom.astro │ │ │ │ ├── no-node-builtins/ │ │ │ │ │ ├── astro.config.mjs │ │ │ │ │ ├── package.json │ │ │ │ │ └── src/ │ │ │ │ │ ├── content/ │ │ │ │ │ │ └── docs/ │ │ │ │ │ │ └── index.md │ │ │ │ │ ├── content.config.ts │ │ │ │ │ └── noNodeModule.ts │ │ │ │ └── ssr/ │ │ │ │ ├── astro.config.mjs │ │ │ │ ├── package.json │ │ │ │ └── src/ │ │ │ │ ├── component/ │ │ │ │ │ └── ServerCheck.astro │ │ │ │ ├── content/ │ │ │ │ │ └── docs/ │ │ │ │ │ ├── 404.mdx │ │ │ │ │ ├── content.mdx │ │ │ │ │ ├── demo.mdx │ │ │ │ │ └── index.md │ │ │ │ ├── content.config.ts │ │ │ │ └── middleware.ts │ │ │ ├── git.test.ts │ │ │ ├── legacy-collections-backwards-compat.test.ts │ │ │ ├── no-node-builtins.test.ts │ │ │ ├── ssr.test.ts │ │ │ └── test-utils.ts │ │ ├── __tests__/ │ │ │ ├── absolute-favicon/ │ │ │ │ ├── absolute-favicon.test.ts │ │ │ │ └── vitest.config.ts │ │ │ ├── basics/ │ │ │ │ ├── base.test.ts │ │ │ │ ├── config-errors.test.ts │ │ │ │ ├── config.test-d.ts │ │ │ │ ├── config.test.ts │ │ │ │ ├── format-canonical.test.ts │ │ │ │ ├── format-path.test.ts │ │ │ │ ├── git.test.ts │ │ │ │ ├── i18n.test.ts │ │ │ │ ├── localizedUrl.test.ts │ │ │ │ ├── navigation-labels.test.ts │ │ │ │ ├── navigation-order.test.ts │ │ │ │ ├── navigation.test.ts │ │ │ │ ├── omit-canonical.test.ts │ │ │ │ ├── pagefind.test.ts │ │ │ │ ├── pagination-with-base.test.ts │ │ │ │ ├── route-data.test.ts │ │ │ │ ├── routing.test.ts │ │ │ │ ├── schema.test.ts │ │ │ │ ├── sitemap.test.ts │ │ │ │ ├── slugs.test.ts │ │ │ │ ├── sorting.test.ts │ │ │ │ ├── starlight-page-route-data-extend.test.ts │ │ │ │ ├── starlight-page-route-data.test.ts │ │ │ │ ├── toc.test.ts │ │ │ │ ├── translations.test.ts │ │ │ │ ├── user-config.test.ts │ │ │ │ └── vitest.config.ts │ │ │ ├── build-format-file/ │ │ │ │ ├── navigation.test.ts │ │ │ │ └── vitest.config.ts │ │ │ ├── edit-url/ │ │ │ │ ├── edit-url.test.ts │ │ │ │ └── vitest.config.ts │ │ │ ├── git-utils.ts │ │ │ ├── head/ │ │ │ │ ├── head.test.ts │ │ │ │ └── vitest.config.ts │ │ │ ├── i18n/ │ │ │ │ ├── config.test.ts │ │ │ │ ├── empty-src/ │ │ │ │ │ └── content/ │ │ │ │ │ └── i18n/ │ │ │ │ │ └── .gitkeep │ │ │ │ ├── head.test.ts │ │ │ │ ├── i18n.test.ts │ │ │ │ ├── localizedUrl.test.ts │ │ │ │ ├── malformed-json-src/ │ │ │ │ │ └── content/ │ │ │ │ │ └── i18n/ │ │ │ │ │ └── en.json │ │ │ │ ├── malformed-yaml-src/ │ │ │ │ │ └── content/ │ │ │ │ │ └── i18n/ │ │ │ │ │ └── en.yml │ │ │ │ ├── navigation-order.test.ts │ │ │ │ ├── routing.test.ts │ │ │ │ ├── src/ │ │ │ │ │ └── content/ │ │ │ │ │ └── i18n/ │ │ │ │ │ ├── en.json │ │ │ │ │ └── fr.yml │ │ │ │ ├── translations-ec.test.ts │ │ │ │ ├── translations-fs.test.ts │ │ │ │ ├── translations-with-user-config.test.ts │ │ │ │ ├── translations.test.ts │ │ │ │ └── vitest.config.ts │ │ │ ├── i18n-non-root-single-locale/ │ │ │ │ ├── config.test.ts │ │ │ │ ├── i18n.test.ts │ │ │ │ ├── localizedUrl.test.ts │ │ │ │ ├── routing.test.ts │ │ │ │ ├── slugs.test.ts │ │ │ │ ├── src/ │ │ │ │ │ └── content/ │ │ │ │ │ └── i18n/ │ │ │ │ │ └── fr.json │ │ │ │ ├── translations-fs.test.ts │ │ │ │ ├── translations-with-user-config.test.ts │ │ │ │ ├── translations.test.ts │ │ │ │ └── vitest.config.ts │ │ │ ├── i18n-root-default-locale/ │ │ │ │ ├── i18n.test.ts │ │ │ │ └── vitest.config.ts │ │ │ ├── i18n-root-locale/ │ │ │ │ ├── config.test.ts │ │ │ │ ├── i18n.test.ts │ │ │ │ ├── localizedUrl.test.ts │ │ │ │ ├── routing.test.ts │ │ │ │ ├── slugs.test.ts │ │ │ │ └── vitest.config.ts │ │ │ ├── i18n-sidebar/ │ │ │ │ ├── i18n-sidebar-fallback-slug.test.ts │ │ │ │ ├── i18n-sidebar.test.ts │ │ │ │ ├── sidebar-internal-link-error.test.ts │ │ │ │ └── vitest.config.ts │ │ │ ├── i18n-sidebar-badge-error/ │ │ │ │ ├── i18n-sidebar-badge-error.test.ts │ │ │ │ └── vitest.config.ts │ │ │ ├── i18n-single-root-locale/ │ │ │ │ ├── config.test.ts │ │ │ │ ├── i18n.test.ts │ │ │ │ ├── routing.test.ts │ │ │ │ ├── slugs.test.ts │ │ │ │ ├── src/ │ │ │ │ │ └── content/ │ │ │ │ │ └── i18n/ │ │ │ │ │ └── fr.json │ │ │ │ ├── translations-fs.test.ts │ │ │ │ ├── translations-with-user-config.test.ts │ │ │ │ ├── translations.test.ts │ │ │ │ └── vitest.config.ts │ │ │ ├── middleware/ │ │ │ │ ├── middleware.test.ts │ │ │ │ └── vitest.config.ts │ │ │ ├── plugins/ │ │ │ │ ├── config.test.ts │ │ │ │ ├── integration.test.ts │ │ │ │ ├── route-middleware.test.ts │ │ │ │ ├── translations.test.ts │ │ │ │ └── vitest.config.ts │ │ │ ├── remark-rehype/ │ │ │ │ ├── anchor-links.test.ts │ │ │ │ ├── asides.test.ts │ │ │ │ ├── code-rtl-support.test.ts │ │ │ │ ├── rehype-file-tree.test.ts │ │ │ │ ├── rehype-steps.test.ts │ │ │ │ ├── rehype-tabs.test.ts │ │ │ │ ├── remark-rehype.test.ts │ │ │ │ ├── snapshots/ │ │ │ │ │ ├── file-tree-basic.html │ │ │ │ │ ├── file-tree-comment-nodes.html │ │ │ │ │ ├── file-tree-comment-text.html │ │ │ │ │ ├── generates-anchor-link-markup.html │ │ │ │ │ ├── generates-aside-caution-custom-icon.html │ │ │ │ │ ├── generates-aside-caution-custom-label-and-icon.html │ │ │ │ │ ├── generates-aside-danger-custom-icon.html │ │ │ │ │ ├── generates-aside-danger-custom-label-and-icon.html │ │ │ │ │ ├── generates-aside-note-custom-icon.html │ │ │ │ │ ├── generates-aside-note-custom-label-and-icon.html │ │ │ │ │ ├── generates-aside-note-multiple-path-custom-icon.html │ │ │ │ │ ├── generates-aside-tip-custom-icon.html │ │ │ │ │ ├── generates-aside-tip-custom-label-and-icon.html │ │ │ │ │ ├── generates-aside.html │ │ │ │ │ ├── handles-complex-children.html │ │ │ │ │ ├── nested-asides-custom-titles.html │ │ │ │ │ └── nested-asides.html │ │ │ │ ├── utils.ts │ │ │ │ └── vitest.config.ts │ │ │ ├── sidebar/ │ │ │ │ ├── navigation-attributes.test.ts │ │ │ │ ├── navigation-badges.test.ts │ │ │ │ ├── navigation-hidden.test.ts │ │ │ │ ├── navigation-order.test.ts │ │ │ │ ├── navigation-unicode.test.ts │ │ │ │ ├── navigation.test.ts │ │ │ │ └── vitest.config.ts │ │ │ ├── sidebar-slug-error/ │ │ │ │ ├── sidebar-slug-error.test.ts │ │ │ │ └── vitest.config.ts │ │ │ ├── snapshot-serializer-astro-error.ts │ │ │ ├── test-config.ts │ │ │ ├── test-plugin-utils.ts │ │ │ ├── test-utils.ts │ │ │ └── toc-custom-config/ │ │ │ ├── toc-custom-config.test.ts │ │ │ └── vitest.config.ts │ │ ├── components/ │ │ │ ├── AnchorHeading.astro │ │ │ ├── Banner.astro │ │ │ ├── ContentNotice.astro │ │ │ ├── ContentPanel.astro │ │ │ ├── DraftContentNotice.astro │ │ │ ├── EditLink.astro │ │ │ ├── FallbackContentNotice.astro │ │ │ ├── Footer.astro │ │ │ ├── Head.astro │ │ │ ├── Header.astro │ │ │ ├── Hero.astro │ │ │ ├── LanguageSelect.astro │ │ │ ├── LastUpdated.astro │ │ │ ├── MarkdownContent.astro │ │ │ ├── MobileMenuFooter.astro │ │ │ ├── MobileMenuToggle.astro │ │ │ ├── MobileTableOfContents.astro │ │ │ ├── Page.astro │ │ │ ├── PageFrame.astro │ │ │ ├── PageSidebar.astro │ │ │ ├── PageTitle.astro │ │ │ ├── Pagination.astro │ │ │ ├── Search.astro │ │ │ ├── Select.astro │ │ │ ├── Sidebar.astro │ │ │ ├── SidebarPersister.astro │ │ │ ├── SidebarRestorePoint.astro │ │ │ ├── SidebarSublist.astro │ │ │ ├── SiteTitle.astro │ │ │ ├── SkipLink.astro │ │ │ ├── SocialIcons.astro │ │ │ ├── StarlightPage.astro │ │ │ ├── TableOfContents.astro │ │ │ ├── ThemeProvider.astro │ │ │ ├── ThemeSelect.astro │ │ │ └── TwoColumnContent.astro │ │ ├── components-internals/ │ │ │ ├── Icons.ts │ │ │ ├── SidebarPersistState.ts │ │ │ └── TableOfContents/ │ │ │ ├── TableOfContentsList.astro │ │ │ └── starlight-toc.ts │ │ ├── components.ts │ │ ├── constants.ts │ │ ├── expressive-code.d.ts │ │ ├── expressive-code.mjs │ │ ├── global.d.ts │ │ ├── i18n.d.ts │ │ ├── index.ts │ │ ├── integrations/ │ │ │ ├── asides-error.ts │ │ │ ├── asides.ts │ │ │ ├── code-rtl-support.ts │ │ │ ├── expressive-code/ │ │ │ │ ├── hast.d.ts │ │ │ │ ├── hast.mjs │ │ │ │ ├── index.ts │ │ │ │ ├── preprocessor.ts │ │ │ │ ├── themes/ │ │ │ │ │ ├── night-owl-dark.jsonc │ │ │ │ │ └── night-owl-light.jsonc │ │ │ │ ├── theming.ts │ │ │ │ └── translations.ts │ │ │ ├── heading-links.ts │ │ │ ├── pagefind.ts │ │ │ ├── remark-rehype.ts │ │ │ ├── shared/ │ │ │ │ ├── absolutePathToLang.ts │ │ │ │ ├── localeToLang.ts │ │ │ │ └── slugToLocale.ts │ │ │ ├── sitemap.ts │ │ │ ├── virtual-user-config.ts │ │ │ └── vite-layer-order.ts │ │ ├── internal.ts │ │ ├── loaders.ts │ │ ├── locals.d.ts │ │ ├── locals.ts │ │ ├── package.json │ │ ├── playwright.config.ts │ │ ├── props.ts │ │ ├── route-data.ts │ │ ├── routes/ │ │ │ ├── common.astro │ │ │ ├── ssr/ │ │ │ │ ├── 404.astro │ │ │ │ └── index.astro │ │ │ └── static/ │ │ │ ├── 404.astro │ │ │ └── index.astro │ │ ├── schema.ts │ │ ├── schemas/ │ │ │ ├── badge.ts │ │ │ ├── components.ts │ │ │ ├── expressiveCode.ts │ │ │ ├── favicon.ts │ │ │ ├── head.ts │ │ │ ├── hero.ts │ │ │ ├── i18n.ts │ │ │ ├── icon.ts │ │ │ ├── logo.ts │ │ │ ├── pagefind.ts │ │ │ ├── prevNextLink.ts │ │ │ ├── sidebar.ts │ │ │ ├── site-title.ts │ │ │ ├── social.ts │ │ │ └── tableOfContents.ts │ │ ├── style/ │ │ │ ├── anchor-links.css │ │ │ ├── asides.css │ │ │ ├── layers.css │ │ │ ├── markdown.css │ │ │ ├── print.css │ │ │ ├── props.css │ │ │ ├── reset.css │ │ │ └── util.css │ │ ├── translations/ │ │ │ ├── README.md │ │ │ ├── ar.json │ │ │ ├── ca.json │ │ │ ├── cs.json │ │ │ ├── da.json │ │ │ ├── de.json │ │ │ ├── el.json │ │ │ ├── en.json │ │ │ ├── es.json │ │ │ ├── fa.json │ │ │ ├── fi.json │ │ │ ├── fr.json │ │ │ ├── gl.json │ │ │ ├── he.json │ │ │ ├── hi.json │ │ │ ├── hu.json │ │ │ ├── id.json │ │ │ ├── index.ts │ │ │ ├── it.json │ │ │ ├── ja.json │ │ │ ├── ko.json │ │ │ ├── lv.json │ │ │ ├── nb.json │ │ │ ├── nl.json │ │ │ ├── pl.json │ │ │ ├── pt.json │ │ │ ├── ro.json │ │ │ ├── ru.json │ │ │ ├── sk.json │ │ │ ├── sv.json │ │ │ ├── th.json │ │ │ ├── tr.json │ │ │ ├── uk.json │ │ │ ├── vi.json │ │ │ ├── zh-CN.json │ │ │ └── zh-TW.json │ │ ├── types.ts │ │ ├── user-components/ │ │ │ ├── Aside.astro │ │ │ ├── Badge.astro │ │ │ ├── Card.astro │ │ │ ├── CardGrid.astro │ │ │ ├── FileTree.astro │ │ │ ├── Icon.astro │ │ │ ├── LinkButton.astro │ │ │ ├── LinkCard.astro │ │ │ ├── Steps.astro │ │ │ ├── TabItem.astro │ │ │ ├── Tabs.astro │ │ │ ├── file-tree-icons.ts │ │ │ ├── rehype-file-tree.ts │ │ │ ├── rehype-steps.ts │ │ │ └── rehype-tabs.ts │ │ ├── utils/ │ │ │ ├── base.ts │ │ │ ├── canonical.ts │ │ │ ├── collection-fs.ts │ │ │ ├── collection.ts │ │ │ ├── createPathFormatter.ts │ │ │ ├── createTranslationSystem.ts │ │ │ ├── error-map.ts │ │ │ ├── format-path.ts │ │ │ ├── generateToC.ts │ │ │ ├── git.ts │ │ │ ├── gitInlined.ts │ │ │ ├── head.ts │ │ │ ├── i18n.ts │ │ │ ├── localizedUrl.ts │ │ │ ├── navigation.ts │ │ │ ├── path.ts │ │ │ ├── plugins.ts │ │ │ ├── routing/ │ │ │ │ ├── data.ts │ │ │ │ ├── index.ts │ │ │ │ ├── middleware.ts │ │ │ │ └── types.ts │ │ │ ├── slugs.ts │ │ │ ├── starlight-page.ts │ │ │ ├── translations-fs.ts │ │ │ ├── translations.ts │ │ │ ├── types.ts │ │ │ ├── url.ts │ │ │ ├── user-config.ts │ │ │ └── validateLogoImports.ts │ │ ├── virtual-internal.d.ts │ │ ├── virtual.d.ts │ │ └── vitest.config.ts │ └── tailwind/ │ ├── CHANGELOG.md │ ├── README.md │ ├── __tests__/ │ │ └── tailwind.test.ts │ ├── package.json │ ├── tailwind.css │ └── vitest.config.ts ├── pnpm-workspace.yaml └── tsconfig.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .changeset/README.md ================================================ # Changesets Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works with multi-package repos, or single-package repos to help you version and publish your code. You can find the full documentation for it [in our repository](https://github.com/changesets/changesets) We have a quick list of common questions to get you started engaging with this project in [our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md) ================================================ FILE: .changeset/config.json ================================================ { "$schema": "https://unpkg.com/@changesets/config@2.3.0/schema.json", "changelog": [ "@changesets/changelog-github", { "repo": "withastro/starlight" } ], "commit": false, "linked": [], "access": "public", "baseBranch": "origin/main", "updateInternalDependencies": "patch", "ignore": ["starlight-docs", "@example/*", "starlight-file-icons-generator", "@e2e/*"], "___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH": { "onlyUpdatePeerDependentsWhenOutOfRange": true } } ================================================ FILE: .devcontainer/Dockerfile ================================================ # Based on https://github.com/withastro/astro/blob/main/.devcontainer/Dockerfile FROM mcr.microsoft.com/devcontainers/javascript-node:0-22 # We uninstall pnpm here, since we enable the corepack version in the postCreateCommand # This ensures we respect the "packageManager" version in package.json RUN npm uninstall -g pnpm COPY welcome-message.txt /usr/local/etc/vscode-dev-containers/first-run-notice.txt ================================================ FILE: .devcontainer/devcontainer.json ================================================ { "name": "Contribute to Starlight", "build": { "dockerfile": "Dockerfile" }, "postCreateCommand": "sudo corepack enable pnpm && pnpm config set store-dir /home/node/.pnpm-store && PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=1 pnpm install", "waitFor": "postCreateCommand", "customizations": { "codespaces": { "openFiles": ["CONTRIBUTING.md"] }, "vscode": { "extensions": ["astro-build.astro-vscode", "esbenp.prettier-vscode"] } } } ================================================ FILE: .devcontainer/welcome-message.txt ================================================ 🌟 Welcome to Starlight! 🛠️ Your environment is fully setup with all required software installed. Next steps: - Preview the docs site: cd docs && pnpm dev --host - Run tests: cd packages/starlight && pnpm test ================================================ FILE: .git-blame-ignore-revs ================================================ # Apply with: # `git config --local blame.ignoreRevsFile .git-blame-ignore-revs` # [Add Prettier and format files](https://github.com/withastro/starlight/pull/393) 9b172f5ee09697d80f301e9b70aca1946419ce24 ================================================ FILE: .github/DISCUSSION_TEMPLATE/docs-suggestions.yml ================================================ body: - type: markdown attributes: value: | Thank you for getting in touch! Please fill out this form as completely as possible. Want to report a problem with the Starlight docs? [Open a new issue](https://github.com/withastro/starlight/issues/new?assignees=&labels=&projects=&template=---02-docs-issue.yml) Want to chat before posting? [Join us in the `#starlight` channel on Discord](https://astro.build/chat) - type: textarea id: summary attributes: label: What is your idea? description: A brief, one or two sentence description of your idea for how to improve the Starlight docs. validations: required: true - type: textarea id: background attributes: label: Why is this important? description: Explain why this idea is valuable. What problems would it solve? Which users would it help? validations: required: true - type: textarea id: prior-art attributes: label: How does your idea relate to existing docs content? description: Are there specific pages you would like to change? Or existing pages that are related to your proposal? placeholder: | - Example - Example - Example - type: checkboxes id: will-pr attributes: label: Participation description: Let us know if your interested in contributing this feature yourself. options: - label: I am willing to submit a pull request for this feature. required: false ================================================ FILE: .github/DISCUSSION_TEMPLATE/feature-requests.yml ================================================ body: - type: markdown attributes: value: | Thank you for getting in touch! Please fill out this form as completely as possible. Want to report a bug instead? [Use our bug report form](https://github.com/withastro/starlight/issues/new?assignees=&labels=&projects=&template=---01-bug-report.yml) Want to chat before posting? [Join us in the `#starlight` channel on Discord](https://astro.build/chat) - type: input id: starlight-version attributes: label: What version of `starlight` are you using? placeholder: 0.0.0 validations: required: true - type: textarea id: summary attributes: label: What is your idea? description: A brief, one or two sentence description of your idea for a new feature. validations: required: true - type: textarea id: background attributes: label: Why is this feature necessary? description: Explain why this feature is important. What problems would it solve? Which users would it help? validations: required: true - type: textarea id: prior-art attributes: label: Do you have examples of this feature in other projects? description: Help us understand your idea by sharing links to example implementations we can compare against. placeholder: | - Example - Example - Example - type: checkboxes id: will-pr attributes: label: Participation description: Let us know if your interested in contributing this feature yourself. options: - label: I am willing to submit a pull request for this feature. required: false ================================================ FILE: .github/ISSUE_TEMPLATE/---01-bug-report.yml ================================================ name: "\U0001F41B Bug Report" description: Report an issue or possible bug labels: [] assignees: [] body: - type: markdown attributes: value: | Thank you for taking the time to file a bug report! Please fill out this form as completely as possible. ✅ I am using the **latest versions of Starlight and Astro**. ✅ I am using a compatible version of Node.js (`v22.12.0+`). - type: input id: starlight-version attributes: label: What version of `starlight` are you using? placeholder: 0.0.0 validations: required: true - type: input id: astro-version attributes: label: What version of `astro` are you using? placeholder: 0.0.0 validations: required: true - type: input id: package-manager attributes: label: What package manager are you using? placeholder: npm, yarn, pnpm validations: required: true - type: input id: os attributes: label: What operating system are you using? placeholder: Mac, Windows, Linux validations: required: true - type: input id: browser attributes: label: What browser are you using? placeholder: Chrome, Firefox, Safari validations: required: true - type: textarea id: bug-description attributes: label: Describe the Bug description: A clear and concise description of what the bug is. validations: required: true - type: input id: bug-reproduction attributes: label: Link to Minimal Reproducible Example description: 'Use [astro.new](https://astro.new) to create a minimal reproduction of the problem. **A minimal reproduction is required** so that others can help debug your issue. If a report is vague (e.g. just a generic error message) and has no reproduction, it may be auto-closed. Not sure how to create a minimal example? [Read our guide](https://docs.astro.build/en/guides/troubleshooting/#creating-minimal-reproductions)' placeholder: 'https://stackblitz.com/abcd1234' validations: required: true - type: checkboxes id: will-pr attributes: label: Participation options: - label: I am willing to submit a pull request for this issue. required: false ================================================ FILE: .github/ISSUE_TEMPLATE/---02-docs-issue.yml ================================================ name: "\U0001F4DA Docs Issue" description: Report an issue with the Starlight documentation labels: [] assignees: [] body: - type: markdown attributes: value: | Thank you for taking the time to let us know something is wrong! Please fill out this form as completely as possible. - type: input id: docs-page attributes: label: What page of the docs did you find an issue on? description: If this issue applies to multiple pages, include additional pages in your bug description. placeholder: https://starlight.astro.build/... validations: required: true - type: textarea id: bug-description attributes: label: Describe the issue description: A clear and concise description of what the issue is. validations: required: true - type: input id: os attributes: label: What operating system are you using? placeholder: Mac, Windows, Linux validations: required: true - type: input id: browser attributes: label: What browser are you using? placeholder: Chrome, Firefox, Safari validations: required: true - type: checkboxes id: will-pr attributes: label: Participation options: - label: I am willing to submit a pull request for this issue. required: false ================================================ FILE: .github/ISSUE_TEMPLATE/config.yml ================================================ blank_issues_enabled: false contact_links: - name: 💡 Feature Request url: https://github.com/withastro/starlight/discussions/new?category=feature-requests about: Suggest an improvement you’d like to see added to Starlight - name: 👾 Chat url: https://astro.build/chat about: Our Discord server is active, come join us! - name: 💁 Support url: https://astro.build/chat about: 'This issue tracker is not for support questions. Join us on Discord for assistance!' ================================================ FILE: .github/PULL_REQUEST_TEMPLATE.md ================================================ #### Description - Closes # - What does this PR change? Give us a brief description. - Did you change something visual? A before/after screenshot can be helpful. ================================================ FILE: .github/labeler.yml ================================================ # See https://github.com/actions/labeler '🚨 action': - changed-files: - any-glob-to-any-file: - .github/workflows/** i18n: - changed-files: - any-glob-to-any-file: - docs/src/content/docs/de/**/* - docs/src/content/docs/es/**/* - docs/src/content/docs/fr/**/* - docs/src/content/docs/it/**/* - docs/src/content/docs/ja/**/* - docs/src/content/docs/zh-cn/**/* - docs/src/content/docs/pt-br/**/* - docs/src/content/docs/pt-pt/**/* - docs/src/content/docs/ko/**/* - docs/src/content/docs/ru/**/* - docs/src/content/docs/id/**/* - docs/src/content/docs/tr/**/* - docs/src/content/docs/hi/**/* - docs/src/content/docs/da/**/* - docs/src/content/docs/uk/**/* '🌟 core': - changed-files: - any-glob-to-any-file: - packages/starlight/** '🌟 tailwind': - changed-files: - any-glob-to-any-file: - packages/tailwind/** '🌟 docsearch': - changed-files: - any-glob-to-any-file: - packages/docsearch/** '🌟 markdoc': - changed-files: - any-glob-to-any-file: - packages/markdoc/** '📚 docs': - changed-files: - any-glob-to-any-file: - docs/** ================================================ FILE: .github/renovate.json5 ================================================ { $schema: 'https://docs.renovatebot.com/renovate-schema.json', extends: [ ':disableDependencyDashboard', ':semanticPrefixFixDepsChoreOthers', ':ignoreModulesAndTests', 'workarounds:all', 'helpers:pinGitHubActionDigestsToSemver', 'docker:disable', ], rangeStrategy: 'bump', ignorePaths: ['**/node_modules/**'], packageRules: [ { groupName: 'github-actions', matchManagers: ['github-actions'], }, { matchManagers: ['npm'], groupName: 'dependencies', matchDepTypes: ['devDependencies', 'dependencies', 'peerDependencies'], enabled: false, }, { description: 'Disable package manager version updates', matchPackageNames: ['pnpm'], matchDepTypes: ['packageManager'], enabled: false, }, { description: 'Disable Node.js version updates with actions/setup-node', matchDepNames: ['node'], matchDepTypes: ['uses-with'], enabled: false, }, ], } ================================================ FILE: .github/workflows/ci.yml ================================================ name: CI on: push: branches: [main] merge_group: pull_request: branches: [main] # Automatically cancel in-progress actions on the same branch concurrency: group: ${{ github.workflow }}-${{ github.event_name == 'pull_request_target' && github.head_ref || github.ref }} cancel-in-progress: true env: NODE_VERSION: 22 ASTRO_TELEMETRY_DISABLED: true jobs: changes: runs-on: ubuntu-latest permissions: pull-requests: read outputs: docs: ${{ steps.filter.outputs.docs }} docs_ja: ${{ steps.filter.outputs.docs_ja }} docs_en: ${{ steps.filter.outputs.docs_en }} docs_not_content: ${{ steps.filter.outputs.docs_not_content }} packages: ${{ steps.filter.outputs.packages }} ci: ${{ steps.filter.outputs.ci }} steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 id: filter # When updating filters here, make sure to also add or remove them from the # outputs block above. with: filters: | docs: - 'docs/**' docs_ja: - 'docs/src/content/docs/ja/**' docs_en: - 'docs/src/content/docs/**' # Exclude languages with a two-letter code - '!docs/src/content/docs/{a..z}{a..z}/**' # Exclude languages with a region subtag - '!docs/src/content/docs/{a..z}{a..z}-{a..z}{a..z}/**' docs_not_content: - 'docs/**' - '!docs/src/content/docs/**' packages: - 'packages/**' ci: - '.github/workflows/ci.yml' unit-test: name: Run unit tests needs: changes if: ${{ needs.changes.outputs.packages == 'true' || needs.changes.outputs.ci == 'true' }} runs-on: ubuntu-latest steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0 - uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0 with: node-version: ${{ env.NODE_VERSION }} cache: 'pnpm' - run: pnpm i - name: Test packages run: pnpm -r test:coverage e2e-test: name: 'Run E2E tests (${{ matrix.os }})' needs: changes if: ${{ needs.changes.outputs.packages == 'true' || needs.changes.outputs.ci == 'true' }} strategy: fail-fast: false matrix: os: [ubuntu-latest, windows-latest] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 # Uninstall man-db to prevent man page updates taking a long time after package installations # on Ubuntu 24.04. # https://github.com/actions/runner/issues/4030 # https://github.com/actions/runner-images/issues/10977 - name: Uninstall man-db if: matrix.os == 'ubuntu-latest' run: | sudo apt-get update sudo apt-get remove man-db - uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0 - uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0 with: node-version: ${{ env.NODE_VERSION }} cache: 'pnpm' - run: pnpm i - name: Test packages (Linux) if: matrix.os == 'ubuntu-latest' run: pnpm -r test:e2e:chrome # Firefox is used for Windows E2E tests as Chrome on Windows requires the installation of the # Server Media Foundation windows feature, which can take up to 3 minutes to install on CI. # https://github.com/microsoft/playwright/blob/e7bff526433b6dcb02801763ab5b1c6407902d47/packages/playwright-core/src/server/registry/dependencies.ts#L79-L89 - name: Test packages (Windows) if: matrix.os == 'windows-latest' run: pnpm -r test:e2e:firefox type-check: name: Run type checks runs-on: ubuntu-latest steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0 - uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0 with: node-version: ${{ env.NODE_VERSION }} cache: 'pnpm' - run: pnpm i - name: Generate docs types working-directory: docs run: pnpm astro sync - name: Type check packages run: pnpm typecheck lint: name: Lint code runs-on: ubuntu-latest steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0 - uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0 with: node-version: ${{ env.NODE_VERSION }} cache: 'pnpm' - run: pnpm i - name: Generate types working-directory: ./docs run: pnpm astro sync - name: Run linter run: pnpm lint a11y: name: Check for accessibility issues needs: changes if: ${{ needs.changes.outputs.docs_not_content == 'true' || needs.changes.outputs.docs_ja == 'true' || needs.changes.outputs.docs_en == 'true' || needs.changes.outputs.ci == 'true' || needs.changes.outputs.packages == 'true' }} runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 # Uninstall man-db to prevent man page updates taking a long time after package installations # on Ubuntu 24.04. # https://github.com/actions/runner/issues/4030 # https://github.com/actions/runner-images/issues/10977 - name: Uninstall man-db run: | sudo apt-get update sudo apt-get remove man-db - name: Setup PNPM uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0 - name: Setup Node uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0 with: node-version: ${{ env.NODE_VERSION }} cache: 'pnpm' - name: Install Dependencies run: pnpm i - name: Run accessibility audit working-directory: ./docs run: pnpm t windows-smoke: name: Docs site builds on Windows runs-on: windows-latest steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0 - uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0 with: node-version: ${{ env.NODE_VERSION }} cache: 'pnpm' - run: pnpm i - name: Build docs site working-directory: ./docs run: pnpm build links: name: Check for broken links needs: changes if: ${{ needs.changes.outputs.docs == 'true' || needs.changes.outputs.ci == 'true' }} runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Setup PNPM uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0 - name: Setup Node uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0 with: node-version: ${{ env.NODE_VERSION }} cache: 'pnpm' - name: Install Dependencies run: pnpm i - name: Build docs site and check links working-directory: ./docs run: pnpm linkcheck ================================================ FILE: .github/workflows/congratsbot.yml ================================================ name: Congratsbot on: push: branches: [main] jobs: congrats: if: ${{ github.repository_owner == 'withastro' && github.event.head_commit.message != '[ci] format' }} uses: withastro/automation/.github/workflows/congratsbot.yml@main with: EMOJIS: '🎉,🎊,🧑‍🚀,🥳,🙌,🚀,🤩,☄️,💫,<:starlight:1107431075543797802>,<:houston_pride:1130504824673284107>' COAUTHOR_TEMPLATES: > [ "Thanks for helping! ✨", " stepped up to lend a hand — thank you! 🙌", " with the assist! 💪", "Couldn’t have done this without ! 💖", "Made even better by ! 🚀", "And the team effort award goes to… ! 🏆", "Featuring contributions by ! 🌟" ] secrets: DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK_CONGRATS }} ================================================ FILE: .github/workflows/file-icons.yml ================================================ name: File icons generator on: schedule: - cron: '0 0 * * 0' workflow_dispatch: permissions: contents: write pull-requests: write jobs: icons: name: Generate file icons if: github.repository_owner == 'withastro' runs-on: ubuntu-latest steps: - name: Checkout Repo uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Setup PNPM uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0 - name: Setup Node uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0 with: node-version: 22.12.0 cache: 'pnpm' - name: Install Dependencies run: pnpm i - name: Run file icons generator run: pnpm build working-directory: packages/file-icons-generator - name: Create Pull Request uses: peter-evans/create-pull-request@c0f553fe549906ede9cf27b5156039d195d2ece0 # v8.1.0 with: branch: ci/file-icons token: ${{ secrets.FREDKBOT_GITHUB_TOKEN }} commit-message: 'ci: update file icons' title: 'ci: update file icons' body: | This PR is auto-generated by a GitHub action to update the file icons and file tree definitions available in Starlight. ================================================ FILE: .github/workflows/format.yml ================================================ name: Format on: push: branches: - main jobs: format: runs-on: ubuntu-latest steps: - name: Check out code using Git uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: ref: ${{ github.head_ref }} # Needs access to push to main token: ${{ secrets.FREDKBOT_GITHUB_TOKEN }} - uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0 - uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0 with: node-version: 22.12.0 cache: 'pnpm' - run: pnpm i - name: Format with Prettier run: pnpm format - name: Commit changes uses: stefanzweifel/git-auto-commit-action@04702edda442b2e678b25b537cec683a1493fcb9 # v7.1.0 with: commit_message: '[ci] format' branch: ${{ github.head_ref }} commit_user_name: fredkbot commit_user_email: fred+astrobot@astro.build ================================================ FILE: .github/workflows/lunaria.yml ================================================ name: Lunaria on: # Trigger the workflow every time a pull request is opened or synchronized at the target `main` branch pull_request_target: types: [opened, synchronize] branches: [main] paths: - 'docs/**' # Allow this job to clone the repository and comment on the pull request permissions: contents: read pull-requests: write jobs: lunaria-overview: name: Generate Lunaria Overview runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: # Necessary for Lunaria to work properly # Makes the action clone the entire git history fetch-depth: 0 - name: Setup PNPM uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0 - name: Setup Node uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0 with: node-version: 22.12.0 cache: pnpm - name: Install dependencies run: pnpm install shell: bash - name: Generate Lunaria Overview uses: yanthomasdev/lunaria-action@06ad5ab2704d030708baf3b279ca0446b418e853 # v0.1.0 with: token: ${{ secrets.FREDKBOT_GITHUB_TOKEN }} working-directory: docs ================================================ FILE: .github/workflows/pr-labeler.yml ================================================ name: 'Pull Request Labeler' on: - pull_request_target jobs: triage: permissions: contents: read pull-requests: write runs-on: ubuntu-latest steps: - uses: actions/labeler@634933edcd8ababfe52f92936142cc22ac488b1b # v6.0.1 with: repo-token: '${{ secrets.GITHUB_TOKEN }}' ================================================ FILE: .github/workflows/preview-release.yml ================================================ name: Preview Release permissions: {} on: pull_request: branches: [main] types: [labeled] # Automatically cancel in-progress actions on the same branch concurrency: group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.head_ref || github.ref }} cancel-in-progress: true jobs: preview: name: Preview Release if: ${{ github.repository_owner == 'withastro' && github.event.label.name == 'pr-preview' }} runs-on: ubuntu-latest permissions: contents: read pull-requests: write steps: - name: Checkout Repo uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: # While releasing with changesets works with a shallow clone, this is not the case of # running `changeset status` which does not extend a shallow clone. fetch-depth: 0 persist-credentials: false - name: Setup PNPM uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0 - name: Setup Node uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0 with: node-version: 24.10.0 cache: 'pnpm' - name: Install Dependencies run: pnpm i - name: Get changeset status id: changeset run: | pnpm changeset status --output changeset-status.json echo "status=$(cat changeset-status.json | jq -c .)" >> $GITHUB_OUTPUT - name: Get pnpm packages id: pnpm run: echo "packages=$(pnpm list --recursive --depth -1 --json | jq -c .)" >> $GITHUB_OUTPUT - name: Get preview packages id: preview uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 env: CHANGESET: ${{ steps.changeset.outputs.status }} PACKAGES: ${{ steps.pnpm.outputs.packages }} with: script: | const { relative } = require('node:path'); const changeset = JSON.parse(process.env.CHANGESET); const packages = JSON.parse(process.env.PACKAGES); // A map of all packages name in the monorepo to their relative paths. const packagePathsMap = Object.fromEntries(packages.map(pkg => [pkg.name, relative(process.cwd(), pkg.path)])); // A list of all relative package paths to publish in this preview release. const previewPackagePaths = [...new Set(changeset.changesets.map(change => change.releases.map(release => packagePathsMap[release.name])).flat())] // A space-separated string of all relative package paths to publish in this preview release (or an empty string if none). core.setOutput('packages', previewPackagePaths.join(' ')); # We remove the preview label before publishing so that the label is always removed even if # publishing fails, so we can retry by only adding the label again. - name: Remove Preview Label uses: actions-ecosystem/action-remove-labels@2ce5d41b4b6aa8503e285553f75ed56e0a40bae0 # v1.3.0 with: labels: pr-preview - name: Publish preview packages env: PACKAGES: ${{ steps.preview.outputs.packages }} run: | if [ -z "$PACKAGES" ]; then echo "::error::No packages to publish in this preview release." echo "::error::Make sure the pull request includes a changeset." exit 1 fi # Note that `--compact` is used for shorter URLs but requires packages to be published on # npm. This means that it's not possible to publish a preview for a new package that has # not yet been published on npm. pnpm dlx pkg-pr-new publish --pnpm --compact --packageManager=pnpm --no-template $PACKAGES ================================================ FILE: .github/workflows/release.yml ================================================ name: Release permissions: {} on: push: branches: - main jobs: release: name: Release if: ${{ github.repository_owner == 'withastro' }} runs-on: ubuntu-latest permissions: contents: write pull-requests: write id-token: write steps: - name: Checkout Repo uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: # This makes Actions fetch all Git history so that Changesets can generate changelogs with the correct commits fetch-depth: 0 persist-credentials: false - name: Setup PNPM uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0 - name: Setup Node uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0 with: node-version: 24.10.0 cache: 'pnpm' - name: Install Dependencies run: pnpm i - name: Create Release Pull Request uses: changesets/action@6a0a831ff30acef54f2c6aa1cbbc1096b066edaf # v1.7.0 with: version: pnpm run version publish: pnpm changeset publish commit: '[ci] release' title: '[ci] release' env: GITHUB_TOKEN: ${{ secrets.FREDKBOT_GITHUB_TOKEN }} NPM_TOKEN: "" # See https://github.com/changesets/changesets/issues/1152#issuecomment-3190884868 ================================================ FILE: .github/workflows/size-limit.yml ================================================ name: Size Limit on: pull_request: branches: [main] # Automatically cancel in-progress actions on the same branch concurrency: group: ${{ github.workflow }}-${{ github.event_name == 'pull_request_target' && github.head_ref || github.ref }} cancel-in-progress: true env: NODE_VERSION: 22 jobs: # This basic check runs size-limit for the current branch. # It will fail if the branch pushes the size over the specified budget. size-limit-basic: if: ${{ github.event.pull_request.head.repo.full_name != 'withastro/starlight' }} name: Check build output is within performance budget (forks) runs-on: ubuntu-latest steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0 - name: Setup Node uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0 with: node-version: ${{ env.NODE_VERSION }} cache: 'pnpm' - run: pnpm i - run: 'pnpm build:examples' - run: pnpm size # This check cannot run in forks, so is only run for PRs from this repo. # It will run size-limit for both `main` and the PR branch and comment in the PR with changes. size-limit: if: ${{ github.event.pull_request.head.repo.full_name == 'withastro/starlight' }} name: Check build output is within performance budget runs-on: ubuntu-latest steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0 - name: Setup Node uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0 with: node-version: ${{ env.NODE_VERSION }} cache: 'pnpm' - name: Run size-limit uses: andresz1/size-limit-action@94bc357df29c36c8f8d50ea497c3e225c3c95d1d # v1.8.0 with: github_token: ${{ secrets.FREDKBOT_GITHUB_TOKEN }} build_script: 'build:examples' package_manager: pnpm ================================================ FILE: .github/workflows/welcome-bot.yml ================================================ name: WelcomeBot on: pull_request_target: branches: [main] types: [opened] permissions: pull-requests: write jobs: welcome: name: Welcome First-Time Contributors runs-on: ubuntu-latest steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - uses: zephyrproject-rtos/action-first-interaction@58853996b1ac504b8e0f6964301f369d2bb22e5c with: repo-token: ${{ secrets.FREDKBOT_GITHUB_TOKEN }} pr-opened-message: | Hello! Thank you for opening your **first PR** to Starlight! ✨ Here’s what will happen next: 1. Our GitHub bots will run to check your changes. If they spot any issues you will see some error messages on this PR. Don’t hesitate to ask any questions if you’re not sure what these mean! 2. In a few minutes, you’ll be able to see a preview of your changes on Netlify 🤩 3. One or more of our maintainers will take a look and may ask you to make changes. We try to be responsive, but don’t worry if this takes a few days. ================================================ FILE: .gitignore ================================================ # dependencies node_modules/ # logs npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* # environment variables .env .env.production # macOS-specific files .DS_Store # Vitest __coverage__/ # Playwright test-results/ # Vercel output .vercel ================================================ FILE: .npmrc ================================================ prefer-workspace-packages=true link-workspace-packages=true shell-emulator=true auto-install-peers=false ================================================ FILE: .prettierignore ================================================ # Deep Directories **/node_modules # Generated Directories **/dist **/build **/.astro **/__coverage__ # Directories .changeset # Files pnpm-lock.yaml # Test snapshots **/__tests__/**/snapshots # https://github.com/withastro/prettier-plugin-astro/issues/337 packages/starlight/user-components/Tabs.astro # Prettier forces whitespace between elements we want to avoid for consistency with the rehype version packages/starlight/components/AnchorHeading.astro packages/starlight/__e2e__/fixtures/basics/src/content/docs/anchor-heading-component.mdx # Malformed YAML file used for testing packages/starlight/__tests__/i18n/malformed-yaml-src/content/i18n/*.yml # GitHub Actions workflow files .github/workflows/*.yml ================================================ FILE: .prettierrc ================================================ { "printWidth": 100, "semi": true, "singleQuote": true, "tabWidth": 2, "trailingComma": "es5", "useTabs": true, "plugins": ["prettier-plugin-astro"], "overrides": [ { "files": [".*", "*.json", "*.md", "*.toml", "*.yml"], "options": { "useTabs": false } }, { "files": ["*.md", "*.mdx"], "options": { "printWidth": 80 } } ] } ================================================ FILE: .vscode/extensions.json ================================================ { "recommendations": [ "astro-build.astro-vscode", "dbaeumer.vscode-eslint", "hideoo.starlight-links" ], "unwantedRecommendations": [] } ================================================ FILE: .vscode/launch.json ================================================ { "version": "0.2.0", "configurations": [ { "command": "./node_modules/.bin/astro dev", "cwd": "${workspaceFolder}/docs", "name": "Development server", "request": "launch", "type": "node-terminal" } ] } ================================================ FILE: CONTRIBUTING.md ================================================ # Contributor Manual We welcome contributions of any size and contributors of any skill level. As an open source project, we believe in giving back to our contributors. We are happy to help with guidance on PRs, technical writing, and turning any feature idea into a reality. > **Tip for new contributors:** > Take a look at [GitHub's Docs](https://docs.github.com/en/get-started/quickstart/hello-world) for helpful information on working with GitHub. This document is an active work in progress — like Starlight itself! Feel free to join us in [the Astro Discord server][discord] to join the discussion. Look for the `#starlight` channel and say “Hi!” when you arrive. ## Types of contributions There are lots of ways to contribute to Starlight. Maintaining Starlight requires writing Astro code, as well as addressing accessibility, styling, and UX concerns. This repository also contains the code for the Starlight docs website. Help writing docs, catching typos and errors, as well as translating docs into other languages is always welcome. You can also get involved by leaving feedback on [issues][issues] or reviewing [pull requests][pulls] by other contributors. We encourage you to: - [**Open an issue**][new-issue] to let us know of bugs in Starlight, documentation you found unclear, or other issues you run into. - [**Look at existing issues**][issues] (especially those labelled [“good first issue”][gfi]) to find ways to contribute. - **Make a pull request (PR)** to address an open issue or to fix obvious problems. Read more about [making a PR in GitHub’s docs][pr-docs] - [**Review existing PRs**][pulls] to help us merge contributions sooner. - [**Add or update translations**](#translations). We need help translating both Starlight’s UI and documentation. ## About this repo This repo is a “monorepo,” meaning it contains several projects in one. It contains the Starlight docs site in [`docs/`](./docs/) and the packages that make up Starlight in [`packages/`](./packages/). ### Setting up a development environment You can [develop locally](#developing-locally) or use an online coding development environment like [GitHub Codespaces](#developing-using-github-codespaces) to get started quickly. #### Developing locally **Prerequisites:** Developing Starlight requires [Node.js](https://nodejs.org/en) (v16 or higher) and [pnpm](https://pnpm.io/) (v8.2 or higher). Make sure you have these installed before following these steps. 1. **Fork Starlight** to your personal GitHub account by clicking Fork on the [main Starlight repo page][sl]. 2. **Clone your fork** of Starlight to your computer. Replace `YOUR-USERNAME` in the command below with your GitHub username to clone in a Terminal: ```sh git clone https://github.com/YOUR-USERNAME/starlight.git ``` 3. **Change directory** to the cloned repo: ```sh cd starlight ``` 4. **Install dependencies** with `pnpm`: ```sh pnpm i ``` 5. **Generate TypeScript types** for all Astro modules: ```sh cd docs pnpm astro sync ``` #### Developing using GitHub Codespaces 1. **Create a new codespace** via https://codespaces.new/withastro/starlight 2. **Generate TypeScript types** for all Astro modules: ```sh pnpm astro sync ``` 3. If running the docs site, pass the `--host` flag to avoid “502 Bad Gateway” errors: ```sh cd docs pnpm dev --host ``` The dev container used for GitHub Codespaces can also be used with [other supporting tools](https://containers.dev/supporting), including VS Code. ### Making a Pull Request When making a pull request containing changes impacting users to Starlight or any related packages (`packages/*`), be sure to [add a changeset](https://github.com/changesets/changesets/blob/main/docs/adding-a-changeset.md#i-am-in-a-multi-package-repository-a-mono-repo) that will describe the changes to users. Documentation-only (`docs/*`) and non-package (`examples/*`) changes do not need changesets. ```sh pnpm exec changeset ``` ## Testing ### Testing visual changes while you work Run the Astro dev server on the docs site to see how changes you make impact a project using Starlight. To do this, move into the `docs/` directory from the root of the repo and then run `pnpm dev`: ```sh cd docs pnpm dev ``` You should then be able to open and see your changes. > **Note** > Changes to the Starlight integration will require you to quit and restart the dev server to take effect. ### Check for broken links in the docs site When adding or translating content in the Starlight docs site, you can check all internal links are valid. All GitHub PRs are checked this way automatically, but testing locally can help if you want to confirm changes are correct before committing them. To do this, move into the `docs/` directory from the root of the repo and then run `pnpm linkcheck`: ```sh cd docs pnpm linkcheck ``` If there are any broken links, the build will fail and log which pages need to be fixed. ### Unit tests The Starlight package includes unit tests in [`packages/starlight/__tests__/`](./packages/starlight/__tests__/), which are run using [Vitest][vitest]. To run tests, move into the Starlight package and then run `pnpm test`: ```sh cd packages/starlight pnpm test ``` This will run tests and then listen for changes, re-running tests when files change. #### Test environments A lot of Starlight code relies on Vite virtual modules provided either by Astro or by Starlight itself. Each subdirectory of `packages/starlight/__tests__/` should contain a `vitest.config.ts` file that uses the `defineVitestConfig()` helper to define a valid test environment for tests in that directory. This helper takes a single argument, which provides a Starlight user config object: ```ts // packages/starlight/__tests__/basics/vitest.config.ts import { defineVitestConfig } from '../test-config'; export default defineVitestConfig({ title: 'Basics', }); ``` This allows you to run tests of Starlight code against different combinations of Starlight configuration options. #### Mocking content collections Starlight relies on a user’s `docs` and (optional) `i18n` content collections, which aren’t available during testing. You can use a top-level `vi.mock()` call and the `mockedAstroContent` helper to set up fake collection entries for the current test file: ```js import { describe, expect, test, vi } from 'vitest'; vi.mock('astro:content', async () => (await import('../test-utils')).mockedAstroContent({ docs: [ ['index.mdx', { title: 'Home Page' }], ['environmental-impact.md', { title: 'Eco-friendly docs' }], ], i18n: [['en', { 'page.editLink': 'Modify this doc!' }]], }) ); ``` #### Test coverage To see how much of Starlight’s code is currently being tested, run `pnpm test:coverage` from the Starlight package: ```sh cd packages/starlight pnpm test:coverage ``` This will print a table to your terminal and also generate an HTML report you can load in a web browser by opening [`packages/starlight/__coverage__/index.html`](./packages/starlight/__coverage__/index.html). ### End-to-end (E2E) tests Starlight also includes E2E tests in [`packages/starlight/__e2e__/`](./packages/starlight/__e2e__/), which are run using [Playwright][playwright]. To run these tests, move into the Starlight package and then run `pnpm test:e2e`: ```sh cd packages/starlight pnpm test:e2e ``` #### Test fixtures Each subdirectory of `packages/starlight/__e2e__/fixtures` should contain the basic files needed to run Starlight (`package.json`, `astro.config.mjs`, a content collection configuration in `src/content.config.ts` and some content to render in `src/content/docs/`). The `testFactory()` helper can be used in a test file to define the fixture which will be built and loaded in a preview server during a set of tests. ```ts // packages/starlight/__e2e__/feature.test.ts import { testFactory } from './test-utils'; const test = await testFactory('./fixtures/basics/'); ``` This allows you to run tests against different combinations of Astro and Starlight configuration options for various content. #### When to add E2E tests? E2E are most useful for testing what happens on a page after it has been loaded by a browser. They run slower than unit tests so they should be used sparingly when unit tests aren’t sufficient. ## Translations Translations help make Starlight accessible to more people. Check out the dedicated [i18n contribution guidelines](https://contribute.docs.astro.build/guides/i18n/#quality-standards--adaptation) in the Astro docs contributor guide for more details regarding our translation process and quality standards. ### Translating Starlight’s UI Starlight’s UI comes with some built-in text elements. For example, the table of contents on a Starlight page has a heading of “On this page” and the theme picker shows “Light”, “Dark”, and “Auto” labels. Starlight aims to provide these in as many languages as possible. Help out by adding or updating translation files in [`packages/starlight/translations`](./packages/starlight/translations/). Each language’s JSON file follows the [translation structure described in Starlight’s docs](https://starlight.astro.build/guides/i18n/#translate-starlights-ui). 📺 **Prefer a visual walkthrough?** [Watch an introduction to Starlight’s translation files.](https://scrimba.com/scrim/cpb44bt3) ### Translating Starlight’s docs Starlight’s documentation is also translated into multiple languages. You can find the source code for the site in [the `docs/` directory](./docs/) of this repository. Help out by: - Reviewing [open translation PRs][pulls] - Updating out-of-date translated pages - Adding an untranslated page Visit **** to track translation progress for the currently supported languages. #### Adding a new language to Starlight’s docs To add a language, you will need its BCP-47 tag and a label. See [“Adding a new language”](https://contribute.docs.astro.build/guides/i18n/#adding-a-new-language) in the Astro docs contributor guide for some helpful tips around choosing these. - Add your language to the `locales` config in `docs/astro.config.mjs` - Add your language to the `locales` config in `docs/lunaria.config.json` - Add your language’s subtag to the i18n label config in `.github/labeler.yml` - Add your language to the `config.sitemap.exclude` option in `docs/__a11y__/test-utils.ts` - Create the first translated page for your language. This must be the Starlight landing page: `docs/src/content/docs/{language}/index.mdx`. - Open a pull request on GitHub to add your changes to Starlight! ## Understanding Starlight - Starlight is built as an Astro integration. Read the [Astro Integration API docs][api-docs] to learn more about how integrations work. The Starlight integration is exported from [`packages/starlight/index.ts`](./packages/starlight/index.ts). It sets up Starlight’s routing logic, parses user config, and adds configuration to a Starlight user’s Astro project. - Most pages in a Starlight project are built using a single [`packages/starlight/index.astro`](./packages/starlight/index.astro) route. If you’ve worked on an Astro site before, much of this should look familiar: it’s an Astro component and uses a number of other components to build a page based on user content. - Starlight consumes a user’s content from the `'docs'` [content collection](https://docs.astro.build/en/guides/content-collections/). This allows us to specify the permissible frontmatter via [a Starlight-specific schema](./packages/starlight/schema.ts) and get predictable data while providing clear error messages if a user sets invalid frontmatter in a page. - Components that require JavaScript for their functionality are all written without a UI framework, most often as custom elements. This helps keep Starlight lightweight and makes it easier for a user to choose to add components from a framework of their choice to their project. - Components that require client-side JavaScript or CSS should use JavaScript/CSS features that are well-supported by browsers. You can find a list of supported browsers and their versions using this [browserslist query](https://browsersl.ist/#q=%3E+0.5%25%2C+not+dead%2C+Chrome+%3E%3D+105%2C+Edge+%3E%3D+105%2C+Firefox+%3E%3D+121%2C+Safari+%3E%3D+15.4%2C+iOS+%3E%3D+15.4%2C+not+op_mini+all). To check whether or not a feature is supported, you can visit the [Can I use](https://caniuse.com) website and search for the feature. [discord]: https://astro.build/chat [issues]: https://github.com/withastro/starlight/issues [sl]: https://github.com/withastro/starlight/pulls [pulls]: https://github.com/withastro/starlight/pulls [new-issue]: https://github.com/withastro/starlight/issues/new/choose [pr-docs]: https://docs.github.com/en/get-started/quickstart/contributing-to-projects#making-a-pull-request [gfi]: https://github.com/withastro/starlight/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22+ [api-docs]: https://docs.astro.build/en/reference/integrations-reference/ [vitest]: https://vitest.dev/ [playwright]: https://playwright.dev/ ## Showcase ### Sites We love to see websites built with Starlight and share them with the community on our [showcase](https://starlight.astro.build/resources/showcase/) page. If you’ve built a documentation site with Starlight, adding it to the showcase is just a pull request away! 1. Set up a development environment by following the [“Setting up a development environment”](#setting-up-a-development-environment) instructions. 2. Add a screenshot of your site to the `docs/src/assets/showcase/` directory. The image file must: - Be a `.png` file and named after your site’s domain, e.g. `example.com.png`. - Have the dimensions of 800 × 450 pixels. 3. Add a new entry for your website in `docs/src/components/showcase-sites.astro`. - The new entry must be appended at the end of the existing list of sites. - The `title` attribute must be the name of your site with no extra details. - The `href` attribute must be the URL of your Starlight site. If your documentation is hosted on a subdomain or subdirectory, include that in the URL. - The `thumbnail` attribute must be the filename of the screenshot you added in step 2. ```diff + ``` 4. Open a pull request on GitHub to add your changes. ### Themes Share themes for Starlight you built by adding them to our [themes](https://starlight.astro.build/resources/themes/) page. Here’s how! 1. Set up a development environment by following the [“Setting up a development environment”](#setting-up-a-development-environment) instructions. 2. Take screenshots of your theme’s light and dark modes using our demo project. 1. Open the [theme demo project](https://stackblitz.com/edit/github-jj1kzx5x?file=astro.config.mjs) on StackBlitz. 2. Install your theme using StackBlitz’s integrated terminal: ```sh npm i your-theme-name ``` 3. Update `astro.config.mjs` to import your theme and add it to Starlight’s `plugins` array. 4. Run the dev server: ```sh npm run dev ``` 5. Open the theme preview in a new tab and use dev tools’ responsive view to take screenshots with the screen sized to 1280×720 pixels. 3. Add your screenshots of the theme’s light and dark modes to the `docs/src/assets/themes/` directory. The images must: - be PNG files with your theme’s name and the color variant, e.g. a theme named “Moon” would have files named `moon-light.png` and `moon-dark.png` - have dimensions of 1280×720 pixels 4. Add a new entry for your website in `docs/src/content/docs/resources/themes.mdx`. You can look at existing entries to see how to format this. - The new entry must be appended at the end of the existing list of sites. - The `title` attribute must be the name of your theme. - The `description` attribute should briefly describe your theme’s aesthetic, inspiration, or key features. - The `href` attribute must be the URL of your theme’s website demonstrating what the theme looks like. - The `previews` attribute must be an object listing the filenames of the screenshots you added in step 3. ## Preview releases Maintainers can create preview releases for any pull requests containing pending changesets by adding the `pr-preview` label to such PRs. When doing so, a GitHub Actions workflow will be triggered to create a preview release for all necessary packages and a comment will be added to the PR with instructions on how to install the preview packages. To update a preview release after making additional changes to the PR, add the `pr-preview` label again to re-trigger the workflow. ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2023 [Astro contributors](https://github.com/withastro/starlight/graphs/contributors) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: docs/.gitignore ================================================ # build output dist/ # generated types .astro/ # dependencies node_modules/ # logs npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* # environment variables .env .env.production # macOS-specific files .DS_Store ================================================ FILE: docs/README.md ================================================ # Starlight Docs [![Built with Starlight](https://astro.badg.es/v2/built-with-starlight/tiny.svg)](https://starlight.astro.build) This directory contains the Starlight documentation website (built with Starlight!) [![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/github/withastro/starlight/tree/main/docs) [![Open with CodeSandbox](https://assets.codesandbox.io/github/button-edit-lime.svg)](https://codesandbox.io/p/sandbox/github/withastro/starlight/tree/main/docs) ## 🧞 Commands All commands are run from the root of the project, from a terminal: | Command | Action | | :---------------------- | :----------------------------------------------- | | `pnpm install` | Installs dependencies | | `pnpm run dev` | Starts local dev server at `localhost:4321` | | `pnpm run build` | Build your production site to `./dist/` | | `pnpm run preview` | Preview your build locally, before deploying | | `pnpm run astro ...` | Run CLI commands like `astro add`, `astro check` | | `pnpm run astro --help` | Get help using the Astro CLI | ## 👀 Want to learn more? Feel free to check [the Astro documentation](https://docs.astro.build) or jump into the [Astro Discord server](https://astro.build/chat). ================================================ FILE: docs/__a11y__/docs.test.ts ================================================ import { expect, test } from './test-utils'; test('does not report accessibility violations on the docs site', async ({ docsSite }) => { let violationsCount = 0; const urls = await docsSite.getAllUrls(); for (const url of urls) { const violations = await docsSite.testPage(url); if (violations.length > 0) { violationsCount += violations.length; } await docsSite.reportPageViolations(violations); } expect( violationsCount, `Found ${violationsCount} accessibility violations. Check the errors above for more details.` ).toBe(0); }); ================================================ FILE: docs/__a11y__/test-utils.ts ================================================ import { test as baseTest, type Page } from '@playwright/test'; import { DefaultTerminalReporter, getViolations, injectAxe, reportViolations, } from 'axe-playwright'; import Sitemapper from 'sitemapper'; // We use the Lunaria config to get the list of languages rather than the Astro config as importing // the latter does not play well with Playwright. import lunariaConfig from '../lunaria.config.json' with { type: 'json' }; export { expect, type Locator } from '@playwright/test'; const config: Config = { axe: { // https://www.deque.com/axe/core-documentation/api-documentation/#axecore-tags runOnly: { type: 'tag', values: ['wcag2a', 'wcag21a', 'wcag2aa', 'wcag21aa', 'wcag22aa', 'best-practice'], }, }, // i18n specific configuration. i18n: { // A list of slugs to exclude from the sitemap for the default locale. // By default, all slugs for the default locale are included. exclude: [ 'components/using-components', 'getting-started', 'guides/customization', 'guides/i18n', 'guides/overriding-components', 'guides/pages', 'guides/project-structure', 'guides/route-data', 'guides/site-search', 'manual-setup', 'reference/frontmatter', 'reference/overrides', 'reference/plugins', 'reference/route-data', ], // Locale-specific included slugs (non-default locale slugs are excluded by default). locales: { // N.B. If adding more locales here, also update the changed files filters in // `.github/workflows/ci.yml` to ensure tests run when files for those locales change. ja: ['guides/route-data', 'reference/frontmatter'], }, }, // A list of violation to ignore. ignore: [{ id: 'landmark-unique', nodeMatcher: landmarkUniqueNodeMatcher }], sitemap: { url: 'http://localhost:4321/sitemap-index.xml', replace: { query: 'https://starlight.astro.build', value: 'http://localhost:4321', }, }, }; process.env.ASTRO_TELEMETRY_DISABLED = 'true'; process.env.ASTRO_DISABLE_UPDATE_CHECK = 'true'; const locales = lunariaConfig.locales.map((locale) => locale.lang); export const test = baseTest.extend<{ docsSite: DocsSite; }>({ docsSite: async ({ page }, use) => use(new DocsSite(page)), }); // A Playwright test fixture accessible from within all tests. class DocsSite { private readonly page: Page; constructor(page: Page) { this.page = page; } async getAllUrls() { const sitemap = new Sitemapper({ url: config.sitemap.url }); const { sites } = await sitemap.fetch(); if (sites.length === 0) { throw new Error('No URLs found in sitemap.'); } const urls: string[] = []; for (const site of sites) { const slug = site.replace(config.sitemap.replace.query, ''); const url = config.sitemap.replace.value + slug; // Default locale if (!locales.some((locale) => slug.startsWith(`/${locale}/`))) { // Skip default locale excluded slugs if (config.i18n.exclude.some((excludedSlug) => slug.endsWith(`/${excludedSlug}/`))) continue; } else { // Get locale-specific config const locale = slug.split('/')[1]!; const localeConfig = config.i18n.locales[locale]; // Skip non-configured locales if (!localeConfig) continue; // Skip locale-specific non-included slugs if (!localeConfig.some((includedSlug) => slug.endsWith(`/${includedSlug}/`))) continue; } urls.push(url); } return urls; } async testPage(url: string) { await this.page.goto(url); await injectAxe(this.page); await this.page.waitForLoadState('networkidle'); const violations = await getViolations(this.page, undefined, config.axe); return this.#filterViolations(violations); } async reportPageViolations(violations: Awaited>) { const url = this.page.url().replace(config.sitemap.replace.value, ''); if (violations.length > 0) { console.error(`> Found ${violations.length} violations on ${url}\n`); await reportViolations(violations, new DefaultTerminalReporter(true, true, false)); console.error('\n'); } else { console.log(`> Found no violations on ${url}`); } } #filterViolations(violations: Awaited>) { return violations.filter((violation) => { return !config.ignore.some((ignore) => { if (typeof ignore === 'string') return violation.id === ignore; if (violation.id !== ignore.id) return false; if (!ignore.nodeMatcher) return true; return !violation.nodes.some(ignore.nodeMatcher); }); }); } } function landmarkUniqueNodeMatcher(node: ViolationNode) { // Ignore some `landmark-unique` violations. return ( /** * Asides: the best action to fix this violation would be to remove the landmark altogether as * it's not necessary in this case and switch to the `note` role. Although, this is not possible * at the moment due to an issue with NVDA not announcing it and also skipping the associated * label for a role not supported. * * @see https://github.com/nvaccess/nvda/issues/10439 * @see https://github.com/withastro/starlight/pull/2503 */ !/^]* class="starlight-aside[^>]*>$/.test(node.html) && /** * Expressive Code `
` blocks: EC 0.41.3 introduced a change adding the `region` role to
		 * scrollable code blocks. The best action to fix this violation would potentially to switch to
		 * another role, e.g. `group`, and adding `aria-label` or `aria-labelledby` to provide a generic
		 * label, e.g. `'Horizontally scrollable code'`.
		 *
		 * @see https://github.com/expressive-code/expressive-code/pull/343
		 * @see https://github.com/expressive-code/expressive-code/pull/348
		 */
		!/^]* data-language[^>]* role="region"[^>]*>$/.test(node.html)
	);
}

interface Config {
	axe: Parameters[2];
	i18n: { exclude: string[]; locales: Record };
	ignore: Array<
		| string
		| {
				id: string;
				// A function called for each node to evaluate if it should be ignored or not.
				// Return `true` if the node should be considered for the violation, `false` otherwise.
				nodeMatcher?: (node: ViolationNode) => boolean;
		  }
	>;
	sitemap: {
		url: string;
		replace: {
			query: string;
			value: string;
		};
	};
}

type Violations = Awaited>;
type ViolationNode = Violations[number]['nodes'][number];


================================================
FILE: docs/astro.config.mjs
================================================
// @ts-check
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';
import starlightLinksValidator from 'starlight-links-validator';
import markdocGrammar from './grammars/markdoc.tmLanguage.json';

export const locales = {
	root: { label: 'English', lang: 'en' },
	de: { label: 'Deutsch', lang: 'de' },
	es: { label: 'Español', lang: 'es' },
	ja: { label: '日本語', lang: 'ja' },
	fr: { label: 'Français', lang: 'fr' },
	it: { label: 'Italiano', lang: 'it' },
	id: { label: 'Bahasa Indonesia', lang: 'id' },
	'zh-cn': { label: '简体中文', lang: 'zh-CN' },
	'pt-br': { label: 'Português do Brasil', lang: 'pt-BR' },
	'pt-pt': { label: 'Português', lang: 'pt-PT' },
	ko: { label: '한국어', lang: 'ko' },
	tr: { label: 'Türkçe', lang: 'tr' },
	ru: { label: 'Русский', lang: 'ru' },
	hi: { label: 'हिंदी', lang: 'hi' },
	da: { label: 'Dansk', lang: 'da' },
	uk: { label: 'Українська', lang: 'uk' },
};

/* https://docs.netlify.com/configure-builds/environment-variables/#read-only-variables */
const NETLIFY_PREVIEW_SITE = process.env.CONTEXT !== 'production' && process.env.DEPLOY_PRIME_URL;

const site = NETLIFY_PREVIEW_SITE || 'https://starlight.astro.build/';
const ogUrl = new URL('og.jpg?v=1', site).href;
const ogImageAlt = 'Make your docs shine with Starlight';

export default defineConfig({
	site,
	trailingSlash: 'always',
	integrations: [
		starlight({
			title: 'Starlight',
			logo: {
				light: '/src/assets/logo-light.svg',
				dark: '/src/assets/logo-dark.svg',
				replacesTitle: true,
			},
			lastUpdated: true,
			editLink: {
				baseUrl: 'https://github.com/withastro/starlight/edit/main/docs/',
			},
			social: [
				{ icon: 'github', label: 'GitHub', href: 'https://github.com/withastro/starlight' },
				{ icon: 'discord', label: 'Discord', href: 'https://astro.build/chat' },
			],
			head: [
				{
					tag: 'script',
					attrs: {
						src: 'https://cdn.usefathom.com/script.js',
						'data-site': 'EZBHTSIG',
						defer: true,
					},
				},
				{
					tag: 'meta',
					attrs: { property: 'og:image', content: ogUrl },
				},
				{
					tag: 'meta',
					attrs: { property: 'og:image:alt', content: ogImageAlt },
				},
			],
			customCss: ['./src/assets/landing.css'],
			locales,
			sidebar: [
				{
					label: 'Start Here',
					translations: {
						de: 'Beginne hier',
						es: 'Comienza aqui',
						ja: 'ここからはじめる',
						fr: 'Commencez ici',
						it: 'Inizia qui',
						id: 'Mulai dari sini',
						'zh-CN': '从这里开始',
						'pt-BR': 'Comece Aqui',
						'pt-PT': 'Comece Aqui',
						ko: '시작 안내',
						tr: 'Buradan Başlayın',
						ru: 'Первые шаги',
						hi: 'यहाँ से शुरू करे',
						uk: 'Почніть звідси',
					},
					items: [
						'getting-started',
						'manual-setup',
						{
							label: 'Environmental Impact',
							slug: 'environmental-impact',
							translations: {
								de: 'Umweltbelastung',
								es: 'Documentación ecológica',
								ja: '環境への負荷',
								fr: 'Impact environnemental',
								it: 'Impatto ambientale',
								id: 'Dampak terhadap lingkungan',
								'zh-CN': '环境影响',
								'pt-BR': 'Impacto Ambiental',
								'pt-PT': 'Impacto Ambiental',
								ko: '환경적 영향',
								tr: 'Çevre Etkisi',
								ru: 'Влияние на окружающую среду',
								hi: 'पर्यावरणीय प्रभाव',
								uk: 'Вплив на довкілля',
							},
						},
					],
				},
				{
					label: 'Guides',
					translations: {
						de: 'Anleitungen',
						es: 'Guías',
						ja: 'ガイド',
						fr: 'Guides',
						it: 'Guide',
						id: 'Panduan',
						'zh-CN': '指南',
						'pt-BR': 'Guias',
						'pt-PT': 'Guias',
						ko: '가이드',
						tr: 'Rehber',
						ru: 'Руководства',
						hi: 'गाइड',
						uk: 'Ґайди',
					},
					autogenerate: { directory: 'guides' },
				},
				{
					label: 'Components',
					translations: {
						de: 'Komponenten',
						fr: 'Composants',
						ru: 'Компоненты',
						ko: '컴포넌트',
						ja: 'コンポーネント',
						'zh-CN': '组件',
						uk: 'Компоненти',
					},
					autogenerate: { directory: 'components' },
				},
				{
					label: 'Reference',
					translations: {
						de: 'Referenzen',
						es: 'Referencias',
						ja: 'リファレンス',
						fr: 'Référence',
						it: 'Riferimenti',
						id: 'Referensi',
						'zh-CN': '参考',
						'pt-BR': 'Referência',
						ko: '참조',
						tr: 'Referanslar',
						ru: 'Справочник',
						hi: 'संदर्भ',
						uk: 'Довідник',
					},
					autogenerate: { directory: 'reference' },
				},
				{
					label: 'Resources',
					translations: {
						de: 'Ressourcen',
						'zh-CN': '资源',
						fr: 'Ressources',
						'pt-BR': 'Recursos',
						'pt-PT': 'Recursos',
						ja: 'リソース',
						ru: 'Ресурсы',
						ko: '리소스',
						uk: 'Ресурси',
					},
					autogenerate: { directory: 'resources' },
				},
			],
			expressiveCode: { shiki: { langs: [markdocGrammar] } },
			plugins: process.env.CHECK_LINKS
				? [
						starlightLinksValidator({
							errorOnFallbackPages: false,
							errorOnInconsistentLocale: true,
						}),
					]
				: [],
		}),
	],
});


================================================
FILE: docs/grammars/README.md
================================================
# Starlight Docs Grammars

This directory contains additional grammars for the Starlight documentation website.

## Grammars

The following additional grammars are generated and available for use:

- [Markdoc](https://github.com/markdoc/language-server)

## Usage

To generate the grammars from their source files, run:

```sh
pnpm grammars
```

To include the grammars in the Starlight documentation website, update the `expressiveCode.shiki.langs` array in the `astro.config.mjs` file:

```diff
starlight({
  expressiveCode: {
    shiki: {
      langs: [
        JSON.parse(
          fs.readFileSync('./grammars/existing.tmLanguage.json', 'utf-8'),
+         fs.readFileSync('./grammars/new.tmLanguage.json', 'utf-8'),
        ),
      ],
    },
  },
});
```


================================================
FILE: docs/grammars/generate.mjs
================================================
// @ts-check

import fs from 'node:fs/promises';

const markdown = {
	repo: 'shikijs/textmate-grammars-themes',
	tmLanguagePath: 'packages/tm-grammars/grammars/markdown.json',
};

const markdoc = {
	repo: 'markdoc/language-server',
	// We don't need the Markdoc grammar, only the Markdoc Markdown grammar.
	// tmLanguagePath: 'syntaxes/markdoc.tmLanguage.json',
	markdownTmLanguagePath: 'syntaxes/markdoc.markdown.tmLanguage.json',
};

/**
 * Download a TextMate grammar file from a GitHub repository.
 * @param {string} repo
 * @param {string} path
 */
async function fetchTmLanguage(repo, path) {
	const url = `https://raw.githubusercontent.com/${repo}/main/${path}`;
	const response = await fetch(url);
	const data = await response.json();
	return data;
}

// Download the TextMate grammar files for Markdown.
const markdownTmLanguage = await fetchTmLanguage(markdown.repo, markdown.tmLanguagePath);

// Download the TextMate grammar files for Markdoc Markdown.
const markdocMarkdownTmLanguage = await fetchTmLanguage(
	markdoc.repo,
	markdoc.markdownTmLanguagePath
);

// Reference: https://macromates.com/manual/en/language_grammars

// Update the name and scope name for the Markdoc grammar.
markdownTmLanguage.name = 'markdoc';
markdownTmLanguage.scopeName = 'text.html.markdoc';

// Merge the Markdown and Markdoc Markdown grammar repositories.
markdownTmLanguage.repository = {
	...markdownTmLanguage.repository,
	...markdocMarkdownTmLanguage.repository,
};

// Include the Markdoc Markdown grammar rules at the beginning of the Markdown grammar.
for (const rule of Object.keys(markdocMarkdownTmLanguage.repository)) {
	// Skip shortcut rules as they break syntax highlighting of child content that includes dots in
	// words and we don't ever use them.
	if (rule === 'shortcut') continue;

	markdownTmLanguage.repository.block.patterns.unshift({ include: `#${rule}` });
	markdownTmLanguage.repository.inline.patterns.unshift({ include: `#${rule}` });
}

// Write the grammar to a file.
await fs.writeFile(
	'./grammars/markdoc.tmLanguage.json',
	JSON.stringify(
		markdownTmLanguage,
		(key, value) => {
			// The `applyEndPatternLast` property should be a boolean and not a number.
			if (key === 'applyEndPatternLast') return Boolean(value);
			return value;
		},
		2
	)
);

console.log('Markdoc grammar generated successfully.');


================================================
FILE: docs/grammars/markdoc.tmLanguage.json
================================================
{
  "displayName": "Markdown",
  "name": "markdoc",
  "patterns": [
    {
      "include": "#frontMatter"
    },
    {
      "include": "#block"
    }
  ],
  "repository": {
    "ampersand": {
      "comment": "Markdown will convert this for us. We match it so that the HTML grammar will not mark it up as invalid.",
      "match": "&(?!([a-zA-Z0-9]+|#\\d+|#x[0-9a-fA-F]+);)",
      "name": "meta.other.valid-ampersand.markdown"
    },
    "block": {
      "patterns": [
        {
          "include": "#tag"
        },
        {
          "include": "#attribute"
        },
        {
          "include": "#separator"
        },
        {
          "include": "#heading"
        },
        {
          "include": "#blockquote"
        },
        {
          "include": "#lists"
        },
        {
          "include": "#fenced_code_block"
        },
        {
          "include": "#raw_block"
        },
        {
          "include": "#link-def"
        },
        {
          "include": "#html"
        },
        {
          "include": "#table"
        },
        {
          "include": "#paragraph"
        }
      ]
    },
    "blockquote": {
      "begin": "(^|\\G)[ ]{0,3}(>) ?",
      "captures": {
        "2": {
          "name": "punctuation.definition.quote.begin.markdown"
        }
      },
      "name": "markup.quote.markdown",
      "patterns": [
        {
          "include": "#block"
        }
      ],
      "while": "(^|\\G)\\s*(>) ?"
    },
    "bold": {
      "begin": "(?(\\*\\*(?=\\w)|(?]*+>|(?`+)([^`]|(?!(?(?!`))`)*+\\k|\\\\[\\\\`*_{}\\[\\]()#.!+\\->]?+|\\[((?[^\\[\\]\\\\]|\\\\.|\\[\\g*+\\])*+\\](([ ]?\\[[^\\]]*+\\])|(\\([ \\t]*+?[ \\t]*+((?['\"])(.*?)\\k<title>)?\\))))|(?!(?<=\\S)\\k<open>).)++(?<=\\S)(?=__\\b|\\*\\*)\\k<open>)",
      "captures": {
        "1": {
          "name": "punctuation.definition.bold.markdown"
        }
      },
      "end": "(?<=\\S)(\\1)",
      "name": "markup.bold.markdown",
      "patterns": [
        {
          "applyEndPatternLast": true,
          "begin": "(?=<[^>]*?>)",
          "end": "(?<=>)",
          "patterns": [
            {
              "include": "text.html.derivative"
            }
          ]
        },
        {
          "include": "#escape"
        },
        {
          "include": "#ampersand"
        },
        {
          "include": "#bracket"
        },
        {
          "include": "#raw"
        },
        {
          "include": "#bold"
        },
        {
          "include": "#italic"
        },
        {
          "include": "#image-inline"
        },
        {
          "include": "#link-inline"
        },
        {
          "include": "#link-inet"
        },
        {
          "include": "#link-email"
        },
        {
          "include": "#image-ref"
        },
        {
          "include": "#link-ref-literal"
        },
        {
          "include": "#link-ref"
        },
        {
          "include": "#link-ref-shortcut"
        },
        {
          "include": "#strikethrough"
        }
      ]
    },
    "bracket": {
      "comment": "Markdown will convert this for us. We match it so that the HTML grammar will not mark it up as invalid.",
      "match": "<(?![a-zA-Z/?$!])",
      "name": "meta.other.valid-bracket.markdown"
    },
    "escape": {
      "match": "\\\\[-`*_#+.!(){}\\[\\]\\\\>]",
      "name": "constant.character.escape.markdown"
    },
    "fenced_code_block": {
      "patterns": [
        {
          "include": "#fenced_code_block_css"
        },
        {
          "include": "#fenced_code_block_basic"
        },
        {
          "include": "#fenced_code_block_ini"
        },
        {
          "include": "#fenced_code_block_java"
        },
        {
          "include": "#fenced_code_block_lua"
        },
        {
          "include": "#fenced_code_block_makefile"
        },
        {
          "include": "#fenced_code_block_perl"
        },
        {
          "include": "#fenced_code_block_r"
        },
        {
          "include": "#fenced_code_block_ruby"
        },
        {
          "include": "#fenced_code_block_php"
        },
        {
          "include": "#fenced_code_block_sql"
        },
        {
          "include": "#fenced_code_block_vs_net"
        },
        {
          "include": "#fenced_code_block_xml"
        },
        {
          "include": "#fenced_code_block_xsl"
        },
        {
          "include": "#fenced_code_block_yaml"
        },
        {
          "include": "#fenced_code_block_dosbatch"
        },
        {
          "include": "#fenced_code_block_clojure"
        },
        {
          "include": "#fenced_code_block_coffee"
        },
        {
          "include": "#fenced_code_block_c"
        },
        {
          "include": "#fenced_code_block_cpp"
        },
        {
          "include": "#fenced_code_block_diff"
        },
        {
          "include": "#fenced_code_block_dockerfile"
        },
        {
          "include": "#fenced_code_block_git_commit"
        },
        {
          "include": "#fenced_code_block_git_rebase"
        },
        {
          "include": "#fenced_code_block_go"
        },
        {
          "include": "#fenced_code_block_groovy"
        },
        {
          "include": "#fenced_code_block_pug"
        },
        {
          "include": "#fenced_code_block_js"
        },
        {
          "include": "#fenced_code_block_js_regexp"
        },
        {
          "include": "#fenced_code_block_json"
        },
        {
          "include": "#fenced_code_block_jsonc"
        },
        {
          "include": "#fenced_code_block_less"
        },
        {
          "include": "#fenced_code_block_objc"
        },
        {
          "include": "#fenced_code_block_swift"
        },
        {
          "include": "#fenced_code_block_scss"
        },
        {
          "include": "#fenced_code_block_perl6"
        },
        {
          "include": "#fenced_code_block_powershell"
        },
        {
          "include": "#fenced_code_block_python"
        },
        {
          "include": "#fenced_code_block_julia"
        },
        {
          "include": "#fenced_code_block_regexp_python"
        },
        {
          "include": "#fenced_code_block_rust"
        },
        {
          "include": "#fenced_code_block_scala"
        },
        {
          "include": "#fenced_code_block_shell"
        },
        {
          "include": "#fenced_code_block_ts"
        },
        {
          "include": "#fenced_code_block_tsx"
        },
        {
          "include": "#fenced_code_block_csharp"
        },
        {
          "include": "#fenced_code_block_fsharp"
        },
        {
          "include": "#fenced_code_block_dart"
        },
        {
          "include": "#fenced_code_block_handlebars"
        },
        {
          "include": "#fenced_code_block_markdown"
        },
        {
          "include": "#fenced_code_block_log"
        },
        {
          "include": "#fenced_code_block_erlang"
        },
        {
          "include": "#fenced_code_block_elixir"
        },
        {
          "include": "#fenced_code_block_latex"
        },
        {
          "include": "#fenced_code_block_bibtex"
        },
        {
          "include": "#fenced_code_block_twig"
        },
        {
          "include": "#fenced_code_block_unknown"
        }
      ]
    },
    "fenced_code_block_basic": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(html|htm|shtml|xhtml|inc|tmpl|tpl)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.html",
          "patterns": [
            {
              "include": "text.html.basic"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_bibtex": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(bibtex)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.bibtex",
          "patterns": [
            {
              "include": "text.bibtex"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_c": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(c|h)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.c",
          "patterns": [
            {
              "include": "source.c"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_clojure": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(clj|cljs|clojure)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.clojure",
          "patterns": [
            {
              "include": "source.clojure"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_coffee": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(coffee|Cakefile|coffee.erb)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.coffee",
          "patterns": [
            {
              "include": "source.coffee"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_cpp": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(cpp|c\\+\\+|cxx)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.cpp source.cpp",
          "patterns": [
            {
              "include": "source.cpp"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_csharp": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(cs|csharp|c#)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.csharp",
          "patterns": [
            {
              "include": "source.cs"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_css": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(css|css.erb)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.css",
          "patterns": [
            {
              "include": "source.css"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_dart": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(dart)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.dart",
          "patterns": [
            {
              "include": "source.dart"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_diff": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(patch|diff|rej)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.diff",
          "patterns": [
            {
              "include": "source.diff"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_dockerfile": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(dockerfile|Dockerfile)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.dockerfile",
          "patterns": [
            {
              "include": "source.dockerfile"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_dosbatch": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(bat|batch)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.dosbatch",
          "patterns": [
            {
              "include": "source.batchfile"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_elixir": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(elixir)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.elixir",
          "patterns": [
            {
              "include": "source.elixir"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_erlang": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(erlang)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.erlang",
          "patterns": [
            {
              "include": "source.erlang"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_fsharp": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(fs|fsharp|f#)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.fsharp",
          "patterns": [
            {
              "include": "source.fsharp"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_git_commit": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(COMMIT_EDITMSG|MERGE_MSG)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.git_commit",
          "patterns": [
            {
              "include": "text.git-commit"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_git_rebase": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(git-rebase-todo)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.git_rebase",
          "patterns": [
            {
              "include": "text.git-rebase"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_go": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(go|golang)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.go",
          "patterns": [
            {
              "include": "source.go"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_groovy": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(groovy|gvy)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.groovy",
          "patterns": [
            {
              "include": "source.groovy"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_handlebars": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(handlebars|hbs)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.handlebars",
          "patterns": [
            {
              "include": "text.html.handlebars"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_ini": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(ini|conf)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.ini",
          "patterns": [
            {
              "include": "source.ini"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_java": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(java|bsh)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.java",
          "patterns": [
            {
              "include": "source.java"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_js": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(js|jsx|javascript|es6|mjs|cjs|dataviewjs|\\{\\.js.+?\\})((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.javascript",
          "patterns": [
            {
              "include": "source.js"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_js_regexp": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(regexp)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.js_regexp",
          "patterns": [
            {
              "include": "source.js.regexp"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_json": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(json|json5|sublime-settings|sublime-menu|sublime-keymap|sublime-mousemap|sublime-theme|sublime-build|sublime-project|sublime-completions)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.json",
          "patterns": [
            {
              "include": "source.json"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_jsonc": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(jsonc)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.jsonc",
          "patterns": [
            {
              "include": "source.json.comments"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_julia": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(julia|\\{\\.julia.+?\\})((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.julia",
          "patterns": [
            {
              "include": "source.julia"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_latex": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(latex|tex)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.latex",
          "patterns": [
            {
              "include": "text.tex.latex"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_less": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(less)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.less",
          "patterns": [
            {
              "include": "source.css.less"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_log": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(log)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.log",
          "patterns": [
            {
              "include": "text.log"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_lua": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(lua)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.lua",
          "patterns": [
            {
              "include": "source.lua"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_makefile": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(Makefile|makefile|GNUmakefile|OCamlMakefile)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.makefile",
          "patterns": [
            {
              "include": "source.makefile"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_markdown": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(markdown|md)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.markdown",
          "patterns": [
            {
              "include": "text.html.markdown"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_objc": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(objectivec|objective-c|mm|objc|obj-c|m|h)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.objc",
          "patterns": [
            {
              "include": "source.objc"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_perl": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(perl|pl|pm|pod|t|PL|psgi|vcl)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.perl",
          "patterns": [
            {
              "include": "source.perl"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_perl6": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(perl6|p6|pl6|pm6|nqp)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.perl6",
          "patterns": [
            {
              "include": "source.perl.6"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_php": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(php|php3|php4|php5|phpt|phtml|aw|ctp)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.php",
          "patterns": [
            {
              "include": "text.html.basic"
            },
            {
              "include": "source.php"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_powershell": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(powershell|ps1|psm1|psd1|pwsh)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.powershell",
          "patterns": [
            {
              "include": "source.powershell"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_pug": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(jade|pug)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.pug",
          "patterns": [
            {
              "include": "text.pug"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_python": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(python|py|py3|rpy|pyw|cpy|SConstruct|Sconstruct|sconstruct|SConscript|gyp|gypi|\\{\\.python.+?\\})((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.python",
          "patterns": [
            {
              "include": "source.python"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_r": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(R|r|s|S|Rprofile|\\{\\.r.+?\\})((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.r",
          "patterns": [
            {
              "include": "source.r"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_regexp_python": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(re)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.regexp_python",
          "patterns": [
            {
              "include": "source.regexp.python"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_ruby": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(ruby|rb|rbx|rjs|Rakefile|rake|cgi|fcgi|gemspec|irbrc|Capfile|ru|prawn|Cheffile|Gemfile|Guardfile|Hobofile|Vagrantfile|Appraisals|Rantfile|Berksfile|Berksfile.lock|Thorfile|Puppetfile)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.ruby",
          "patterns": [
            {
              "include": "source.ruby"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_rust": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(rust|rs|\\{\\.rust.+?\\})((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.rust",
          "patterns": [
            {
              "include": "source.rust"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_scala": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(scala|sbt)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.scala",
          "patterns": [
            {
              "include": "source.scala"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_scss": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(scss)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.scss",
          "patterns": [
            {
              "include": "source.css.scss"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_shell": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(shell|sh|bash|zsh|bashrc|bash_profile|bash_login|profile|bash_logout|.textmate_init|\\{\\.bash.+?\\})((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.shellscript",
          "patterns": [
            {
              "include": "source.shell"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_sql": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(sql|ddl|dml)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.sql",
          "patterns": [
            {
              "include": "source.sql"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_swift": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(swift)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.swift",
          "patterns": [
            {
              "include": "source.swift"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_ts": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(typescript|ts)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.typescript",
          "patterns": [
            {
              "include": "source.ts"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_tsx": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(tsx)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.typescriptreact",
          "patterns": [
            {
              "include": "source.tsx"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_twig": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(twig)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.twig",
          "patterns": [
            {
              "include": "source.twig"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_unknown": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?=([^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown"
    },
    "fenced_code_block_vs_net": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(vb)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.vs_net",
          "patterns": [
            {
              "include": "source.asp.vb.net"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_xml": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(xml|xsd|tld|jsp|pt|cpt|dtml|rss|opml)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.xml",
          "patterns": [
            {
              "include": "text.xml"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_xsl": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(xsl|xslt)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.xsl",
          "patterns": [
            {
              "include": "text.xml.xsl"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "fenced_code_block_yaml": {
      "begin": "(^|\\G)(\\s*)(`{3,}|~{3,})\\s*(?i:(yaml|yml)((\\s+|:|,|\\{|\\?)[^`]*)?$)",
      "beginCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        },
        "4": {
          "name": "fenced_code.block.language.markdown"
        },
        "5": {
          "name": "fenced_code.block.language.attributes.markdown"
        }
      },
      "end": "(^|\\G)(\\2|\\s{0,3})(\\3)\\s*$",
      "endCaptures": {
        "3": {
          "name": "punctuation.definition.markdown"
        }
      },
      "name": "markup.fenced_code.block.markdown",
      "patterns": [
        {
          "begin": "(^|\\G)(\\s*)(.*)",
          "contentName": "meta.embedded.block.yaml",
          "patterns": [
            {
              "include": "source.yaml"
            }
          ],
          "while": "(^|\\G)(?!\\s*([`~]{3,})\\s*$)"
        }
      ]
    },
    "frontMatter": {
      "applyEndPatternLast": true,
      "begin": "\\A(?=(-{3,}))",
      "end": "^ {,3}\\1-*[ \\t]*$|^[ \\t]*\\.{3}$",
      "endCaptures": {
        "0": {
          "name": "punctuation.definition.end.frontmatter"
        }
      },
      "patterns": [
        {
          "begin": "\\A(-{3,})(.*)$",
          "beginCaptures": {
            "1": {
              "name": "punctuation.definition.begin.frontmatter"
            },
            "2": {
              "name": "comment.frontmatter"
            }
          },
          "contentName": "meta.embedded.block.frontmatter",
          "patterns": [
            {
              "include": "source.yaml"
            }
          ],
          "while": "^(?! {,3}\\1-*[ \\t]*$|[ \\t]*\\.{3}$)"
        }
      ]
    },
    "heading": {
      "captures": {
        "1": {
          "patterns": [
            {
              "captures": {
                "1": {
                  "name": "punctuation.definition.heading.markdown"
                },
                "2": {
                  "name": "entity.name.section.markdown",
                  "patterns": [
                    {
                      "include": "#inline"
                    },
                    {
                      "include": "text.html.derivative"
                    }
                  ]
                },
                "3": {
                  "name": "punctuation.definition.heading.markdown"
                }
              },
              "match": "(#{6})\\s+(.*?)(?:\\s+(#+))?\\s*$",
              "name": "heading.6.markdown"
            },
            {
              "captures": {
                "1": {
                  "name": "punctuation.definition.heading.markdown"
                },
                "2": {
                  "name": "entity.name.section.markdown",
                  "patterns": [
                    {
                      "include": "#inline"
                    },
                    {
                      "include": "text.html.derivative"
                    }
                  ]
                },
                "3": {
                  "name": "punctuation.definition.heading.markdown"
                }
              },
              "match": "(#{5})\\s+(.*?)(?:\\s+(#+))?\\s*$",
              "name": "heading.5.markdown"
            },
            {
              "captures": {
                "1": {
                  "name": "punctuation.definition.heading.markdown"
                },
                "2": {
                  "name": "entity.name.section.markdown",
                  "patterns": [
                    {
                      "include": "#inline"
                    },
                    {
                      "include": "text.html.derivative"
                    }
                  ]
                },
                "3": {
                  "name": "punctuation.definition.heading.markdown"
                }
              },
              "match": "(#{4})\\s+(.*?)(?:\\s+(#+))?\\s*$",
              "name": "heading.4.markdown"
            },
            {
              "captures": {
                "1": {
                  "name": "punctuation.definition.heading.markdown"
                },
                "2": {
                  "name": "entity.name.section.markdown",
                  "patterns": [
                    {
                      "include": "#inline"
                    },
                    {
                      "include": "text.html.derivative"
                    }
                  ]
                },
                "3": {
                  "name": "punctuation.definition.heading.markdown"
                }
              },
              "match": "(#{3})\\s+(.*?)(?:\\s+(#+))?\\s*$",
              "name": "heading.3.markdown"
            },
            {
              "captures": {
                "1": {
                  "name": "punctuation.definition.heading.markdown"
                },
                "2": {
                  "name": "entity.name.section.markdown",
                  "patterns": [
                    {
                      "include": "#inline"
                    },
                    {
                      "include": "text.html.derivative"
                    }
                  ]
                },
                "3": {
                  "name": "punctuation.definition.heading.markdown"
                }
              },
              "match": "(#{2})\\s+(.*?)(?:\\s+(#+))?\\s*$",
              "name": "heading.2.markdown"
            },
            {
              "captures": {
                "1": {
                  "name": "punctuation.definition.heading.markdown"
                },
                "2": {
                  "name": "entity.name.section.markdown",
                  "patterns": [
                    {
                      "include": "#inline"
                    },
                    {
                      "include": "text.html.derivative"
                    }
                  ]
                },
                "3": {
                  "name": "punctuation.definition.heading.markdown"
                }
              },
              "match": "(#{1})\\s+(.*?)(?:\\s+(#+))?\\s*$",
              "name": "heading.1.markdown"
            }
          ]
        }
      },
      "match": "(?:^|\\G)[ ]{0,3}(#{1,6}\\s+(.*?)(\\s+#{1,6})?\\s*)$",
      "name": "markup.heading.markdown"
    },
    "heading-setext": {
      "patterns": [
        {
          "match": "^(={3,})(?=[ \\t]*$\\n?)",
          "name": "markup.heading.setext.1.markdown"
        },
        {
          "match": "^(-{3,})(?=[ \\t]*$\\n?)",
          "name": "markup.heading.setext.2.markdown"
        }
      ]
    },
    "html": {
      "patterns": [
        {
          "begin": "(^|\\G)\\s*(<!--)",
          "captures": {
            "1": {
              "name": "punctuation.definition.comment.html"
            },
            "2": {
              "name": "punctuation.definition.comment.html"
            }
          },
          "end": "(-->)",
          "name": "comment.block.html"
        },
        {
          "begin": "(?i)(^|\\G)\\s*(?=<(script|style|pre)(\\s|$|>)(?!.*?</(script|style|pre)>))",
          "end": "(?i)(.*)((</)(script|style|pre)(>))",
          "endCaptures": {
            "1": {
              "patterns": [
                {
                  "include": "text.html.derivative"
                }
              ]
            },
            "2": {
              "name": "meta.tag.structure.$4.end.html"
            },
            "3": {
              "name": "punctuation.definition.tag.begin.html"
            },
            "4": {
              "name": "entity.name.tag.html"
            },
            "5": {
              "name": "punctuation.definition.tag.end.html"
            }
          },
          "patterns": [
            {
              "begin": "(\\s*|$)",
              "patterns": [
                {
                  "include": "text.html.derivative"
                }
              ],
              "while": "(?i)^(?!.*</(script|style|pre)>)"
            }
          ]
        },
        {
          "begin": "(?i)(^|\\G)\\s*(?=</?[a-zA-Z]+[^\\s/>]*(\\s|$|/?>))",
          "patterns": [
            {
              "include": "text.html.derivative"
            }
          ],
          "while": "^(?!\\s*$)"
        },
        {
          "begin": "(^|\\G)\\s*(?=(<[a-zA-Z0-9\\-](/?>|\\s.*?>)|</[a-zA-Z0-9\\-]>)\\s*$)",
          "patterns": [
            {
              "include": "text.html.derivative"
            }
          ],
          "while": "^(?!\\s*$)"
        }
      ]
    },
    "image-inline": {
      "captures": {
        "1": {
          "name": "punctuation.definition.link.description.begin.markdown"
        },
        "2": {
          "name": "string.other.link.description.markdown"
        },
        "4": {
          "name": "punctuation.definition.link.description.end.markdown"
        },
        "5": {
          "name": "punctuation.definition.metadata.markdown"
        },
        "7": {
          "name": "punctuation.definition.link.markdown"
        },
        "8": {
          "name": "markup.underline.link.image.markdown"
        },
        "9": {
          "name": "punctuation.definition.link.markdown"
        },
        "10": {
          "name": "markup.underline.link.image.markdown"
        },
        "12": {
          "name": "string.other.link.description.title.markdown"
        },
        "13": {
          "name": "punctuation.definition.string.begin.markdown"
        },
        "14": {
          "name": "punctuation.definition.string.end.markdown"
        },
        "15": {
          "name": "string.other.link.description.title.markdown"
        },
        "16": {
          "name": "punctuation.definition.string.begin.markdown"
        },
        "17": {
          "name": "punctuation.definition.string.end.markdown"
        },
        "18": {
          "name": "string.other.link.description.title.markdown"
        },
        "19": {
          "name": "punctuation.definition.string.begin.markdown"
        },
        "20": {
          "name": "punctuation.definition.string.end.markdown"
        },
        "21": {
          "name": "punctuation.definition.metadata.markdown"
        }
      },
      "match": "(!\\[)((?<square>[^\\[\\]\\\\]|\\\\.|\\[\\g<square>*+\\])*+)(\\])(\\()[ \\t]*((<)((?:\\\\[<>]|[^<>\\n])*)(>)|((?<url>(?>[^\\s()]+)|\\(\\g<url>*\\))*))[ \\t]*(?:((\\().+?(\\)))|((\").+?(\"))|((').+?(')))?\\s*(\\))",
      "name": "meta.image.inline.markdown"
    },
    "image-ref": {
      "captures": {
        "1": {
          "name": "punctuation.definition.link.description.begin.markdown"
        },
        "2": {
          "name": "string.other.link.description.markdown"
        },
        "4": {
          "name": "punctuation.definition.link.description.end.markdown"
        },
        "5": {
          "name": "punctuation.definition.constant.markdown"
        },
        "6": {
          "name": "constant.other.reference.link.markdown"
        },
        "7": {
          "name": "punctuation.definition.constant.markdown"
        }
      },
      "match": "(!\\[)((?<square>[^\\[\\]\\\\]|\\\\.|\\[\\g<square>*+\\])*+)(\\])[ ]?(\\[)(.*?)(\\])",
      "name": "meta.image.reference.markdown"
    },
    "inline": {
      "patterns": [
        {
          "include": "#tag"
        },
        {
          "include": "#attribute"
        },
        {
          "include": "#ampersand"
        },
        {
          "include": "#bracket"
        },
        {
          "include": "#bold"
        },
        {
          "include": "#italic"
        },
        {
          "include": "#raw"
        },
        {
          "include": "#strikethrough"
        },
        {
          "include": "#escape"
        },
        {
          "include": "#image-inline"
        },
        {
          "include": "#image-ref"
        },
        {
          "include": "#link-email"
        },
        {
          "include": "#link-inet"
        },
        {
          "include": "#link-inline"
        },
        {
          "include": "#link-ref"
        },
        {
          "include": "#link-ref-literal"
        },
        {
          "include": "#link-ref-shortcut"
        }
      ]
    },
    "italic": {
      "begin": "(?<open>(\\*(?=\\w)|(?<!\\w)\\*|(?<!\\w)\\b_))(?=\\S)(?=(<[^>]*+>|(?<raw>`+)([^`]|(?!(?<!`)\\k<raw>(?!`))`)*+\\k<raw>|\\\\[\\\\`*_{}\\[\\]()#.!+\\->]?+|\\[((?<square>[^\\[\\]\\\\]|\\\\.|\\[\\g<square>*+\\])*+\\](([ ]?\\[[^\\]]*+\\])|(\\([ \\t]*+<?(.*?)>?[ \\t]*+((?<title>['\"])(.*?)\\k<title>)?\\))))|\\k<open>\\k<open>|(?!(?<=\\S)\\k<open>).)++(?<=\\S)(?=_\\b|\\*)\\k<open>)",
      "captures": {
        "1": {
          "name": "punctuation.definition.italic.markdown"
        }
      },
      "end": "(?<=\\S)(\\1)((?!\\1)|(?=\\1\\1))",
      "name": "markup.italic.markdown",
      "patterns": [
        {
          "applyEndPatternLast": true,
          "begin": "(?=<[^>]*?>)",
          "end": "(?<=>)",
          "patterns": [
            {
              "include": "text.html.derivative"
            }
          ]
        },
        {
          "include": "#escape"
        },
        {
          "include": "#ampersand"
        },
        {
          "include": "#bracket"
        },
        {
          "include": "#raw"
        },
        {
          "include": "#bold"
        },
        {
          "include": "#image-inline"
        },
        {
          "include": "#link-inline"
        },
        {
          "include": "#link-inet"
        },
        {
          "include": "#link-email"
        },
        {
          "include": "#image-ref"
        },
        {
          "include": "#link-ref-literal"
        },
        {
          "include": "#link-ref"
        },
        {
          "include": "#link-ref-shortcut"
        },
        {
          "include": "#strikethrough"
        }
      ]
    },
    "link-def": {
      "captures": {
        "1": {
          "name": "punctuation.definition.constant.markdown"
        },
        "2": {
          "name": "constant.other.reference.link.markdown"
        },
        "3": {
          "name": "punctuation.definition.constant.markdown"
        },
        "4": {
          "name": "punctuation.separator.key-value.markdown"
        },
        "5": {
          "name": "punctuation.definition.link.markdown"
        },
        "6": {
          "name": "markup.underline.link.markdown"
        },
        "7": {
          "name": "punctuation.definition.link.markdown"
        },
        "8": {
          "name": "markup.underline.link.markdown"
        },
        "9": {
          "name": "string.other.link.description.title.markdown"
        },
        "10": {
          "name": "punctuation.definition.string.begin.markdown"
        },
        "11": {
          "name": "punctuation.definition.string.end.markdown"
        },
        "12": {
          "name": "string.other.link.description.title.markdown"
        },
        "13": {
          "name": "punctuation.definition.string.begin.markdown"
        },
        "14": {
          "name": "punctuation.definition.string.end.markdown"
        },
        "15": {
          "name": "string.other.link.description.title.markdown"
        },
        "16": {
          "name": "punctuation.definition.string.begin.markdown"
        },
        "17": {
          "name": "punctuation.definition.string.end.markdown"
        }
      },
      "match": "\\s*(\\[)([^]]+?)(\\])(:)[ \\t]*(?:(<)((?:\\\\[<>]|[^<>\\n])*)(>)|(\\S+?))[ \\t]*(?:((\\().+?(\\)))|((\").+?(\"))|((').+?(')))?\\s*$",
      "name": "meta.link.reference.def.markdown"
    },
    "link-email": {
      "captures": {
        "1": {
          "name": "punctuation.definition.link.markdown"
        },
        "2": {
          "name": "markup.underline.link.markdown"
        },
        "4": {
          "name": "punctuation.definition.link.markdown"
        }
      },
      "match": "(<)((?:mailto:)?[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*)(>)",
      "name": "meta.link.email.lt-gt.markdown"
    },
    "link-inet": {
      "captures": {
        "1": {
          "name": "punctuation.definition.link.markdown"
        },
        "2": {
          "name": "markup.underline.link.markdown"
        },
        "3": {
          "name": "punctuation.definition.link.markdown"
        }
      },
      "match": "(<)((?:https?|ftp)://.*?)(>)",
      "name": "meta.link.inet.markdown"
    },
    "link-inline": {
      "captures": {
        "1": {
          "name": "punctuation.definition.link.title.begin.markdown"
        },
        "2": {
          "name": "string.other.link.title.markdown",
          "patterns": [
            {
              "include": "#raw"
            },
            {
              "include": "#bold"
            },
            {
              "include": "#italic"
            },
            {
              "include": "#strikethrough"
            },
            {
              "include": "#image-inline"
            }
          ]
        },
        "4": {
          "name": "punctuation.definition.link.title.end.markdown"
        },
        "5": {
          "name": "punctuation.definition.metadata.markdown"
        },
        "7": {
          "name": "punctuation.definition.link.markdown"
        },
        "8": {
          "name": "markup.underline.link.markdown"
        },
        "9": {
          "name": "punctuation.definition.link.markdown"
        },
        "10": {
          "name": "markup.underline.link.markdown"
        },
        "12": {
          "name": "string.other.link.description.title.markdown"
        },
        "13": {
          "name": "punctuation.definition.string.begin.markdown"
        },
        "14": {
          "name": "punctuation.definition.string.end.markdown"
        },
        "15": {
          "name": "string.other.link.description.title.markdown"
        },
        "16": {
          "name": "punctuation.definition.string.begin.markdown"
        },
        "17": {
          "name": "punctuation.definition.string.end.markdown"
        },
        "18": {
          "name": "string.other.link.description.title.markdown"
        },
        "19": {
          "name": "punctuation.definition.string.begin.markdown"
        },
        "20": {
          "name": "punctuation.definition.string.end.markdown"
        },
        "21": {
          "name": "punctuation.definition.metadata.markdown"
        }
      },
      "match": "(\\[)((?<square>[^\\[\\]\\\\]|\\\\.|\\[\\g<square>*+\\])*+)(\\])(\\()[ \\t]*((<)((?:\\\\[<>]|[^<>\\n])*)(>)|((?<url>(?>[^\\s()]+)|\\(\\g<url>*\\))*))[ \\t]*(?:((\\()[^()]*(\\)))|((\")[^\"]*(\"))|((')[^']*(')))?\\s*(\\))",
      "name": "meta.link.inline.markdown"
    },
    "link-ref": {
      "captures": {
        "1": {
          "name": "punctuation.definition.link.title.begin.markdown"
        },
        "2": {
          "name": "string.other.link.title.markdown",
          "patterns": [
            {
              "include": "#raw"
            },
            {
              "include": "#bold"
            },
            {
              "include": "#italic"
            },
            {
              "include": "#strikethrough"
            },
            {
              "include": "#image-inline"
            }
          ]
        },
        "4": {
          "name": "punctuation.definition.link.title.end.markdown"
        },
        "5": {
          "name": "punctuation.definition.constant.begin.markdown"
        },
        "6": {
          "name": "constant.other.reference.link.markdown"
        },
        "7": {
          "name": "punctuation.definition.constant.end.markdown"
        }
      },
      "match": "(?<![\\]\\\\])(\\[)((?<square>[^\\[\\]\\\\]|\\\\.|\\[\\g<square>*+\\])*+)(\\])(\\[)([^\\]]*+)(\\])",
      "name": "meta.link.reference.markdown"
    },
    "link-ref-literal": {
      "captures": {
        "1": {
          "name": "punctuation.definition.link.title.begin.markdown"
        },
        "2": {
          "name": "string.other.link.title.markdown"
        },
        "4": {
          "name": "punctuation.definition.link.title.end.markdown"
        },
        "5": {
          "name": "punctuation.definition.constant.begin.markdown"
        },
        "6": {
          "name": "punctuation.definition.constant.end.markdown"
        }
      },
      "match": "(?<![\\]\\\\])(\\[)((?<square>[^\\[\\]\\\\]|\\\\.|\\[\\g<square>*+\\])*+)(\\])[ ]?(\\[)(\\])",
      "name": "meta.link.reference.literal.markdown"
    },
    "link-ref-shortcut": {
      "captures": {
        "1": {
          "name": "punctuation.definition.link.title.begin.markdown"
        },
        "2": {
          "name": "string.other.link.title.markdown"
        },
        "3": {
          "name": "punctuation.definition.link.title.end.markdown"
        }
      },
      "match": "(?<![\\]\\\\])(\\[)((?:[^\\s\\[\\]\\\\]|\\\\[\\[\\]])+?)((?<!\\\\)\\])",
      "name": "meta.link.reference.markdown"
    },
    "list_paragraph": {
      "begin": "(^|\\G)(?=\\S)(?![*+->]\\s|\\d+\\.\\s)",
      "name": "meta.paragraph.markdown",
      "patterns": [
        {
          "include": "#inline"
        },
        {
          "include": "text.html.derivative"
        },
        {
          "include": "#heading-setext"
        }
      ],
      "while": "(^|\\G)(?!\\s*$|#|[ ]{0,3}([-*_>][ ]{2,}){3,}[ \\t]*$\\n?|[ ]{0,3}[*+->]|[ ]{0,3}\\d+\\.)"
    },
    "lists": {
      "patterns": [
        {
          "begin": "(^|\\G)([ ]{0,3})([*+-])([ \\t])",
          "beginCaptures": {
            "3": {
              "name": "punctuation.definition.list.begin.markdown"
            }
          },
          "comment": "Currently does not support un-indented second lines.",
          "name": "markup.list.unnumbered.markdown",
          "patterns": [
            {
              "include": "#block"
            },
            {
              "include": "#list_paragraph"
            }
          ],
          "while": "((^|\\G)([ ]{2,4}|\\t))|(^[ \\t]*$)"
        },
        {
          "begin": "(^|\\G)([ ]{0,3})(\\d+[\\.)])([ \\t])",
          "beginCaptures": {
            "3": {
              "name": "punctuation.definition.list.begin.markdown"
            }
          },
          "name": "markup.list.numbered.markdown",
          "patterns": [
            {
              "include": "#block"
            },
            {
              "include": "#list_paragraph"
            }
          ],
          "while": "((^|\\G)([ ]{2,4}|\\t))|(^[ \\t]*$)"
        }
      ]
    },
    "paragraph": {
      "begin": "(^|\\G)[ ]{0,3}(?=[^ \\t\\n])",
      "name": "meta.paragraph.markdown",
      "patterns": [
        {
          "include": "#inline"
        },
        {
          "include": "text.html.derivative"
        },
        {
          "include": "#heading-setext"
        }
      ],
      "while": "(^|\\G)((?=\\s*[-=]{3,}\\s*$)|[ ]{4,}(?=[^ \\t\\n]))"
    },
    "raw": {
      "captures": {
        "1": {
          "name": "punctuation.definition.raw.markdown"
        },
        "3": {
          "name": "punctuation.definition.raw.markdown"
        }
      },
      "match": "(`+)((?:[^`]|(?!(?<!`)\\1(?!`))`)*+)(\\1)",
      "name": "markup.inline.raw.string.markdown"
    },
    "raw_block": {
      "begin": "(^|\\G)([ ]{4}|\\t)",
      "name": "markup.raw.block.markdown",
      "while": "(^|\\G)([ ]{4}|\\t)"
    },
    "separator": {
      "match": "(^|\\G)[ ]{0,3}([\\*\\-_])([ ]{0,2}\\2){2,}[ \\t]*$\\n?",
      "name": "meta.separator.markdown"
    },
    "strikethrough": {
      "captures": {
        "1": {
          "name": "punctuation.definition.strikethrough.markdown"
        },
        "2": {
          "patterns": [
            {
              "applyEndPatternLast": true,
              "begin": "(?=<[^>]*?>)",
              "end": "(?<=>)",
              "patterns": [
                {
                  "include": "text.html.derivative"
                }
              ]
            },
            {
              "include": "#escape"
            },
            {
              "include": "#ampersand"
            },
            {
              "include": "#bracket"
            },
            {
              "include": "#raw"
            },
            {
              "include": "#bold"
            },
            {
              "include": "#italic"
            },
            {
              "include": "#image-inline"
            },
            {
              "include": "#link-inline"
            },
            {
              "include": "#link-inet"
            },
            {
              "include": "#link-email"
            },
            {
              "include": "#image-ref"
            },
            {
              "include": "#link-ref-literal"
            },
            {
              "include": "#link-ref"
            },
            {
              "include": "#link-ref-shortcut"
            }
          ]
        },
        "3": {
          "name": "punctuation.definition.strikethrough.markdown"
        }
      },
      "match": "(?<!\\\\)(~{2,})((?:[^~]|(?!(?<![~\\\\])\\1(?!~))~)*+)(\\1)",
      "name": "markup.strikethrough.markdown"
    },
    "table": {
      "begin": "(^|\\G)(\\|)(?=[^|].+\\|\\s*$)",
      "beginCaptures": {
        "2": {
          "name": "punctuation.definition.table.markdown"
        }
      },
      "name": "markup.table.markdown",
      "patterns": [
        {
          "match": "\\|",
          "name": "punctuation.definition.table.markdown"
        },
        {
          "captures": {
            "1": {
              "name": "punctuation.separator.table.markdown"
            }
          },
          "match": "(?<=\\|)\\s*(:?-+:?)\\s*(?=\\|)"
        },
        {
          "captures": {
            "1": {
              "patterns": [
                {
                  "include": "#inline"
                }
              ]
            }
          },
          "match": "(?<=\\|)\\s*(?=\\S)((\\\\\\||[^|])+)(?<=\\S)\\s*(?=\\|)"
        }
      ],
      "while": "(^|\\G)(?=\\|)"
    },
    "shortcut": {
      "match": "(\\$|\\.|#)([-_:a-zA-Z0-9]+)",
      "name": "string.other.markdoc-shortcut"
    },
    "attribute": {
      "match": "([-_a-zA-Z0-9]+)(=)",
      "captures": {
        "1": {
          "name": "entity.other.attribute-name"
        },
        "2": {
          "name": "punctuation.definition.tag.equal.markdoc"
        }
      }
    },
    "tag": {
      "name": "punctuation.definition.tag",
      "begin": "({%)\\s*/?([-_a-zA-Z0-9]+)?",
      "end": "\\s*/?\\s*%}",
      "beginCaptures": {
        "1": {
          "name": "punctuation.definition.tag.begin.markdoc"
        },
        "2": {
          "name": "entity.name.tag"
        }
      },
      "endCaptures": {
        "0": {
          "name": "punctuation.definition.tag.end.markdoc"
        }
      },
      "patterns": [
        {
          "include": "#attribute"
        },
        {
          "include": "#shortcut"
        },
        {
          "include": "source.json"
        }
      ]
    }
  },
  "scopeName": "text.html.markdoc"
}


================================================
FILE: docs/lunaria/components.ts
================================================
import { html } from '@lunariajs/core';

export const TitleParagraph = () => html`
	<p>
		If you're interested in helping us translate
		<a href="https://starlight.astro.build/">starlight.astro.build</a> into one of the languages
		listed below, you've come to the right place! This auto-updating page always lists all the
		content that could use your help right now.
	</p>
	<p>
		Before starting a new translation, please read our
		<a
			href="https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md#translating-starlights-docs"
			>translation guide</a
		>
		to learn about our translation process and how you can get involved.
	</p>
`;


================================================
FILE: docs/lunaria/renderer.config.ts
================================================
import { defineRendererConfig } from '@lunariajs/core';
import { TitleParagraph } from './components';

export default defineRendererConfig({
	slots: {
		afterTitle: TitleParagraph,
	},
});


================================================
FILE: docs/lunaria/styles.css
================================================
:root {
	--theme-accent: hsl(234, 100%, 87%);
	--theme-bg: hsl(223, 13%, 10%);
	--theme-table-header: hsl(222, 13%, 16%);
	--theme-table-hover: hsl(222, 13%, 16%);
	--theme-text: hsl(228, 8%, 77%);
	--theme-text-bright: hsl(0, 0%, 100%);
	--overlay-blurple: hsla(255, 60%, 60%, 0.2);

	--ln-color-background: linear-gradient(215deg, var(--overlay-blurple), transparent 40%),
		radial-gradient(var(--overlay-blurple), transparent 40%) no-repeat -60vw -40vh / 105vw 200vh,
		radial-gradient(var(--overlay-blurple), transparent 65%) no-repeat 50% calc(100% + 20rem) /
			60rem 30rem,
		var(--theme-bg);
	--ln-color-link: var(--theme-accent);
	--ln-color-black: var(--theme-text);
	--ln-color-done: var(--ln-color-blue);
	--ln-color-outdated: #ea580c;
	--ln-color-missing: var(--theme-text-bright);
	--ln-color-table-background: var(--theme-table-header);
	--ln-color-table-border: var(--theme-table-header);

	color-scheme: dark;
}

h1,
h2,
h3,
h4,
h5,
h6 {
	color: var(--theme-text-bright);
}

p a {
	text-decoration: underline;
}

.create-button {
	background-color: hsl(213deg 89% 64% / 20%);
	border-radius: 0.5em;
}

sup {
	display: flex;
	justify-content: center;
}


================================================
FILE: docs/lunaria.config.json
================================================
{
  "$schema": "./node_modules/@lunariajs/core/config.schema.json",
  "repository": {
    "name": "withastro/starlight",
    "rootDir": "docs"
  },
  "defaultLocale": {
    "label": "English",
    "lang": "en"
  },
  "locales": [
    {
      "label": "Dansk",
      "lang": "da"
    },
    {
      "label": "Deutsch",
      "lang": "de"
    },
    {
      "label": "Español",
      "lang": "es"
    },
    {
      "label": "Français",
      "lang": "fr"
    },
    {
      "label": "हिंदी",
      "lang": "hi"
    },
    {
      "label": "Bahasa Indonesia",
      "lang": "id"
    },
    {
      "label": "Italiano",
      "lang": "it"
    },
    {
      "label": "日本語",
      "lang": "ja"
    },
    {
      "label": "한국어",
      "lang": "ko"
    },
    {
      "label": "Português do Brasil",
      "lang": "pt-br"
    },
    {
      "label": "Português",
      "lang": "pt-pt"
    },
    {
      "label": "Русский",
      "lang": "ru"
    },
    {
      "label": "Türkçe",
      "lang": "tr"
    },
    {
      "label": "Українська",
      "lang": "uk"
    },
    {
      "label": "简体中文",
      "lang": "zh-cn"
    }
  ],
  "files": [
    {
      "location": "src/content/docs/**/*.{md,mdx}",
      "pattern": "src/content/docs/@lang/@path",
      "type": "universal"
    }
  ],
  "dashboard": {
    "title": "Starlight Docs Translation Status",
    "description": "Translation progress tracker for the Starlight Docs site. See how much has been translated in your language and get involved!",
    "favicon": {
      "external": [
        {
          "link": "https://starlight.astro.build/favicon.svg",
          "type": "image/svg+xml"
        }
      ]
    },
    "customCss": ["./lunaria/styles.css"],
    "basesToHide": ["src/content/docs/"],
    "ui": {
      "statusByLocale.heading": "Translation progress by locale",
      "statusByLocale.incompleteLocalizationLink": "incomplete translation",
      "statusByLocale.outdatedLocalizationLink": "outdated translation",
      "statusByLocale.completeLocalization": "This translation is complete, amazing job! 🎉",
      "statusByFile.heading": "Translation status by file"
    }
  },
  "ignoreKeywords": ["lunaria-ignore", "typo", "en-only", "broken link", "i18nReady", "i18nIgnore"],
  "renderer": "./lunaria/renderer.config.ts"
}


================================================
FILE: docs/package.json
================================================
{
  "name": "starlight-docs",
  "private": true,
  "type": "module",
  "version": "0.0.1",
  "scripts": {
    "test": "playwright install --with-deps chromium && playwright test",
    "dev": "astro dev",
    "start": "astro dev",
    "build": "astro build",
    "preview": "astro preview",
    "typecheck": "tsc --noEmit",
    "linkcheck": "CHECK_LINKS=true pnpm build",
    "astro": "astro",
    "lunaria:build": "lunaria build",
    "grammars": "node grammars/generate.mjs"
  },
  "dependencies": {
    "@astro-community/astro-embed-youtube": "^0.5.10",
    "@astrojs/starlight": "workspace:*",
    "@lunariajs/core": "^0.1.1",
    "@types/culori": "^2.1.1",
    "astro": "^6.0.1",
    "culori": "^4.0.1",
    "sharp": "^0.34.2"
  },
  "devDependencies": {
    "@playwright/test": "^1.57.0",
    "axe-playwright": "^2.0.3",
    "sitemapper": "^3.2.12",
    "starlight-links-validator": "^0.20.0"
  }
}


================================================
FILE: docs/playwright.config.ts
================================================
import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
	forbidOnly: !!process.env['CI'],
	projects: [
		{
			name: 'Chrome Stable',
			use: {
				...devices['Desktop Chrome'],
				headless: true,
			},
		},
	],
	testMatch: '__a11y__/*.test.ts',
	// The timeout for the accessibility tests only.
	timeout: 180 * 1_000,
	webServer: [
		{
			command: 'pnpm run build && pnpm run preview',
			reuseExistingServer: !process.env['CI'],
			stdout: 'pipe',
			// The timeout of the single build step ran before the accessibility tests.
			timeout: 120 * 1_000,
			url: 'http://localhost:4321',
		},
	],
	workers: 1,
});


================================================
FILE: docs/public/_headers
================================================
/_astro/*
  Cache-Control: public
  Cache-Control: max-age=31536000
  Cache-Control: immutable


================================================
FILE: docs/public/_redirects
================================================
# Proxy to Phat Houston from our Product Hunt launch — site operated by Otterlord
/ph/*               https://astro-houston-ph.pages.dev/ph/:splat    200

# Moved content
/zh/*               /zh-cn/:splat
/showcase/          /resources/showcase/
/:lang/showcase/    /:lang/resources/showcase/

# Component docs
/guides/components/          /components/using-components/
/:lang/guides/components/    /:lang/components/using-components/

# Translated 404s
/:lang/*            /:lang/404/     404
/*                  /404/           404


================================================
FILE: docs/src/assets/landing.css
================================================
:root {
	--purple-hsl: 255, 60%, 60%;
	--overlay-blurple: hsla(var(--purple-hsl), 0.2);
}

:root[data-theme='light'] {
	--purple-hsl: 255, 85%, 65%;
}

[data-has-hero] .page {
	background:
		linear-gradient(215deg, var(--overlay-blurple), transparent 40%),
		radial-gradient(var(--overlay-blurple), transparent 40%) no-repeat -60vw -40vh / 105vw 200vh,
		radial-gradient(var(--overlay-blurple), transparent 65%) no-repeat 50% calc(100% + 20rem) /
			60rem 30rem;
}

[data-has-hero] header {
	border-bottom: 1px solid transparent;
	background-color: transparent;
	-webkit-backdrop-filter: blur(16px);
	backdrop-filter: blur(16px);
}

[data-has-hero] .hero > img {
	filter: drop-shadow(0 0 3rem var(--overlay-blurple));
}


================================================
FILE: docs/src/assets/robots.txt
================================================
User-agent: *
Allow: /

Sitemap: https://starlight.astro.build/sitemap-index.xml


================================================
FILE: docs/src/components/about-astro.astro
================================================
---
interface Props {
	title: string;
}

const { title } = Astro.props;
---

<article class="sl-flex" aria-labelledby="about-astro-heading">
	<small id="about-astro-heading">
		{title}
		<span class="sr-only">Astro</span>
	</small>
	<svg
		aria-hidden="true"
		xmlns="http://www.w3.org/2000/svg"
		viewBox="0 0 301 79"
		fill="var(--sl-color-white)"
	>
		<path
			d="M20.8 66.8c-3.6-3.2-4.6-10-3.1-15 2.5 3.2 6.1 4.2 9.8 4.7 5.7.9 11.3.6 16.5-2l1.9-1.1a9 9 0 0 1 .4 4.3 12 12 0 0 1-5 8.5l-3.6 2.4c-3.6 2.4-4.6 5.3-3.2 9.4l.1.5c-1.8-.8-3.2-2-4.2-3.6-1-1.7-1.6-3.5-1.6-5.5 0-1 0-2-.2-3-.3-2.3-1.4-3.3-3.4-3.4a4 4 0 0 0-4.3 3.3l-.1.5ZM.5 51s10.5-5 21-5l8-24.6c.3-1.2 1.2-2 2.2-2 1 0 1.8.8 2.1 2l8 24.5c12.5 0 21 5.1 21 5.1L45 2.4C44.4.9 43.6 0 42.4 0H21c-1.2 0-2 1-2.6 2.4L.5 51Zm111-7c0 4.3-5.4 6.8-12.8 6.8-4.9 0-6.6-1.2-6.6-3.7 0-2.6 2.1-3.9 7-3.9 4.3 0 8 .1 12.4.6v.2Zm0-5.4a56 56 0 0 0-11.4-1c-14 0-20.5 3.4-20.5 11 0 8 4.5 11 14.9 11 8.8 0 14.7-2.2 17-7.6h.3l-.2 3.6c0 2.8.5 3 2.8 3h10.9c-.6-1.6-1-6.3-1-10.4l.2-12c0-9.1-5.4-14.8-22.4-14.8a83 83 0 0 0-21.7 3C81 27 82 32 82.3 35.2c5.3-2.5 13-3.6 18.8-3.6 8.2 0 10.4 1.9 10.4 5.6v1.5Zm29.8 7.9c-1.5.2-3.5.2-5.5.2-2.2 0-4.2-.1-5.6-.3V48c0 7.5 4.9 11.8 22 11.8 16.3 0 21.6-4.3 21.6-11.8 0-7.2-3.5-10.8-19-11.5-11.9-.6-13-1.9-13-3.4 0-1.7 1.6-2.6 9.6-2.6 8.3 0 10.6 1.1 10.6 3.5v.6a120.9 120.9 0 0 1 11 0l.1-1.4c0-8.8-7.3-11.7-21.5-11.7-15.9 0-21.3 4-21.3 11.5 0 6.8 4.3 11 19.6 11.7 11.3.4 12.5 1.6 12.5 3.4 0 1.8-1.8 2.7-9.7 2.7-9 0-11.4-1.3-11.4-3.9v-.3ZM193.2 15c-4.3 4-12 8-16.3 9v8.5l4 .1-.1 12.8c0 8 4.2 14 17.2 14 5.5 0 9.1-.7 13.7-1.6-.5-3-1-7.4-1.2-10.8-2.7.9-6.1 1.3-10 1.3-5.2 0-7.3-1.4-7.3-5.5v-10l17.5.2c0-3 0-7.6.2-10.6-5.7.2-12.1.2-17.4.2l.1-7.6h-.4Zm35.3 15.8.1-8.4h-11.8a752.4 752.4 0 0 1 0 36.2h13.5c-.2-3.5-.3-9.6-.3-14.7 0-8.1 3.3-10.5 10.8-10.5 3.5 0 6 .5 8.2 1.2 0-3 .6-9 1-11.6-2.3-.6-4.7-1-7.7-1-6.5-.1-11.2 2.5-13.4 8.8h-.4Zm59 9.5c0 6.5-4.7 9.6-12.1 9.6-7.4 0-12.1-2.9-12.1-9.6 0-6.7 4.8-9.2 12-9.2 7.4 0 12.2 2.7 12.2 9.2Zm12.3-.3c0-13-10.1-18.8-24.4-18.8-14.4 0-24.2 5.8-24.2 18.8s9.1 20 24.1 20c15.1 0 24.5-7 24.5-19.9Z"
		>
		</path>
	</svg>
	<slot />
</article>

<style>
	article {
		max-width: 40rem;
		margin-inline: auto;
		padding-block: 5rem;
		flex-direction: column;
		align-items: center;
		text-align: center;
		gap: 0.5rem;
	}
	article > :global(*) {
		max-width: 50ch;
		margin-top: 0 !important;
	}
	small {
		color: var(--sl-color-gray-3);
	}
	svg {
		width: 15rem;
	}
</style>


================================================
FILE: docs/src/components/component-preview.astro
================================================
---
import { Tabs, TabItem } from '@astrojs/starlight/components';

const showContentTypeTabs = Astro.slots.has('markdoc');
---

<figure>
	{
		showContentTypeTabs ? (
			<Tabs syncKey="content-type">
				<TabItem label="MDX">
					<slot />
				</TabItem>
				<TabItem label="Markdoc">
					<slot name="markdoc" />
				</TabItem>
			</Tabs>
		) : (
			<slot />
		)
	}
	<div class="preview">
		<figcaption>{Astro.locals.t('component.preview')}</figcaption>
		<div class="preview-content"><slot name="preview" /></div>
	</div>
</figure>

<style>
	:global(.sl-markdown-content) .preview {
		border: 1px solid var(--sl-color-gray-5);
		border-top: none;
		margin-top: 0;
	}

	.preview:only-child {
		border-top: 1px solid var(--sl-color-gray-5);
	}

	figcaption {
		font-size: var(--sl-text-sm);
		font-weight: 600;
		padding: 0.5rem 1rem 0;
	}

	:global(.sl-markdown-content) .preview-content {
		margin-top: 0;
		padding: 1rem;
	}
</style>


================================================
FILE: docs/src/components/fluid-grid.astro
================================================
---
interface Props {
	minColumnWidth?: string;
	gap?: string;
}
const { minColumnWidth, gap } = Astro.props;
---

<ul class="fluid-grid"><slot /></ul>

<style define:vars={{ minColumnWidth, gap }}>
	.fluid-grid {
		display: grid;
		grid-template-columns: repeat(auto-fit, minmax(min(100%, var(--minColumnWidth, 11rem)), 1fr));
		gap: var(--gap, 1rem);
		list-style: none;
		padding: 0;
	}
	.fluid-grid > :global(*) {
		margin-top: 0 !important;
	}
</style>


================================================
FILE: docs/src/components/icons-list.astro
================================================
---
import { Icon } from '@astrojs/starlight/components';
import { Icons, type StarlightIcon } from '../../../packages/starlight/components-internals/Icons';

interface Props {
	labels?: {
		copied?: string;
	};
}

const { copied = 'Copied!' } = Astro.props.labels ?? {};

const icons = Object.keys(Icons) as StarlightIcon[];
---

<div class="icons-grid" data-label-copied={copied}>
	{
		icons.map((icon) => {
			return (
				<button class="icon-preview" aria-label={`Copy ${icon} icon to clipboard`} data-name={icon}>
					<Icon name={icon} size="1.5rem" />
					<span aria-live="polite">{icon}</span>
				</button>
			);
		})
	}
</div>

<script>
	const iconGrid = document.querySelector<HTMLDivElement>('.icons-grid');
	const copiedLabel = document.querySelector<HTMLDivElement>('.icons-grid')?.dataset.labelCopied!;
	iconGrid?.addEventListener('click', (event) => {
		if (!(event.target instanceof Element)) return;
		const icon = event.target.closest('.icon-preview');
		if (!(icon instanceof HTMLButtonElement)) return;
		const iconName = icon.dataset.name!;
		navigator.clipboard.writeText(iconName);

		const iconLabel = icon.querySelector('[aria-live]');
		if (iconLabel) {
			iconLabel.textContent = copiedLabel;
			setTimeout(() => {
				iconLabel.textContent = iconName;
			}, 1000);
		}
	});
</script>

<style>
	.icons-grid {
		display: grid;
		gap: 1rem;
		grid-template-columns: repeat(auto-fit, minmax(8rem, 1fr));
	}

	.icons-grid .icon-preview {
		align-items: center;
		justify-content: center;
		text-align: center;
		border: 1px solid var(--sl-color-gray-5);
		display: flex;
		flex-direction: column;
		font-size: var(--sl-text-sm);
		gap: 0.25rem;
		margin: 0;
		overflow-wrap: anywhere;
		padding: 0.75rem;
		background: none;
	}

	.icon-preview:hover,
	.icon-preview:focus {
		cursor: pointer;
		border: 1px solid var(--sl-color-gray-3);
		background: var(--sl-color-gray-7, var(--sl-color-gray-6));
	}
</style>


================================================
FILE: docs/src/components/languages-list.astro
================================================
---
import { getEntry } from 'astro:content';
import translations from '../../../packages/starlight/translations';

interface Props {
	startsSentence?: boolean;
}

// The current page's slug.
const slug = Astro.url.pathname.replace(/^\//, '').replace(/\/$/, '');
// The docs entry for the current page, or `undefined` if the page is using fallback content.
const entry = await getEntry('docs', slug);
// The BCP-47 tag for the current page or fallback content's language.
const pageLang = entry && Astro.currentLocale ? Astro.currentLocale : 'en';
// The BCP-47 tags for all supported languages in Starlight.
const supportedLangs = Object.keys(translations);
// An i18n helper that returns the language name for a given BCP-47 tag configured for the current page's language.
const langNames = new Intl.DisplayNames([pageLang], { type: 'language' });

// A list of the language names for all supported languages sorted alphabetically.
const supportedLangNames = supportedLangs
	.map((supportedLang) => {
		const langName = langNames.of(supportedLang);
		if (!langName) throw new Error(`Failed to get the language name for '${supportedLang}'.`);
		return langName;
	})
	.sort((a, b) => a.localeCompare(b, pageLang));

// The list of language names for all supported languages formatted according to the current page's language.
const langList = new Intl.ListFormat(pageLang, {
	style: 'long',
	type: 'conjunction',
}).format(supportedLangNames);
---

{
	Astro.props.startsSentence
		? langList[0]?.toLocaleUpperCase(pageLang) + langList.slice(1)
		: langList
}


================================================
FILE: docs/src/components/media-card.astro
================================================
---
interface Props {
	href?: string | undefined;
}
const { href } = Astro.props;
const El = href ? 'a' : 'span';
---

<li class="not-content sl-flex">
	<El class="media-card sl-flex" {href}>
		<div class="media"><slot name="media" /></div>
		<slot />
	</El>
</li>

<style>
	.media-card {
		flex-direction: column;
		border: 1px solid var(--sl-color-gray-5);
		border-radius: 0.5rem;
		overflow: hidden;
		text-decoration: none;
		box-shadow: var(--sl-shadow-sm);
		width: 100%;
	}
	a:hover {
		border-color: var(--sl-color-gray-2);
		background-color: var(--sl-color-gray-7, var(--sl-color-gray-6));
	}

	.media {
		border-bottom: 1px solid var(--sl-color-gray-5);
	}

	.media :global(img) {
		display: block;
		width: 100%;
		height: auto;
		aspect-ratio: 16 / 9;
		object-fit: cover;
	}

	.media-card :global(.title) {
		color: var(--sl-color-white);
		font-weight: 600;
		line-height: var(--sl-line-height-headings);
	}
</style>


================================================
FILE: docs/src/components/showcase-card.astro
================================================
---
import type { ImageMetadata } from 'astro';
import { Image } from 'astro:assets';
import MediaCard from './media-card.astro';
import { AstroError } from 'astro/errors';

interface Props {
	href: string;
	title: string;
	thumbnail: string;
}
const { href, title } = Astro.props;

const thumbnails = import.meta.glob<{ default: ImageMetadata }>(
	'../assets/showcase/*{.png,.jpg,.jpeg,.webp,.avif}'
);
const thumbnail = thumbnails[`../assets/showcase/${Astro.props.thumbnail}`];
if (!thumbnail) {
	throw new Error(`Could not resolve showcase thumbnail: ${Astro.props.thumbnail}`);
}
const src = (await thumbnail()).default;

if (src.width !== 800 || src.height !== 450) {
	let fileName = src.src.split('/').pop();
	const queryIndex = fileName?.indexOf('?');
	if (queryIndex !== undefined && queryIndex > -1) {
		fileName = fileName?.slice(0, queryIndex);
	}
	throw new AstroError(
		'Showcase images must be **800×450px**',
		`Dimensions of **${src.width}×${src.height}px** found for showcase image \`${fileName || src.src}\`\n\n` +
			`For best results:\n\n` +
			`1. Take a screenshot of the site using a browser resized to **1280×720px**. The responsive view in dev tools can be helpful for this.\n\n` +
			`2. Resize the screenshot to **800×450px** and make sure it is saved as a PNG. An online tool like [Squoosh](https://squoosh.app/) can help here.\n\n` +
			`See more details in the [Starlight contributing guide](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md#showcase)\n`
	);
}
---

<MediaCard {href}>
	<Image slot="media" {src} alt="" width="560" />
	<p class="title">{title}</p>
</MediaCard>

<style>
	.title {
		padding: 0.75rem 1rem;
	}
</style>


================================================
FILE: docs/src/components/showcase-sites.astro
================================================
---
import Card from './showcase-card.astro';
import FluidGrid from './fluid-grid.astro';
---

<FluidGrid>
	<Card title="Athena OS" href="https://athenaos.org" thumbnail="www.athenaos.org.png" />
	<Card title="pls" href="https://pls.cli.rs/" thumbnail="pls.cli.rs.png" />
	<Card title="capo.js" href="https://rviscomi.github.io/capo.js/" thumbnail="capo.js.png" />
	<Card
		title="Web Monetization API"
		href="https://webmonetization.org/docs/"
		thumbnail="webmonetization.org.png"
	/>
	<Card
		title="QBCore Docs"
		href="https://brycerussell.github.io/qbcore-docs/"
		thumbnail="brycerussell.github.io-qbcore-docs.png"
	/>
	<Card title="har.fyi" href="https://har.fyi/" thumbnail="har.fyi.png" />
	<Card title="xs-dev docs" href="https://xs-dev.js.org" thumbnail="xs-dev.js.org.png" />
	<Card title="Felicity" href="https://felicity.pages.dev/" thumbnail="felicity.pages.dev.png" />
	<Card
		title="NgxEditor"
		href="https://sibiraj-s.github.io/ngx-editor/"
		thumbnail="sibiraj-s.github.io-ngx-editor.png"
	/>
	<Card title="Terrateam Docs" href="https://terrateam.io/docs" thumbnail="terrateam.io-docs.png" />
	<Card
		title="Obytes Starter"
		href="https://starter.obytes.com"
		thumbnail="starter.obytes.com.jpg"
	/>
	<Card
		title="Kanri"
		href="https://www.kanriapp.com/getting-started/what-is-kanri/"
		thumbnail="kanriapp.com.png"
	/>
	<Card title="Refact" href="https://docs.refact.ai/" thumbnail="refact.ai.png" />
	<Card
		title="Some drops of PHP Book"
		href="https://drops-of-php.hi-folks.dev/"
		thumbnail="drops-of-php.hi-folks.dev.png"
	/>
	<Card title="Nostalgist.js" href="https://nostalgist.js.org/" thumbnail="nostalgist.js.org.png" />
	<Card
		title="AI Prompt Snippets"
		href="https://ai-prompt-snippets.vercel.app/"
		thumbnail="ai-prompt-snippets.png"
	/>
	<Card
		title="Folks Router"
		href="https://folksrouter.io/docs/introduction"
		thumbnail="folksrouter.io.png"
	/>
	<Card
		title="React Awesome Reveal"
		href="https://react-awesome-reveal.morello.dev/"
		thumbnail="react-awesome-reveal.morello.dev.png"
	/>
	<Card
		title="Ethereum Follow Protocol"
		href="https://docs.ethfollow.xyz/"
		thumbnail="docs.ethfollow.xyz.png"
	/>
	<Card title="Knip" href="https://knip.dev" thumbnail="knip.dev.png" />
	<Card title="secco" href="https://secco.lekoarts.de" thumbnail="secco.lekoarts.de.png" />
	<Card
		title="SiteOne Crawler"
		href="https://crawler.siteone.io/?utm_source=starlight-docs"
		thumbnail="crawler.siteone.io.png"
	/>
	<Card title="Mr. Robøt" href="https://docs.mrrobot.app" thumbnail="docs.mrrobot.app.png" />
	<Card title="Open SaaS Docs" href="https://docs.opensaas.sh/" thumbnail="opensaas.sh.png" />
	<Card
		title="Astro Snipcart"
		href="https://astro-snipcart.vercel.app/"
		thumbnail="astro-snipcart.png"
	/>
	<Card title="oneRepo" href="https://onerepo.tools" thumbnail="onerepo.tools.png" />
	<Card title="Flojoy" href="https://docs.flojoy.ai" thumbnail="docs.flojoy.ai.png" />
	<Card title="AstroNvim" href="https://docs.astronvim.com" thumbnail="docs.astronvim.com.png" />
	<Card
		title="ScreenshotOne Docs"
		href="https://screenshotone.com/docs/"
		thumbnail="screenshotone.com.png"
	/>
	<Card title="DipSway" href="https://api.dipsway.com" thumbnail="api.dipsway.com.png" />
	<Card title="RunsOn" href="https://runs-on.com" thumbnail="runs-on.com.png" />
	<Card title="SST Ion" href="https://ion.sst.dev/" thumbnail="ion.sst.dev.png" />
	<Card
		title="Font Awesome"
		href="https://docs.fontawesome.com/"
		thumbnail="docs.fontawesome.com.png"
	/>
	<Card title="TrueCharts" href="https://truecharts.org/" thumbnail="truecharts.org.png" />
	<Card title="Kinde" href="https://docs.kinde.com/" thumbnail="kinde.com.png" />
	<Card title="DMNO" href="https://dmno.dev" thumbnail="dmno.dev.png" />
	<Card title="EspansoEdit" href="https://ee.qqv.com.au" thumbnail="ee.qqv.com.au.png" />
	<Card title="TutorialKit" href="https://tutorialkit.dev/" thumbnail="tutorialkit.dev.png" />
	<Card
		title="The Dev Health OS"
		href="https://www.devhealthos.com/"
		thumbnail="www.devhealthos.com.png"
	/>
	<Card
		title="FeedbackSpark"
		href="https://feedbackspark.com/docs/"
		thumbnail="feedbackspark.com.png"
	/>
	<Card
		title="QuotesDomain"
		href="https://www.quotesdomain.com/"
		thumbnail="quotesdomain.com.png"
	/>
	<Card title="Saasfly" href="https://document.saasfly.io/" thumbnail="document.saasfly.io.png" />
	<Card
		title="freeCodeCamp"
		href="https://contribute.freecodecamp.org/intro/"
		thumbnail="contribute.freecodecamp.org.png"
	/>
	<Card
		title="Style Dictionary"
		href="https://styledictionary.com/"
		thumbnail="styledictionary.com.png"
	/>
	<Card title="CodeSweetly" href="https://codesweetly.com/" thumbnail="codesweetly.com.png" />
	<Card title="grpcmd" href="https://grpc.md/docs/" thumbnail="grpc.md.png" />
	<Card
		title="Pokemon Database"
		href="https://pokemon-siace.netlify.app/"
		thumbnail="pokemon-siace.netlify.app.png"
	/>
	<Card
		title="Cloudflare Docs"
		href="https://developers.cloudflare.com/"
		thumbnail="developers.cloudflare.com.png"
	/>
	<Card title="Open {re}Source" href="https://openresource.dev" thumbnail="openresource.dev.png" />
	<Card
		title="Orbit CSS"
		href="https://zumerlab.github.io/orbit-docs/"
		thumbnail="zumerlab.github.io.orbit-docs.png"
	/>
	<Card
		title="LaunchFast"
		href="https://www.launchfa.st/documentation"
		thumbnail="launchfa.st.png"
	/>
	<Card title="Capgo" href="https://capgo.app/docs" thumbnail="capgo.app.png" />
	<Card
		title="React Bricks"
		href="https://docs.reactbricks.com"
		thumbnail="docs.reactbricks.com.png"
	/>
	<Card title="emoji-blast" href="https://emojiblast.dev" thumbnail="docs.emojiblast.dev.png" />
	<Card
		title="Text To Table Converter"
		href="https://texttotableconverter.com"
		thumbnail="texttotableconverter.com.png"
	/>
	<Card
		title="Isomorphic Validation"
		href="https://itihon.github.io/isomorphic-validation/"
		thumbnail="itihon.github.io-isomorphic-validation.png"
	/>
	<Card
		title="Accessible Astro"
		href="https://accessible-astro.incluud.dev"
		thumbnail="accessible-astro.incluud.dev.png"
	/>
	<Card title="Learn AISO" href="https://learnaiso.com" thumbnail="learnaiso.com.png" />
	<Card title="PaperMC Docs" href="https://docs.papermc.io" thumbnail="docs.papermc.io.png" />
	<Card title="Bingo" href="https://create.bingo" thumbnail="create.bingo.png" />
	<Card title="OctoGuide" href="https://octo.guide" thumbnail="octo.guide.png" />
	<Card
		title="Sonar"
		href="https://sonar-team.github.io/doc/"
		thumbnail="sonar-team.github.io.png"
	/>
	<Card title="Cookie API" href="https://docs.cookie-api.com" thumbnail="docs.cookie-api.com.png" />
	<Card title="Fluid DnD" href="https://fluid-dnd.netlify.app/" thumbnail="fluid-dnd.png" />
	<Card title="PyDocs" href="https://www.pydocs.site/en" thumbnail="www.pydocs.site.png" />
	<Card title="Fomr" href="https://fomr.io/help" thumbnail="fomr.io.png" />
	<Card
		title="The Jotter | Bag of Tricks"
		href="https://events-3bg.pages.dev/jotter"
		thumbnail="events-3bg.pages.dev.png"
	/>
	<Card title="@vtbag" href="https://vtbag.dev" thumbnail="vtbag.dev.png" />
	<Card title="vlt docs" href="https://docs.vlt.sh/" thumbnail="docs.vlt.sh.png" />
	<Card
		title="sharp"
		href="https://sharp.pixelplumbing.com/"
		thumbnail="sharp.pixelplumbing.com.png"
	/>
	<Card title="Netlify Docs" href="https://docs.netlify.com" thumbnail="docs.netlify.com.png" />
	<Card
		title="Open AI Agents SDK"
		href="https://openai.github.io/openai-agents-js/"
		thumbnail="openai.github.io.png"
	/>
	<Card title="opencode" href="https://opencode.ai/docs" thumbnail="opencode.ai.png" />
	<Card title="Scalekit Docs" href="https://docs.scalekit.com/" thumbnail="docs.scalekit.com.png" />
	<Card title="Aptos Docs" href="https://aptos.dev" thumbnail="aptos.dev.png" />
	<Card title="OmniPrint Docs" href="https://omni-byte.com/docs/" thumbnail="omni-byte.com.png" />
	<Card title="Academeez" href="https://www.academeez.com/" thumbnail="academeez.com.png" />
	<Card title="openstatus Docs" href="https://docs.openstatus.dev" thumbnail="openstatus.dev.png" />
	<Card title="Saucer" href="https://saucer.app" thumbnail="saucer.app.png" />
	<Card title="lychee" href="https://lychee.cli.rs/" thumbnail="lychee.cli.rs.png" />
	<Card title="Biome" href="https://biomejs.dev/" thumbnail="biomejs.dev.png" />
	<Card title="aspire.dev" href="https://aspire.dev/" thumbnail="aspire.dev.png" />
	<Card title="bettercap" href="https://www.bettercap.org/" thumbnail="bettercap.org.png" />
	<Card title="modestbench" href="https://modestbench.dev/" thumbnail="modestbench.dev.png" />
	<Card title="LavaMoat" href="https://lavamoat.github.io/" thumbnail="lavamoat.github.io.png" />
	<Card title="STACKIT Docs" href="https://docs.stackit.cloud" thumbnail="docs.stackit.cloud.png" />
	<Card title="CatchIntent" href="https://catchintent.com/docs" thumbnail="catchintent.com.png" />
	<Card title="Actionbase" href="https://actionbase.io/" thumbnail="actionbase.io.png" />
	<Card title="Formware Help Center" href="https://formware.io/help/" thumbnail="formware.io.png" />
</FluidGrid>


================================================
FILE: docs/src/components/sidebar-preview.astro
================================================
---
import type {
	AutoSidebarGroup,
	SidebarItem,
	InternalSidebarLinkItem,
} from '../../../packages/starlight/schemas/sidebar';
import SidebarSublist from '../../../packages/starlight/components/SidebarSublist.astro';
import type { Badge } from '../../../packages/starlight/schemas/badge';
import type { SidebarEntry } from '../../../packages/starlight/utils/routing/types';

interface Props {
	config: SidebarConfig;
}

type SidebarConfig = (Exclude<SidebarItem, AutoSidebarGroup | InternalSidebarLinkItem> & {
	badge?: Badge;
})[];

const { config } = Astro.props;

function makeEntries(items: SidebarConfig): SidebarEntry[] {
	return items.map((item) => {
		if ('link' in item) {
			return {
				type: 'link',
				label: item.label,
				// Empty hrefs are used to represent internal links that do not exist in the Starlight
				// docs. Using a non-existing anchor link like `#_` will not trigger a page reload or any
				// scrolling.
				href: item.link.length > 0 ? item.link : '#_',
				isCurrent: false,
				badge: item.badge,
				attrs: item.attrs ?? {},
			};
		}

		return {
			type: 'group',
			label: item.label,
			entries: makeEntries(item.items as SidebarConfig),
			collapsed: item.collapsed,
			badge: item.badge,
		};
	});
}
---

<div class="sidebar-preview not-content">
	<SidebarSublist sublist={makeEntries(config)} />
</div>

<style>
	.sidebar-preview {
		background-color: var(--sl-color-bg-sidebar);
		border: 1px solid var(--sl-color-gray-5);
		padding: 1rem var(--sl-sidebar-pad-x);
		/* Matches `var(--sl-sidebar-width)`, but hardcoded to avoid being overridden when printing the page. */
		max-width: 18.75rem;
	}
</style>


================================================
FILE: docs/src/components/social-links-type.astro
================================================
---
import { getRelativeLocaleUrl } from 'astro:i18n';
const href = getRelativeLocaleUrl(Astro.currentLocale ?? 'en', '/reference/icons/');
---

<code>
	<Fragment set:text="Array<{" />
	label: string; icon: <a {href}>StarlightIcon</a>; href: string
	<Fragment set:text="}>" />
</code>


================================================
FILE: docs/src/components/testimonial-grid.astro
================================================
---
interface Props {
	title: string;
}

const { title } = Astro.props;
---

<div class="testimonial-wrapper not-content" data-pagefind-ignore>
	<h2 class="testimonial-grid-title">{title}</h2>
	<ul class="testimonial-grid">
		<slot />
	</ul>
</div>

<style>
	.testimonial-wrapper {
		margin-block: 7rem 2.5rem !important;
		font-size: clamp(var(--sl-text-sm), calc(0.5rem + 1vw), var(--sl-text-body));
	}
	.testimonial-grid-title {
		text-align: center;
		font-size: var(--sl-text-h3);
		font-weight: 600;
		color: var(--sl-color-white);
		line-height: var(--sl-line-height-headings);
	}
	.testimonial-grid {
		margin-top: 2.5rem;
		display: grid;
		gap: 5em;
		padding-inline-start: 0;
	}
	@media (min-width: 50rem) {
		.testimonial-grid {
			grid-template-columns: 1fr 1fr;
		}
	}
</style>


================================================
FILE: docs/src/components/testimonial.astro
================================================
---
import type { ImageMetadata } from 'astro';
import { Image } from 'astro:assets';

interface Props {
	handle: string;
	name: string;
	cite: string;
}

const { name, handle, cite } = Astro.props;

const avatars = import.meta.glob<{ default: ImageMetadata }>('../assets/testimonials/*.jpg');
const avatar = avatars[`../assets/testimonials/${handle}.jpg`];
if (!avatar) {
	throw new Error(`Could not resolve testimonial avatar for @${handle}`);
}
const src = (await avatar()).default;
---

<li class="testimonial">
	<blockquote class="quote" cite={cite}>
		<slot />
	</blockquote>
	<div class="footer">
		<Image class="avatar" height="96" width="96" {src} alt="" />
		<div>
			<p class="name">{name}</p>
			<a href={cite} class="handle">@{handle}</a>
		</div>
	</div>
</li>

<style>
	.testimonial {
		display: flex;
		flex-direction: column;
		gap: 1.5em;
	}
	@media (min-width: 50rem) {
		.testimonial {
			gap: 2em;
		}
	}
	.quote {
		position: relative;
		padding-inline-start: 1.5em;
	}
	.quote::before {
		position: absolute;
		content: '';
		inset-block: 0.5em;
		inset-inline-start: 0;
		border-inline-start: 1px solid var(--sl-color-text-accent);
	}
	.quote > :global(* + *) {
		margin-top: 0.75em;
	}

	.footer {
		display: flex;
		gap: 1rem;
		align-items: center;
	}
	.avatar {
		--outline-color: rgba(255, 255, 255, 0.33);
		outline: 1px solid var(--outline-color);
		outline-offset: -1px;
		border-radius: 99rem;
		width: 4em;
		height: 4em;
	}
	:global([data-theme='light']) .avatar {
		--outline-color: rgba(23, 25, 30, 0.33);
	}

	.name {
		font-weight: 600;
		font-size: var(--sl-text-h4);
		color: var(--sl-color-white);
		line-height: var(--sl-line-height-headings);
	}
	.handle {
		text-underline-offset: 4px;
		color: var(--sl-color-text-accent);
	}
	.handle:hover {
		color: var(--sl-color-white);
	}
</style>


================================================
FILE: docs/src/components/theme-designer/atom.ts
================================================
class Atom<T> {
	#v: T;
	#subscribers = new Map<(v: T) => void, (v: T) => void>();
	#notify = () => this.#subscribers.forEach((cb) => cb(this.#v));
	constructor(init: T) {
		this.#v = init;
	}
	get(): T {
		return this.#v;
	}
	set(v: T): void {
		this.#v = v;
		this.#notify();
	}
	subscribe(cb: (v: T) => void): () => boolean {
		cb(this.#v);
		this.#subscribers.set(cb, cb);
		return () => this.#subscribers.delete(cb);
	}
}

type MapStore<T> = Atom<T> & { setKey: (key: keyof T, value: T[typeof key]) => void };

export function map<T extends Record<string, unknown>>(value: T): MapStore<T> {
	const atom = new Atom(value) as MapStore<T>;
	atom.setKey = (key: keyof T, value: T[typeof key]) => {
		const curr = atom.get();
		if (curr[key] !== value) atom.set({ ...curr, [key]: value });
	};
	return atom;
}

export function atom<T>(value: T): Atom<T> {
	return new Atom(value);
}


================================================
FILE: docs/src/components/theme-designer/color-editor.astro
================================================
---
import { oklchToHex } from './color-lib';
import { store } from './store';
import ValueSlider from './value-slider.astro';

export interface Props {
	key: keyof typeof store;
	legend: string;
	labels: Record<'pickColor' | 'hue' | 'chroma', string>;
}
const { key, legend, labels } = Astro.props;
const { hue, chroma } = store[key].get();
const initialColor = oklchToHex(52, chroma, hue);
---

<color-editor data-key={key}>
	<fieldset>
		<legend>{legend}</legend>
		<label class="color-picker">
			<span class="sr-only">{labels.pickColor}</span>
			<input type="color" value={initialColor} />
		</label>
		<div class="sliders">
			<ValueSlider label={labels.hue} storeKey={key} type="hue" />
			<ValueSlider label={labels.chroma} storeKey={key} type="chroma" />
		</div>
	</fieldset>
</color-editor>

<script>
	import { oklch, oklchToHex } from './color-lib';
	import { store } from './store';

	export class ColorEditor extends HTMLElement {
		#store = store[this.dataset.key as keyof typeof store];
		#colorInput = this.querySelector<HTMLInputElement>('input[type="color"]')!;

		constructor() {
			super();
			// Update color on user input.
			this.#store.subscribe(({ chroma, hue }) => {
				this.#colorInput.value = oklchToHex(52, chroma, hue);
			});
			this.#colorInput.addEventListener('input', (e) => {
				if (!(e.target instanceof HTMLInputElement)) return;
				const old = this.#store.get();
				const { c, h } = { ...oklch(e.target.value) };
				this.#store.set({ hue: h ?? old.hue, chroma: c ?? old.chroma });
			});
		}
	}
	customElements.define('color-editor', ColorEditor);
</script>

<style>
	fieldset {
		border: 1px solid var(--sl-color-gray-5);
		background-color: var(--sl-color-gray-7, var(--sl-color-gray-6));
		padding: 1rem;
		color: var(--sl-color-white);
	}
	legend {
		float: left;
		float: inline-start;
		font-weight: 600;
	}
	.color-picker {
		float: right;
		float: inline-end;
	}
	.sliders {
		clear: both;
	}
	input[type='color'] {
		border: 0;
		background: transparent;
		height: 2em;
		width: 3rem;
		cursor: pointer;
		--swatch-border: var(--sl-color-gray-3);
	}
	input[type='color']:hover {
		--swatch-border: var(--sl-color-gray-1);
	}
	input[type='color']::-webkit-color-swatch {
		border: 1px solid var(--swatch-border);
		border-radius: 0.5rem;
	}
	input[type='color']::-moz-color-swatch {
		border: 1px solid var(--swatch-border);
		border-radius: 0.5rem;
	}
</style>


================================================
FILE: docs/src/components/theme-designer/color-lib.ts
================================================
import {
	clampChroma,
	formatHex,
	modeLrgb,
	modeOklch,
	modeRgb,
	useMode,
	wcagContrast,
	type Oklch,
} from 'culori/fn';

const rgb = useMode(modeRgb);
export const oklch = useMode(modeOklch);
// We need to initialise LRGB support for culori’s `wcagContrast()` method.
useMode(modeLrgb);

/** Convert a culori OKLCH color object to an RGB hex code. */
const oklchColorToHex = (okLchColor: Oklch) => {
	const rgbColor = rgb(clampChroma(okLchColor, 'oklch'));
	return formatHex(rgbColor);
};
/** Construct a culori OKLCH color object from LCH parameters. */
const oklchColorFromParts = (l: number, c: number, h: number) => oklch(`oklch(${l}% ${c} ${h})`)!;
/** Convert OKLCH parameters to an RGB hex code. */
export const oklchToHex = (l: number, c: number, h: number) =>
	oklchColorToHex(oklchColorFromParts(l, c, h));

/**
 * Ensure a text colour passes a contrast threshold against a specific background colour.
 * If necessary, colours will be darkened/lightened to increase contrast until the threshold is passed.
 *
 * @param text The text colour to adjust if necessary.
 * @param bg The background colour to test contrast against.
 * @param threshold The minimum contrast ratio required. Defaults to `4.5` to meet WCAG AA standards.
 * @returns The adjusted text colour as a culori OKLCH color object.
 */
const contrastColor = (text: Oklch, bg: Oklch, threshold = 4.5): Oklch => {
	/** Clone of the input foreground colour to mutate. */
	const fgColor = { ...text };
	// Brighten text in dark mode, darken text in light mode.
	const increment = fgColor.l > bg.l ? 0.005 : -0.005;
	while (wcagContrast(fgColor, bg) < threshold && fgColor.l < 100 && fgColor.l > 0) {
		fgColor.l += increment;
	}
	return fgColor;
};

/** Generate dark and light palettes based on user-selected hue and chroma values. */
export function getPalettes(config: {
	accent: { hue: number; chroma: number };
	gray: { hue: number; chroma: number };
	minimumContrast?: number;
}) {
	const {
		accent: { hue: ah, chroma: ac },
		gray: { hue: gh, chroma: gc },
		minimumContrast: mc,
	} = config;

	const palettes = {
		dark: {
			// Accents
			'accent-low': oklchColorFromParts(25.94, ac / 3, ah),
			accent: oklchColorFromParts(52.28, ac, ah),
			'accent-high': oklchColorFromParts(83.38, ac / 3, ah),
			// Grays
			white: oklchColorFromParts(100, 0, 0),
			'gray-1': oklchColorFromParts(94.77, gc / 2.5, gh),
			'gray-2': oklchColorFromParts(81.34, gc / 2, gh),
			'gray-3': oklchColorFromParts(63.78, gc, gh),
			'gray-4': oklchColorFromParts(46.01, gc, gh),
			'gray-5': oklchColorFromParts(34.09, gc, gh),
			'gray-6': oklchColorFromParts(27.14, gc, gh),
			black: oklchColorFromParts(20.94, gc / 2, gh),
		},
		light: {
			// Accents
			'accent-low': oklchColorFromParts(87.81, ac / 4, ah),
			accent: oklchColorFromParts(52.95, ac, ah),
			'accent-high': oklchColorFromParts(31.77, ac / 2, ah),
			// Grays
			white: oklchColorFromParts(20.94, gc / 2, gh),
			'gray-1': oklchColorFromParts(27.14, gc, gh),
			'gray-2': oklchColorFromParts(34.09, gc, gh),
			'gray-3': oklchColorFromParts(46.01, gc, gh),
			'gray-4': oklchColorFromParts(63.78, gc, gh),
			'gray-5': oklchColorFromParts(81.34, gc / 2, gh),
			'gray-6': oklchColorFromParts(94.77, gc / 2.5, gh),
			'gray-7': oklchColorFromParts(97.35, gc / 5, gh),
			black: oklchColorFromParts(100, 0, 0),
		},
	};

	// Ensure text shades have sufficient contrast against common background colours.

	// Dark mode:
	// `gray-2` is used against `gray-5` in inline code snippets.
	palettes.dark['gray-2'] = contrastColor(palettes.dark['gray-2'], palettes.dark['gray-5'], mc);
	// `gray-3` is used in the table of contents.
	palettes.dark['gray-3'] = contrastColor(palettes.dark['gray-3'], palettes.dark.black, mc);

	// Light mode:
	// `accent` is used for links and link buttons and can be slightly under 7:1 for some hues.
	palettes.light.accent = contrastColor(palettes.light.accent, palettes.light['gray-6'], mc);
	// `gray-2` is used against `gray-6` in inline code snippets.
	palettes.light['gray-2'] = contrastColor(palettes.light['gray-2'], palettes.light['gray-6'], mc);
	// `gray-3` is used in the table of contents.
	palettes.light['gray-3'] = contrastColor(palettes.light['gray-3'], palettes.light.black, mc);

	// Convert the palette from OKLCH to RGB hex codes.
	return {
		dark: Object.fromEntries(
			Object.entries(palettes.dark).map(([key, color]) => [key, oklchColorToHex(color)])
		) as Record<keyof typeof palettes.dark, string>,
		light: Object.fromEntries(
			Object.entries(palettes.light).map(([key, color]) => [key, oklchColorToHex(color)])
		) as Record<keyof typeof palettes.light, string>,
	};
}

/*
This is the default Starlight color palette in OKLCH.
Used as a reference when designing the algorithm for mapping
user hue and chroma pairs to a similar palette.

Dark mode:
  accent lo   oklch(25.94% 0.09 273.5)
  accent      oklch(52.28% 0.266 268.7)
  accent hi   oklch(83.38% 0.084 279.5)

  white       oklch(100% 0 0)
  gray-1      oklch(94.77% 0.008 278.19)
  gray-2      oklch(81.34% 0.011 274.87)
  gray-3      oklch(63.78% 0.019 265.84)
  gray-4      oklch(46.01% 0.021 270.93)
  gray-5      oklch(34.09% 0.017 267.07)
  gray-6      oklch(27.14% 0.015 267.03)
  black       oklch(20.94% 0.01 268.4)
  
Light mode:
  accent lo   oklch(87.81% 0.056 280.2)
  accent      oklch(52.95% 0.243 270.2)
  accent hi   oklch(31.77% 0.177 267.2)
  
  white       oklch(20.94% 0.01 268.4)
  gray-1      oklch(27.14% 0.015 267.03)
  gray-2      oklch(34.09% 0.017 267.07)
  gray-3      oklch(46.01% 0.021 270.93)
  gray-4      oklch(63.78% 0.019 265.84)
  gray-5      oklch(81.34% 0.011 274.87)
  gray-6      oklch(94.77% 0.008 278.19)
  gray-7      oklch(97.35% 0.004 286.32)
  black       oklch(100% 0 0)
*/


================================================
FILE: docs/src/components/theme-designer/contrast-level.astro
================================================
---
export interface Props {
	labels: {
		label: string;
	};
}
const { labels = { label: 'WCAG Contrast Level' } } = Astro.props;
---

<contrast-level-toggle class="sl-flex">
	<fieldset class="not-content">
		<legend>{labels.label}</legend>
		<div class="sl-flex">
			<label class="sl-flex">
				<input type="radio" name="contrast-level" value="4.5" checked />
				AA
			</label>
			<label class="sl-flex">
				<input type="radio" name="contrast-level" value="7" />
				AAA
			</label>
		</div>
	</fieldset>
</contrast-level-toggle>

<script>
	import { minimumContrast } from './store';

	class ContrastLevelToggle extends HTMLElement {
		#fieldset = this.querySelector('fieldset')!;
		constructor() {
			super();
			this.#fieldset.addEventListener('input', (e) => {
				if (e.target instanceof HTMLInputElement) {
					const contrast = parseFloat(e.target.value);
					minimumContrast.set(contrast);
				}
			});
		}
	}

	customElements.define('contrast-level-toggle', ContrastLevelToggle);
</script>

<style>
	fieldset {
		border: 0;
		padding: 0;
	}
	fieldset > * {
		float: left;
		float: inline-start;
		vertical-align: middle;
	}
	legend {
		color: var(--sl-color-white);
		margin-inline-end: 0.75rem;
	}
	label {
		align-items: center;
		padding: 0.25rem 0.75rem;
		gap: 0.375rem;
		background-color: var(--sl-color-gray-6);
		font-size: var(--sl-text-xs);
		cursor: pointer;
	}
	label:has(:focus-visible) {
		outline: 2px solid;
		outline-offset: -4px;
	}
	label:first-child {
		border-start-start-radius: 99rem;
		border-end-start-radius: 99rem;
	}
	label:last-child {
		border-start-end-radius: 99rem;
		border-end-end-radius: 99rem;
	}
	label:has(:checked) {
		color: var(--sl-color-black);
		background-color: var(--sl-color-text-accent);
	}
	input:focus-visible {
		outline: none;
	}
</style>


================================================
FILE: docs/src/components/theme-designer/palette.astro
================================================
---
interface Props {
	light?: boolean;
}
---

<div class="not-content">
	<div class="palette">
		{
			Astro.props.light ? (
				<div class="circle" style="--bg:var(--sl-color-accent)" />
			) : (
				<div class="circle" style="--bg:var(--sl-color-accent-high)" />
			)
		}
		<div style="--bg:var(--sl-color-black)"></div>
		<div style="--bg:var(--sl-color-white)"></div>
		<div style="--bg:var(--sl-color-gray-1)"></div>
		<div style="--bg:var(--sl-color-gray-2)"></div>
		<div style="--bg:var(--sl-color-gray-3)"></div>
		<div style="--bg:var(--sl-color-gray-4)"></div>
		<div style="--bg:var(--sl-color-gray-5)"></div>
		<div style="--bg:var(--sl-color-gray-6)"></div>
		{Astro.props.light && <div style="--bg:var(--sl-color-gray-7)" />}
	</div>
</div>

<style>
	.palette {
		display: grid;
		grid-template-columns: repeat(10, 1fr);
	}
	.palette > * {
		aspect-ratio: 1;
		background-color: var(--bg);
	}

	.circle {
		border-radius: 50%;
	}
</style>


================================================
FILE: docs/src/components/theme-designer/presets.astro
================================================
---
import { Icon } from '@astrojs/starlight/components';
import { getPalettes } from './color-lib';
import { presets } from './store';

export interface Props {
	labels: Record<keyof typeof presets, string> & {
		label: string;
		random: string;
	};
}
const { labels } = Astro.props;

const resolvedPresets = Object.entries(presets).map(([key, preset]) => {
	const palette = getPalettes(preset);
	const label = labels[key as keyof typeof presets];
	return [key, { ...palette, label }] as const;
});
---

<preset-picker class="sl-flex not-content">
	<span class="label">{labels.label}</span>
	{
		resolvedPresets.map(([key, { label, dark, light }]) => (
			<button
				data-preset={key}
				style={{
					'--dark-bg': dark['accent-high'],
					'--light-bg': light.accent,
					'--dark-text': dark['accent-low'],
					'--light-text': light.black,
				}}
			>
				{label}
			</button>
		))
	}
	<button data-random>{labels.random}<Icon name="random" size="1rem" /></button>
</preset-picker>

<style>
	preset-picker {
		flex-wrap: wrap;
		align-items: center;
		gap: 0.75rem;
	}

	.label {
		color: var(--sl-color-white);
	}

	[data-preset],
	[data-random] {
		border: 0;
		border-radius: 99rem;
		min-width: 4.5rem;
		display: flex;
		gap: 0.25rem;
		align-items: center;
		justify-content: center;
		padding: 0.25rem 0.75rem;
		background-color: var(--dark-bg, var(--sl-color-white));
		color: var(--dark-text, var(--sl-color-black));
		font-size: var(--sl-text-xs);
		cursor: pointer;
	}
	button:focus-visible {
		outline: 2px solid;
		outline-offset: -4px;
	}
	:global([data-theme='light']) [data-preset] {
		background-color: var(--light-bg);
		color: var(--light-text);
	}
	button > :global(*) {
		/* We want all clicks to go to the button, not child elements. */
		pointer-events: none;
	}
</style>

<script>
	import { usePreset, useRandom } from './store';

	class PresetPicker extends HTMLElement {
		constructor() {
			super();
			this.addEventListener('click', (e) => {
				if (e.target instanceof HTMLButtonElement) {
					const name = e.target.dataset.preset;
					if (name) usePreset(name);
					if ('random' in e.target.dataset) useRandom();
				}
			});
		}
	}

	customElements.define('preset-picker', PresetPicker);
</script>


================================================
FILE: docs/src/components/theme-designer/preview.astro
================================================
---
import type { HTMLAttributes } from 'astro/types';
import Palette from './palette.astro';

interface Props extends HTMLAttributes<'div'> {
	labels: {
		lightMode: string;
		darkMode: string;
		bodyText: string;
		linkText: string;
		dimText: string;
		inlineCode: string;
	};
}
const { labels, ...attrs } = Astro.props;
const light = 'data-light' in attrs;
const linkColor = light ? '--sl-color-accent' : '--sl-color-accent-high';
const codeBg = light ? '--sl-color-gray-6' : '--sl-color-gray-5';
---

<div class="preview-card" {...attrs}>
	<h4>{light ? labels.lightMode : labels.darkMode}</h4>
	<p>
		{labels.bodyText}{' '}
		<span class="link" style={`color:var(${linkColor})`}>{labels.linkText}</span>{' '}
		<span class="dim">{labels.dimText}</span>{' '}
		<code style={`--sl-color-bg-inline-code:var(${codeBg})`}>{labels.inlineCode}</code>
	</p>
	<Palette {light} />
</div>

<style>
	.preview-card {
		margin: 0 !important;
		border: 1px solid var(--sl-color-gray-5);
		padding: 1rem;
		background-color: var(--sl-color-black);
	}

	p {
		margin-top: 0.5em !important;
		font-size: var(--sl-text-sm);
		color: var(--sl-color-gray-2);
	}

	.link {
		text-decoration: underline;
	}

	.dim {
		color: var(--sl-color-gray-3);
	}
</style>


================================================
FILE: docs/src/components/theme-designer/store.ts
================================================
import { atom, map } from './atom';

export const presets = {
	ocean: {
		accent: { hue: 240, chroma: 0.27 },
		gray: { hue: 220, chroma: 0.025 },
	},
	forest: {
		accent: { hue: 140, chroma: 0.27 },
		gray: { hue: 140, chroma: 0.03 },
	},
	oxide: {
		accent: { hue: 30, chroma: 0.27 },
		gray: { hue: 30, chroma: 0.02 },
	},
	nebula: {
		accent: { hue: 320, chroma: 0.27 },
		gray: { hue: 305, chroma: 0.07 },
	},
	default: {
		accent: { hue: 269, chroma: 0.27 },
		gray: { hue: 270, chroma: 0.016 },
	},
};

export const store = {
	accent: map(presets.default.accent),
	gray: map(presets.default.gray),
};
export const minimumContrast = atom(4.5);

export const usePreset = (name: string) => {
	if (name in presets) {
		const { accent, gray } = presets[name as keyof typeof presets];
		store.accent.set(accent);
		store.gray.set(gray);
	}
};

const MAX_CHROMA = 0.27;

export const useRandom = () => {
	store.accent.set({ hue: randomHue(), chroma: MAX_CHROMA - randomChroma() });
	store.gray.set({ hue: randomHue(), chroma: randomChroma() });
};

const randomHue = () => Math.round(Math.random() * 360);
const randomChroma = () => Math.pow(Math.random(), 3) * MAX_CHROMA;


================================================
FILE: docs/src/components/theme-designer/value-slider.astro
================================================
---
import { store } from './store';

interface Props {
	label: string;
	storeKey: keyof typeof store;
	type: 'hue' | 'chroma';
}
const { label, storeKey, type } = Astro.props;

const { max, step } = { hue: { max: 360, step: 1 }, chroma: { max: 0.27, step: 0.001 } }[type];
const value = store[storeKey].get()[type];
---

<value-slider data-store={storeKey} data-type={type}>
	<label>
		<span>{label}</span>
		<input type="range" {max} {step} {value} />
		<span class="value">{value}</span>
	</label>
</value-slider>

<script>
	import { store } from './store';

	class ValueSlider extends HTMLElement {
		#input = this.querySelector('input')!;
		#output = this.querySelector<HTMLSpanElement>('.value')!;
		#store = store[this.dataset.store as keyof typeof store];
		#type = this.dataset.type as 'hue' | 'chroma';
		#formatter = new Intl.NumberFormat(document.documentElement.lang || 'en');

		constructor() {
			super();
			this.#input.addEventListener('input', () =>
				this.#store.setKey(this.#type, this.#input.valueAsNumber)
			);
			this.#store.subscribe((v) => {
				const newValue = v[this.#type];
				this.#input.value = String(newValue);
				this.#output.innerText = this.#formatter.format(newValue);
			});
		}
	}
	customElements.define('value-slider', ValueSlider);
</script>

<style>
	label {
		display: grid;
		grid-template-columns: auto 1fr 2.5rem;
		align-items: center;
		gap: 0.75rem;
	}
	input {
		min-width: 5rem;
	}
	.value {
		font-size: var(--sl-text-sm);
		color: var(--sl-color-gray-2);
	}
</style>


================================================
FILE: docs/src/components/theme-designer.astro
================================================
---
import { TabItem, Tabs } from '@astrojs/starlight/components';
import ColorEditor, { type Props as EditorProps } from './theme-designer/color-editor.astro';
import ContrastLevel, {
	type Props as ContrastLevelProps,
} from './theme-designer/contrast-level.astro';
import Presets, { type Props as PresetsProps } from './theme-designer/presets.astro';
import Preview from './theme-designer/preview.astro';

interface Props {
	labels: {
		presets: PresetsProps['labels'];
		contrast: ContrastLevelProps['labels'];
		editor: EditorProps['labels'] & { accentColor: string; grayColor: string };
		preview: Record<
			'darkMode' | 'lightMode' | 'bodyText' | 'linkText' | 'dimText' | 'inlineCode',
			string
		>;
	};
}
const {
	labels: { presets, contrast, editor, preview },
} = Astro.props;
---

<Presets labels={presets} />

<ContrastLevel labels={contrast} />

<div>
	<theme-designer>
		<div class="sl-flex controls not-content">
			<ColorEditor key="accent" legend={editor.accentColor} labels={editor} />
			<ColorEditor key="gray" legend={editor.grayColor} labels={editor} />
		</div>

		<div class="preview" data-accent-preview>
			<Preview labels={preview} data-dark />
			<Preview labels={preview} data-light />
		</div>

		<Tabs>
			<TabItem label="CSS">
				<slot name="css-docs" />
				<pre
					class="generated-code"
					tabindex="0"><code style="background-color: var(--astro-code-color-background);color: var(--sl-color-text)" data-theme-css /></pre>
			</TabItem>
			<TabItem label="Tailwind">
				<slot name="tailwind-docs" />
				<pre
					class="generated-code"
					tabindex="0"><code style="background-color: var(--astro-code-color-background);color: var(--sl-color-text)" data-theme-tailwind /></pre>
			</TabItem>
		</Tabs>
	</theme-designer>
</div>

<script>
	import { getPalettes } from './theme-designer/color-lib';
	import { store, minimumContrast } from './theme-designer/store';

	class ThemeDesigner extends HTMLElement {
		#stylesheet = new CSSStyleSheet();

		constructor() {
			super();
			// Add our stylesheet to the document.
			document.adoptedStyleSheets = [...document.adoptedStyleSheets, this.#stylesheet];
			// Update theme palettes on user input.
			const onInput = () => this.#update();
			store.accent.subscribe(onInput);
			store.gray.subscribe(onInput);
			minimumContrast.subscribe(onInput);
		}

		#update() {
			const palettes = getPalettes({
				accent: store.accent.get(),
				gray: store.gray.get(),
				minimumContrast: minimumContrast.get(),
			});
			this.#updatePreview(palettes);
			this.#updateStylesheet(palettes);
			this.#updateTailwindConfig(palettes);
		}

		/** Apply the generated palettes to the style attributes of the in-content preview panes. */
		#updatePreview({ dark, light }: ReturnType<typeof getPalettes>) {
			const previews = this.querySelectorAll<HTMLDivElement>('[data-accent-preview] > *');
			previews.forEach((preview) => {
				const theme = 'dark' in preview.dataset ? dark : light;
				Object.entries(theme).forEach(([key, color]) => {
					preview.style.setProperty(`--sl-color-${key}`, color);
				});
			});
		}

		/** Convert a color palette into a string of CSS rules. */
		#paletteToRules(palette: ReturnType<typeof getPalettes>['dark' | 'light']) {
			return Object.entries(palette)
				.map(([key, color]) => `--sl-color-${key}: ${color};`)
				.join('\n\t');
		}

		/** Update the CSS stylesheet applied to the current page and offered to users to copy. */
		#updateStylesheet({ dark, light }: ReturnType<typeof getPalettes>) {
			const styles = `/* Dark mode colors. */
:root {\n\t${this.#paletteToRules(dark)}\n}
/* Light mode colors. */
:root[data-theme='light'] {\n\t${this.#paletteToRules(light)}\n}`;
			this.#stylesheet.replaceSync(styles);
			const codePreview = this.querySelector('[data-theme-css]');
			if (codePreview) codePreview.innerHTML = styles;
		}

		#updateTailwindConfig({ dark, light }: ReturnType<typeof getPalettes>) {
			const config = `/* Generated accent color palettes. */
--color-accent-200: ${dark['accent-high']};
--color-accent-600: ${light.accent};
--color-accent-900: ${light['accent-high']};
--color-accent-950: ${dark['accent-low']};
/* Generated gray color palettes. */
--color-gray-100: ${light['gray-7']};
--color-gray-200: ${light['gray-6']};
--color-gray-300: ${light['gray-5']};
--color-gray-400: ${light['gray-4']};
--color-gray-500: ${light['gray-3']};
--color-gray-700: ${light['gray-2']};
--color-gray-800: ${light['gray-1']};
--color-gray-900: ${light.white};`;
			const codePreview = this.querySelector('[data-theme-tailwind]');
			if (codePreview) codePreview.innerHTML = config;
		}
	}

	customElements.define('theme-designer', ThemeDesigner);
</script>

<style>
	.controls {
		flex-wrap: wrap;
		gap: 1.5rem;
	}
	.controls > :global(*) {
		flex: 1 1;
	}
	.preview {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 1.5rem;
	}

	.generated-code {
		height: 16rem;
		background-color: var(--astro-code-color-background);
		overflow: auto scroll;
		user-select: all;
	}
</style>


================================================
FILE: docs/src/components/theme-grid.astro
================================================
---
import { Icon } from '@astrojs/starlight/components';
import FluidGrid from './fluid-grid.astro';
import MediaCard from './media-card.astro';
import ThemeImage from './theme-image.astro';

interface Props {
	labels: {
		/** Accessible label for the theme toggle. */
		legend: string;
		/** Accessible label for the dark color scheme variant. */
		dark: string;
		/** Accessible label for the light color scheme variant. */
		light: string;
	};
	themes: Array<{
		/** The name of this theme. */
		title: string;
		/** A short description of this theme. */
		description: string;
		/** URL for this theme’s website. Ideally should link to a demo site showing off the theme. */
		href: string;
		previews: {
			/** Image filename as found in `src/assets/themes/`, e.g. `ion-light.png`. */
			light: string;
			/** Image filename as found in `src/assets/themes/`, e.g. `ion-dark.png`. */
			dark: string;
		};
	}>;
}

const { labels, themes } = Astro.props;
---

<starlight-theme-preview data-theme-preview="dark">
	<fieldset class="not-content sl-flex">
		{
			/* `<legend>` is a pain to position, so we visually hide it and use an `aria-hidden` duplicate
		for the visual representation. See https://adrianroselli.com/2022/07/use-legend-and-fieldset.html */
		}
		<legend class="sr-only">{labels.legend}</legend>
		<strong aria-hidden="true">{labels.legend}</strong>
		{
			(['dark', 'light'] as const).map((variant) => (
				<label class:list={['sl-flex', variant]} for={`${variant}-input`}>
					<span class="radio">
						<Icon name="approve-check" />
					</span>
					<span>{labels[variant]}</span>
					<input
						id={`${variant}-input`}
						class="sr-only"
						name="preview-theme"
						value={variant}
						type="radio"
						checked={variant === 'dark'}
					/>
				</label>
			))
		}
		{/* If the currently active theme is light mode, default to showing the light mode previews. */}
		<script is:inline>
			// @ts-nocheck
			const theme = document.documentElement.dataset.theme || 'dark';
			const input = document.querySelector(`input[value="${theme}"]`);
			if (input) input.checked = true;
			const customEl = document.querySelector('starlight-theme-preview');
			if (customEl) customEl.dataset.themePreview = theme;
		</script>
	</fieldset>

	<FluidGrid minColumnWidth="25rem" gap="clamp(1rem, calc(0.75rem + 1vw), 1.5rem)">
		{
			themes.map(
				async ({ title, description, href, previews }) =>
					previews && (
						<MediaCard {href}>
							<div class="preview-images" slot="media" aria-hidden="true">
								<ThemeImage src={previews.light} class="light" />
								<ThemeImage src={previews.dark} class="dark" />
							</div>
							<div class="meta sl-flex">
								<p class="title">{title}</p>
								<p class="description" set:html={description} />
							</div>
						</MediaCard>
					)
			)
		}
	</FluidGrid>
</starlight-theme-preview>

<script>
	customElements.define(
		'starlight-theme-preview',
		class ThemePreview extends HTMLElement {
			constructor() {
				super();
				this.querySelector('fieldset')?.addEventListener('change', ({ target }) => {
					if (target instanceof HTMLInputElement) {
						this.dataset.themePreview = target.value;
					}
				});
			}
		}
	);
</script>

<style>
	starlight-theme-preview {
		--transition-time: 0.25s;
		display: block;
	}

	fieldset {
		/* Snappier transitions for the form controls. */
		--transition-time: 0.15s;

		/* Stick the control bar to bottom of the nav bar on scroll. */
		position: sticky;
		top: var(--sl-nav-height);
		z-index: var(--sl-z-index-toc);
		/* Pull the bar out so it is full width on small screens. */
		margin-inline: calc(-1 * var(--sl-nav-pad-x));
		padding: var(--sl-nav-pad-y) var(--sl-nav-pad-x);
		/* Internal layout and styles. */
		gap: 1rem;
		align-items: center;
		justify-content: end;
		border: 1px solid var(--sl-color-hairline);
		font-size: var(--sl-text-sm);
		background-color: var(--sl-color-bg-nav);
		box-shadow: var(--sl-shadow-md);
	}
	@media (min-width: 50rem) and (max-width: 72rem) {
		/* Medium-width screens need a custom value to avoid x-axis overflow. */
		fieldset {
			margin-inline: -1rem;
		}
	}

	label {
		align-items: center;
		gap: 0.375rem;
		color: var(--sl-color-gray-3);
		transition: color var(--transition-time) ease-in-out;
	}
	label:hover,
	label:has(:checked) {
		color: var(--sl-color-white);
	}

	.radio {
		display: grid;
		place-content: center;
		border: 1px solid var(--sl-color-gray-5);
		border-radius: 100%;
		width: 1.5rem;
		height: 1.5rem;
		background-color: #000;
		color: #fff;
		transition: transform var(--transition-time) ease-in-out;
	}
	label:not(:has(:checked)):hover .radio {
		transform: scale(1.15);
	}
	.light .radio {
		background-color: #fff;
		color: #000;
	}

	/* Show the input’s focus ring on the label. */
	label:has(:focus-visible) {
		outline: auto;
		outline-offset: 2px;
	}

	/* Show check mark icon only when input is checked. */
	label svg {
		opacity: 0;
		transition: opacity var(--transition-time) ease-in-out;
	}
	label:has(:checked) svg {
		opacity: 1;
	}

	/* Stack light/dark images in the same grid row and column. */
	.preview-images {
		display: grid;
		grid-template-columns: 1fr;
	}
	.preview-images > * {
		grid-area: 1 / 1;
	}

	/* Fade out the preview image that isn’t currently selected. */
	img {
		transition: opacity var(--transition-time) ease-in-out;
	}
	[data-theme-preview='dark'] img.light {
		opacity: 0;
	}
	[data-theme-preview='light'] img.dark {
		opacity: 0;
	}

	.meta {
		padding: 1rem;
		flex-direction: column;
		gap: 0.5rem;
	}

	.title {
		font-size: var(--sl-text-lg);
	}

	.description {
		color: var(--sl-color-gray-3);
		line-height: 1.5;
	}
</style>


================================================
FILE: docs/src/components/theme-image.astro
================================================
---
import { AstroError } from 'astro/errors';
import { Image } from 'astro:assets';

interface Props {
	src: string;
	class: 'light' | 'dark';
}

const thumbnails = import.meta.glob<{ default: ImageMetadata }>(
	'../assets/themes/*{.png,.jpg,.jpeg,.webp,.avif}'
);

const thumbnail = thumbnails[`../assets/themes/${Astro.props.src}`];
if (!thumbnail) {
	throw new Error(`Could not resolve showcase thumbnail: ${Astro.props.src}`);
}
const src = (await thumbnail()).default;

if (src.width !== 1280 || src.height !== 720) {
	let fileName = src.src.split('/').pop();
	const queryIndex = fileName?.indexOf('?');
	if (queryIndex !== undefined && queryIndex > -1) {
		fileName = fileName?.slice(0, queryIndex);
	}
	throw new AstroError(
		'Theme screenshots must be **1280×720px**',
		`Dimensions of **${src.width}×${src.height}px** found for theme image \`${fileName || src.src}\`\n\n` +
			`For best results:\n\n` +
			`1. Take a screenshot of the site using a browser resized to **1280×720px**. The responsive view in dev tools can be helpful for this.\n\n` +
			`2. Resize the screenshot to **1280×720px** if necessary and make sure it is saved as a PNG. An online tool like [Squoosh](https://squoosh.app/) can help here.\n\n` +
			`See more details in the [Starlight contributing guide](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md#themes)\n`
	);
}
---

<Image {src} alt="" width="960" class={Astro.props.class} />


================================================
FILE: docs/src/components/ui-strings-list.astro
================================================
---
import { Code } from '@astrojs/starlight/components';
import uiStrings from '../../../packages/starlight/translations/en.json?raw';
---

<Code code={uiStrings} lang="json" />


================================================
FILE: docs/src/components/youtube-card.astro
================================================
---
import { YouTube } from '@astro-community/astro-embed-youtube';
import MediaCard from './media-card.astro';

export interface Props {
	href: string;
	title: string;
	description?: string;
}
const { href, title, description } = Astro.props;
---

<MediaCard>
	<YouTube slot="media" id={href} />
	<div class="meta sl-flex">
		<p class="title">{title}</p>
		{description && <p class="description" set:html={description} />}
	</div>
</MediaCard>

<style>
	.meta {
		padding: 1rem;
		flex-direction: column;
		gap: 0.5rem;
	}
	.title {
		font-size: var(--sl-text-lg);
	}
	.description {
		color: var(--sl-color-gray-3);
		line-height: 1.5;
	}
</style>


================================================
FILE: docs/src/components/youtube-grid.astro
================================================
---
import FluidGrid from './fluid-grid.astro';
import YoutubeCard, { type Props as CardProps } from './youtube-card.astro';

interface Props {
	videos: CardProps[];
}
---

<FluidGrid minColumnWidth="16rem">
	{Astro.props.videos.map((video) => <YoutubeCard {...video} />)}
</FluidGrid>


================================================
FILE: docs/src/content/docs/404.md
================================================
---
title: Not found
template: splash
editUrl: false
lastUpdated: false
hero:
  title: '404'
  tagline: <strong>Houston, we have a problem.</strong> We couldn’t find that page.<br>Check the URL or try using the search bar.
  actions:
    - text: Go home
      icon: right-arrow
      link: /
      variant: primary
---


================================================
FILE: docs/src/content/docs/components/asides.mdx
================================================
---
title: Asides
description: Learn how to use asides in Starlight to display secondary information alongside a page’s main content.
---

import { Aside } from '@astrojs/starlight/components';

To display secondary information alongside a page’s main content, use the `<Aside>` component.

import Preview from '~/components/component-preview.astro';

<Preview>

<Aside slot="preview">
    Include nonessential, supplementary information in an `<Aside>`.
</Aside>

</Preview>

## Import

```tsx
import { Aside } from '@astrojs/starlight/components';
```

## Usage

Display an aside (also known as “admonitions” or “callouts”) using the `<Aside>` component.

An `<Aside>` can have an optional [`type`](#type) attribute, which controls the aside’s color, icon, and default title.

<Preview>

````mdx
import { Aside } from '@astrojs/starlight/components';

<Aside>Some content in an aside.</Aside>

<Aside type="caution">Some cautionary content.</Aside>

<Aside type="tip">

Other content is also supported in asides.

```js
// A code snippet, for example.
```

</Aside>

<Aside type="danger">Do not give your password to anyone.</Aside>
````

<Fragment slot="markdoc">

````markdoc
{% aside %}
Some content in an aside.
{% /aside %}

{% aside type="caution" %}
Some cautionary content.
{% /aside %}

{% aside type="tip" %}
Other content is also supported in asides.

```js
// A code snippet, for example.
```
{% /aside %}

{% aside type="danger" %}
Do not give your password to anyone.
{% /aside %}
````

</Fragment>

<Fragment slot="preview">

    <Aside>Some content in an aside.</Aside>

    <Aside type="caution">Some cautionary content.</Aside>

    <Aside type="tip">

    Other content is also supported in asides.

    ```js
    // A code snippet, for example.
    ```

    </Aside>

    <Aside type="danger">Do not give your password to anyone.</Aside>

</Fragment>

</Preview>

Starlight also provides a custom syntax for rendering asides in Markdown and MDX as an alternative to the `<Aside>` component.
See the [“Authoring Content in Markdown”](/guides/authoring-content/#asides) guide for details of the custom syntax.

### Use custom titles

Override the default aside titles by using the [`title`](#title) attribute.

<Preview>

```mdx 'title="Watch out!"'
import { Aside } from '@astrojs/starlight/components';

<Aside type="caution" title="Watch out!">
	A warning aside *with* a custom title.
</Aside>
```

<Fragment slot="markdoc">

```markdoc 'title="Watch out!"'
{% aside type="caution" title="Watch out!" %}
A warning aside *with* a custom title.
{% /aside %}
```

</Fragment>

<Aside slot="preview" type="caution" title="Watch out!">
	A warning aside *with* a custom title.
</Aside>

</Preview>

### Use custom icons

Override the default aside icons by using the [`icon`](#icon) attribute set to the name of [one of Starlight’s built-in icons](/reference/icons/#all-icons).

<Preview>

```mdx 'icon="starlight"'
import { Aside } from '@astrojs/starlight/components';

<Aside type="tip" icon="starlight">
	A tip aside *with* a custom icon.
</Aside>
```

<Fragment slot="markdoc">

```markdoc 'icon="starlight"'
{% aside type="tip" icon="starlight" %}
A tip aside *with* a custom icon.
{% /aside %}
```

</Fragment>

<Aside slot="preview" type="tip" icon="starlight">
	A tip aside *with* a custom icon.
</Aside>

</Preview>

## `<Aside>` Props

**Implementation:** [`Aside.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Aside.astro)

The `<Aside>` component accepts the following props:

### `type`

**type:** `'note' | 'tip' | 'caution' | 'danger'`  
**default:** `'note'`

The type of aside to display:

- `note` asides (the default) are blue and display an information icon.
- `tip` asides are purple and display a rocket icon.
- `caution` asides are yellow and display a triangular warning icon.
- `danger` asides are red and display an octagonal warning icon.

### `title`

**type:** `string`

The title of the aside to display.
If `title` is not set, the default title for the current aside `type` will be used.

### `icon`

**type:** [`StarlightIcon`](/reference/icons/#starlighticon-type)

An aside can include an `icon` attribute set to the name of [one of Starlight’s built-in icons](/reference/icons/#all-icons).


================================================
FILE: docs/src/content/docs/components/badges.mdx
================================================
---
title: Badges
description: Learn how to use badges in Starlight to display additional pieces of information.
---

import { Badge } from '@astrojs/starlight/components';

To display small pieces of information, such as a status or category, use the `<Badge>` component.

import Preview from '~/components/component-preview.astro';

<Preview>

<Badge slot="preview" text="New" />

</Preview>

## Import

```tsx
import { Badge } from '@astrojs/starlight/components';
```

## Usage

Display a badge using the `<Badge>` component and pass the content you want to display to the [`text`](#text) attribute of the `<Badge>` component.

By default, the badge will use the theme accent color of your site.
To use a built-in badge color, set the [`variant`](#variant) attribute to one of the supported values.

<Preview>

```mdx
import { Badge } from '@astrojs/starlight/components';

- <Badge text="Note" variant="note" />
- <Badge text="Success" variant="success" />
- <Badge text="Tip" variant="tip" />
- <Badge text="Caution" variant="caution" />
- <Badge text="Danger" variant="danger" />
```

<Fragment slot="markdoc">

```markdoc
- {% badge text="Note" variant="note" /%}
- {% badge text="Success" variant="success" /%}
- {% badge text="Tip" variant="tip" /%}
- {% badge text="Caution" variant="caution" /%}
- {% badge text="Danger" variant="danger" /%}
```

</Fragment>

<Fragment slot="preview">
	- <Badge text="Note" variant="note" />
	- <Badge text="Success" variant="success" />
	- <Badge text="Tip" variant="tip" />
	- <Badge text="Caution" variant="caution" />
	- <Badge text="Danger" variant="danger" />
</Fragment>

</Preview>

### Use different sizes

Use the [`size`](#size) attribute to control the size of the badge text.

<Preview>

```mdx /size="\w+"/
import { Badge } from '@astrojs/starlight/components';

- <Badge text="New" size="small" />
- <Badge text="New and improved" size="medium" />
- <Badge text="New, improved, and bigger" size="large" />
```

<Fragment slot="markdoc">

```markdoc /size="\w+"/
- {% badge text="New" size="small" /%}
- {% badge text="New and improved" size="medium" /%}
- {% badge text="New, improved, and bigger" size="large" /%}
```

</Fragment>

<Fragment slot="preview">
	- <Badge text="New" size="small" />
	- <Badge text="New and improved" size="medium" />
	- <Badge text="New, improved, and bigger" size="large" />
</Fragment>

</Preview>

### Customize badges

Customize badges by using any other `<span>` attributes such as `class` or `style` with custom CSS.

<Preview>

```mdx "style={{ fontStyle: 'italic' }}"
import { Badge } from '@astrojs/starlight/components';

<Badge text="Custom" variant="success" style={{ fontStyle: 'italic' }} />
```

<Fragment slot="markdoc">

```markdoc 'style="font-style: italic;"'
{% badge text="Custom" variant="success" style="font-style: italic;" /%}
```

</Fragment>

<Badge
	slot="preview"
	text="Custom"
	variant="success"
	style={{ fontStyle: 'italic' }}
/>

</Preview>

## `<Badge>` Props

**Implementation:** [`Badge.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Badge.astro)

The `<Badge>` component accepts the following props and also any [other `<span>` attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes):

### `text`

**required**  
**type:** `string`

The text content to display in the badge.

### `variant`

**type:** `'note' | 'danger' | 'success' | 'caution' | 'tip' | 'default'`  
**default:** `'default'`

The badge color variant to use: `note` (blue), `tip` (purple), `danger` (red), `caution` (orange), `success` (green), or `default` (theme accent color).

### `size`

**type:** `'small' | 'medium' | 'large'`

Defines the size of the badge to display.


================================================
FILE: docs/src/content/docs/components/card-grids.mdx
================================================
---
title: Card Grids
description: Learn how to wrap multiple cards in a grid in Starlight.
sidebar:
  order: 4
---

import { Card, CardGrid, LinkCard } from '@astrojs/starlight/components';

To wrap multiple [`<Card>`](/components/cards/) or [`<LinkCard>`](/components/link-cards/) components in a grid, use the`<CardGrid>` component.

import Preview from '~/components/component-preview.astro';

<Preview>

<CardGrid slot="preview">
	<Card title="Stars" icon="star">
		Sirius, Vega, Betelgeuse
	</Card>
	<Card title="Moons" icon="moon">
		Io, Europa, Ganymede
	</Card>
</CardGrid>

</Preview>

## Import

```tsx
import { CardGrid } from '@astrojs/starlight/components';
```

## Usage

### Group cards

Display multiple [`<Card>`](/components/cards/) components side-by-side when there’s enough space by grouping them using the `<CardGrid>` component.

<Preview>

```mdx {3,10}
import { Card, CardGrid } from '@astrojs/starlight/components';

<CardGrid>
	<Card title="Check this out" icon="open-book">
		Interesting content you want to highlight.
	</Card>
	<Card title="Other feature" icon="information">
		More information you want to share.
	</Card>
</CardGrid>
```

<Fragment slot="markdoc">

```markdoc {1,9}
{% cardgrid %}
{% card title="Check this out" icon="open-book" %}
Interesting content you want to highlight.
{% /card %}

{% card title="Other feature" icon="information" %}
More information you want to share.
{% /card %}
{% /cardgrid %}
```

</Fragment>

<CardGrid slot="preview">
	<Card title="Check this out" icon="open-book">
		Interesting content you want to highlight.
	</Card>
	<Card title="Other feature" icon="information">
		More information you want to share.
	</Card>
</CardGrid>

</Preview>

### Group link cards

Display multiple [`<LinkCard>`](/components/link-cards/) components side-by-side when there’s enough space by grouping them using the `<CardGrid>` component.

<Preview>

```mdx {3,6}
import { LinkCard, CardGrid } from '@astrojs/starlight/components';

<CardGrid>
	<LinkCard title="Authoring Markdown" href="/guides/authoring-content/" />
	<LinkCard title="Components" href="/components/using-components/" />
</CardGrid>
```

<Fragment slot="markdoc">

```markdoc {1,5}
{% cardgrid %}
{% linkcard title="Authoring Markdown" href="/guides/authoring-content/" /%}

{% linkcard title="Components" href="/components/using-components/" /%}
{% /cardgrid %}
```

</Fragment>

<CardGrid slot="preview">
	<LinkCard title="Authoring Markdown" href="/guides/authoring-content/" />
	<LinkCard title="Components" href="/components/using-components/" />
</CardGrid>

</Preview>

### Stagger cards

Shift the second column of the grid vertically to add visual interest by adding the [`stagger`](#stagger) attribute to the `<CardGrid>` component.

This attribute is useful on your home page to display your project’s key features.

<Preview>

```mdx "stagger"
import { Card, CardGrid } from '@astrojs/starlight/components';

<CardGrid stagger>
	<Card title="Check this out" icon="open-book">
		Interesting content you want to highlight.
	</Card>
	<Card title="Other feature" icon="information">
		More information you want to share.
	</Card>
</CardGrid>
```

<Fragment slot="markdoc">

```markdoc "stagger=true"
{% cardgrid stagger=true %}
{% card title="Check this out" icon="open-book" %}
Interesting content you want to highlight.
{% /card %}

{% card title="Other feature" icon="information" %}
More information you want to share.
{% /card %}
{% /cardgrid %}
```

</Fragment>

<CardGrid slot="preview" stagger>
	<Card title="Check this out" icon="open-book">
		Interesting content you want to highlight.
	</Card>
	<Card title="Other feature" icon="information">
		More information you want to share.
	</Card>
</CardGrid>

</Preview>

## `<CardGrid>` Props

**Implementation:** [`CardGrid.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/CardGrid.astro)

The `<CardGrid>` component accepts the following props:

### `stagger`

**type:** `boolean`

Defines whether to stagger the cards in the grid or not.


================================================
FILE: docs/src/content/docs/components/cards.mdx
================================================
---
title: Cards
description: Learn how to use cards in Starlight to display content in a box.
sidebar:
  order: 2
---

import { Card } from '@astrojs/starlight/components';

To display content in a box matching Starlight’s styles, use the `<Card>` component.

import Preview from '~/components/component-preview.astro';

<Preview>

<Card slot="preview" title="Moons" icon="moon">
	Io, Europa, Ganymede
</Card>

</Preview>

## Import

```tsx
import { Card } from '@astrojs/starlight/components';
```

## Usage

Display a card using the `<Card>` component and provide a [`title`](#title) for the card.

<Preview>

```mdx
import { Card } from '@astrojs/starlight/components';

<Card title="Check this out">Interesting content you want to highlight.</Card>
```

<Fragment slot="markdoc">

```markdoc
{% card title="Check this out" %}
Interesting content you want to highlight.
{% /card %}
```

</Fragment>

<Card slot="preview" title="Check this out">
	Interesting content you want to highlight.
</Card>

</Preview>

### Add icons to cards

Include an icon in a card using the [`icon`](#icon) attribute set to the name of [one of Starlight’s built-in icons](/reference/icons/#all-icons).

<Preview>

```mdx 'icon="star"'
import { Card } from '@astrojs/starlight/components';

<Card title="Stars" icon="star">
	Sirius, Vega, Betelgeuse
</Card>
```

<Fragment slot="markdoc">

```markdoc 'icon="star"'
{% card title="Stars" icon="star" %}
Sirius, Vega, Betelgeuse
{% /card %}
```

</Fragment>

<Card slot="preview" title="Stars" icon="star">
	Sirius, Vega, Betelgeuse
</Card>

</Preview>

### Group cards

Display multiple cards side-by-side when there’s enough space by grouping them using the [`<CardGrid>`](/components/card-grids/) component.
See the [“Group cards”](/components/card-grids/#group-cards) guide for an example.

## `<Card>` Props

**Implementation:** [`Card.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Card.astro)

The `<Card>` component accepts the following props:

### `title`

**required**  
**type:** `string`

The title of the card to display.

### `icon`

**type:** `string`

A card can include an `icon` attribute set to the name of [one of Starlight’s built-in icons](/reference/icons/#all-icons).


================================================
FILE: docs/src/content/docs/components/code.mdx
================================================
---
title: Code
description: Learn how to display syntax highlighted code in Starlight without Markdown code blocks.
---

import { Code } from '@astrojs/starlight/components';

The `<Code>` component renders syntax highlighted code.
It is useful when using a [Markdown code block](/guides/authoring-content/#code-blocks) is not possible, for example, to render data coming from external sources like files, databases, or APIs.

import Preview from '~/components/component-preview.astro';

<Preview>

<Code
	slot="preview"
	code={`## Welcome

Hello from **space**!`}
lang="md"
title="example.md"
ins={3}
/>

</Preview>

## Import

```tsx
import { Code } from '@astrojs/starlight/components';
```

## Usage

Use the `<Code>` component to render syntax highlighted code, for example when displaying code fetched from external sources.

See the [Expressive Code “Code Component” docs](https://expressive-code.com/key-features/code-component/) for full details on how to use the `<Code>` component and the list of available props.

<Preview>

```mdx
import { Code } from '@astrojs/starlight/components';

export const exampleCode = `console.log('This could come from a file or CMS!');`;
export const fileName = 'example.js';
export const highlights = ['file', 'CMS'];

<Code code={exampleCode} lang="js" title={fileName} mark={highlights} />
```

<Fragment slot="markdoc">

```markdoc
{% code
   code="console.log('This could come from a file or CMS!');"
   lang="js"
   title="example.js"
   meta="'file' 'CMS'" /%}
```

</Fragment>

export const exampleCode = `console.log('This could come from a file or CMS!');`;
export const fileName = 'example.js';
export const highlights = ['file', 'CMS'];

<Code
	slot="preview"
	code={exampleCode}
	lang="js"
	title={fileName}
	mark={highlights}
/>

</Preview>

### Display imported code

In MDX files and Astro components, use [Vite’s `?raw` import suffix](https://vite.dev/guide/assets#importing-asset-as-string) to import any code file as a string.
You can then pass this imported string to the `<Code>` component to include it on your page.

<Preview>

```mdx "?raw"
# src/content/docs/example.mdx

import { Code } from '@astrojs/starlight/components';
import importedCode from '/tsconfig.json?raw';

<Code code={importedCode} lang="json" title="tsconfig.json" />
```

import importedCode from '../../../../../examples/basics/tsconfig.json?raw';

<Code slot="preview" code={importedCode} lang="json" title="tsconfig.json" />

</Preview>

## `<Code>` Props

**Implementation:** [`Code.astro`](https://github.com/expressive-code/expressive-code/blob/main/packages/astro-expressive-code/components/Code.astro)

The `<Code>` component accepts all the props documented in the [Expressive Code “Code Component” docs](https://expressive-code.com/key-features/code-component/#available-props).


================================================
FILE: docs/src/content/docs/components/file-tree.mdx
================================================
---
title: File Tree
description: Learn how to display the structure of a directory with file icons and collapsible sub-directories in Starlight.
---

import { FileTree } from '@astrojs/starlight/components';

To display the structure of a directory with file icons and collapsible sub-directories, use the `<FileTree>` component.

import Preview from '~/components/component-preview.astro';

<Preview>

<FileTree slot="preview">

- astro.config.mjs an **important** file
- package.json
- README.md
- src
  - components
    - **Header.astro**
  - …
- pages/

</FileTree>

</Preview>

## Import

```tsx
import { FileTree } from '@astrojs/starlight/components';
```

## Usage

Display a file tree with file icons and collapsible sub-directories using the `<FileTree>` component.

Specify the structure of your files and directories with an [unordered Markdown list](https://www.markdownguide.org/basic-syntax/#unordered-lists) inside `<FileTree>`.
Create a sub-directory using a nested list or add a `/` to the end of a list item to render it as a directory without specific content.

<Preview>

```mdx
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- astro.config.mjs
- package.json
- src
  - components
    - Header.astro
    - Title.astro
  - pages/

</FileTree>
```

<Fragment slot="markdoc">

```markdoc
{% filetree %}
- astro.config.mjs
- package.json
- src
  - components
    - Header.astro
    - Title.astro
  - pages/
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- astro.config.mjs
- package.json
- src
  - components
    - Header.astro
    - Title.astro
  - pages/

</FileTree>

</Preview>

### Highlight entries

Make a file or directory stand out by making its name bold, e.g. `**README.md**`.

<Preview>

```mdx {7}
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src
  - components
    - **Header.astro**
    - Title.astro

</FileTree>
```

<Fragment slot="markdoc">

```markdoc {4}
{% filetree %}
- src
  - components
    - **Header.astro**
    - Title.astro
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- src
  - components
    - **Header.astro**
    - Title.astro

</FileTree>

</Preview>

### Add comments

Add a comment to a file or directory by adding more text after the name.
Inline Markdown formatting such as bold and italics is supported in comments.

<Preview>

```mdx {7}
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src
  - components
    - Header.astro an **important** file
    - Title.astro

</FileTree>
```

<Fragment slot="markdoc">

```markdoc {4}
{% filetree %}
- src
  - components
    - Header.astro an **important** file
    - Title.astro
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- src
  - components
    - Header.astro an **important** file
    - Title.astro

</FileTree>

</Preview>

### Add placeholders

Add placeholder files and directories by using either `...` or `…` as the name.
This can be useful to indicate to a reader that a folder is expected to contain more items without specifying them all explicitly.

<Preview>

```mdx {8}
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src
  - components
    - Header.astro
    - …

</FileTree>
```

<Fragment slot="markdoc">

```markdoc {5}
{% filetree %}
- src
  - components
    - Header.astro
    - …
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- src
  - components
    - Header.astro
    - …

</FileTree>

</Preview>

### Escape special characters

Escape special characters such as underscores or spaces in filenames by wrapping the filename in code backticks.

<Preview>

```mdx
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- `__init__.py`
- `Hello world.txt`
- **`READ ME FIRST.md`**

</FileTree>
```

<Fragment slot="markdoc">

```markdoc
{% filetree %}
- `__init__.py`
- `Hello world.txt`
- **`READ ME FIRST.md`**
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- `__init__.py`
- `Hello world.txt`
- **`READ ME FIRST.md`**

</FileTree>

</Preview>

## `<FileTree>` Props

**Implementation:** [`FileTree.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/FileTree.astro)

The `<FileTree>` component does not accept any props.


================================================
FILE: docs/src/content/docs/components/icons.mdx
================================================
---
title: Icons
description: Learn how to display icons in Starlight.
---

import { Icon } from '@astrojs/starlight/components';

To display icons from Starlight’s [built-in icon set](/reference/icons/#all-icons), use the `<Icon>` component.

import Preview from '~/components/component-preview.astro';

<Preview>

<Icon
	slot="preview"
	name="open-book"
	color="var(--sl-color-text-accent)"
	size="4rem"
/>

</Preview>

## Import

```tsx
import { Icon } from '@astrojs/starlight/components';
```

## Usage

Display an icon using the `<Icon>` component.
An icon requires a [`name`](#name) set to [one of Starlight’s built-in icons](/reference/icons/#all-icons) and can optionally include a [`label`](#label) to provide context for screen readers.

<Preview>

```mdx
import { Icon } from '@astrojs/starlight/components';

<Icon name="star" />
<Icon name="starlight" label="The Starlight logo" />
```

<Fragment slot="markdoc">

```markdoc
{% icon name="star" /%}
{% icon name="starlight" label="The Starlight logo" /%}
```

</Fragment>

<Fragment slot="preview">
	<Icon name="star" />
	<Icon name="starlight" label="The Starlight logo" />
</Fragment>

</Preview>

### Customize icons

The [`size`](#size) and [`color`](#color) attributes can be used to adjust the icon’s appearance using CSS units and color values.
The [`class`](#class) attribute can be used to add custom CSS classes to the icon.

<Preview>

```mdx
import { Icon } from '@astrojs/starlight/components';

<Icon name="star" color="goldenrod" size="2rem" />
<Icon name="rocket" color="var(--sl-color-text-accent)" />
```

<Fragment slot="markdoc">

```markdoc
{% icon name="star" color="goldenrod" size="2rem" /%}
{% icon name="rocket" color="var(--sl-color-text-accent)" /%}
```

</Fragment>

<Fragment slot="preview">
	<Icon name="star" color="goldenrod" size="2rem" />
	<Icon name="rocket" color="var(--sl-color-text-accent)" />
</Fragment>

</Preview>

## `<Icon>` Props

**Implementation:** [`Icon.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Icon.astro)

The `<Icon>` component accepts the following props:

### `name`

**required**  
**type:** [`StarlightIcon`](/reference/icons/#starlighticon-type)

The name of the icon to display set to [one of Starlight’s built-in icons](/reference/icons/#all-icons).

### `label`

**type:** `string`

An optional label to provide context for assistive technologies, such as screen readers.

When `label` is not set, the icon will be completely hidden from assistive technologies.
In this case, make sure the context is still understandable without the icon.
For example, a link containing only the icon **must** include the `label` attribute in order to be accessible, but if a link contains text and the icon is purely decorative, omitting the `label` may make sense.

### `size`

**type:** `string`

The size of the icon using CSS units.

### `color`

**type:** `string`

The color of the icon using a CSS color value.

### `class`

**type:** `string`

Custom CSS classes to add to the icon.


================================================
FILE: docs/src/content/docs/components/link-buttons.mdx
================================================
---
title: Link Buttons
description: Learn how to create link buttons in Starlight for visually distinct call-to-action links.
---

import { LinkButton } from '@astrojs/starlight/components';

To display visually distinct call-to-action links, use the `<LinkButton>` component.

import Preview from '~/components/component-preview.astro';

<Preview>

<LinkButton slot="preview" href="/getting-started/">
	Read the docs
</LinkButton>

</Preview>

## Import

```tsx
import { LinkButton } from '@astrojs/starlight/components';
```

## Usage

Use the `<LinkButton>` component to display a visually distinct call-to-action link.
A link button is useful for directing users to the most relevant or actionable content and is often used on landing pages.

A `<LinkButton>` requires an [`href`](#href) attribute.
Optionally, customize the appearance of the link button using the [`variant`](#variant) attribute, which can be set to `primary` (the default), `secondary`, or `minimal`.

<Preview>

```mdx
import { LinkButton } from '@astrojs/starlight/components';

<LinkButton href="/getting-started/">Get started</LinkButton>
<LinkButton href="/reference/configuration/" variant="secondary">
	Configuration Reference
</LinkButton>
```

<Fragment slot="markdoc">

```markdoc
{% linkbutton href="/getting-started/" %}Get started{% /linkbutton %}

{% linkbutton href="/reference/configuration/" variant="secondary" %}
Configuration Reference
{% /linkbutton %}
```

</Fragment>

<Fragment slot="preview">
	<LinkButton href="/getting-started/">Get started</LinkButton>
	<LinkButton href="/reference/configuration/" variant="secondary">
		Configuration Reference
	</LinkButton>
</Fragment>

</Preview>

### Add icons to link buttons

Include an icon in a link button using the [`icon`](#icon) attribute set to the name of [one of Starlight’s built-in icons](/reference/icons/#all-icons).

The [`iconPlacement`](#iconplacement) attribute can be used to place the icon before the text by setting it to `start` (defaults to `end`).

<Preview>

```mdx {6-7}
import { LinkButton } from '@astrojs/starlight/components';

<LinkButton
	href="https://docs.astro.build"
	variant="secondary"
	icon="external"
	iconPlacement="start"
>
	Related: Astro
</LinkButton>
```

<Fragment slot="markdoc">

```markdoc {4-5}
{% linkbutton
   href="https://docs.astro.build"
	 variant="secondary"
	 icon="external"
	 iconPlacement="start" %}
Related: Astro
{% /linkbutton %}
```

</Fragment>

<LinkButton
	slot="preview"
	href="https://docs.astro.build"
	variant="secondary"
	icon="external"
	iconPlacement="start"
>
	Related: Astro
</LinkButton>

</Preview>

## `<LinkButton>` Props

**Implementation:** [`LinkButton.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/LinkButton.astro)

The `<LinkButton>` component accepts the following props and also any [other `<a>` attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a):

### `href`

**required**  
**type:** `string`

The URL that the link button points to.

### `variant`

**type:** `'primary' | 'secondary' | 'minimal'`  
**default:** `'primary'`

The appearance of the link button.
Set to `primary` for a prominent call-to-action link using the theme’s accent color, `secondary` for a less prominent link, or `minimal` for a link with minimal styling.

### `icon`

**type:** `string`

A link button can include an `icon` attribute set to the name of [one of Starlight’s built-in icons](/reference/icons/#all-icons).

### `iconPlacement`

**type:** `'start' | 'end'`  
**default:** `'end'`

Determines the placement of the icon in relation to the link button text.


================================================
FILE: docs/src/content/docs/components/link-cards.mdx
================================================
---
title: Link Cards
description: Learn how to display links prominently as cards in Starlight.
sidebar:
  order: 3
---

import { LinkCard } from '@astrojs/starlight/components';

To display links to different pages prominently, use the `<LinkCard>` component.

import Preview from '~/components/component-preview.astro';

<Preview>

<LinkCard
	slot="preview"
	title="Customizing Starlight"
	description="Learn how to make your Starlight site your own with custom styles, fonts, and more."
	href="/guides/customization/"
/>

</Preview>

## Import

```tsx
import { LinkCard } from '@astrojs/starlight/components';
```

## Usage

Display a link prominently using the `<LinkCard>` component.
Each `<LinkCard>` requires a [`title`](#title) and an [`href`](#href) attribute.

<Preview>

```mdx
import { LinkCard } from '@astrojs/starlight/components';

<LinkCard title="Authoring Markdown" href="/guides/authoring-content/" />
```

<Fragment slot="markdoc">

```markdoc
{% linkcard title="Authoring Markdown" href="/guides/authoring-content/" /%}
```

</Fragment>

<LinkCard
	slot="preview"
	title="Authoring Markdown"
	href="/guides/authoring-content/"
/>

</Preview>

### Add a link description

Add a short description to a link card using the [`description`](#description) attribute.

<Preview>

```mdx {6}
import { LinkCard } from '@astrojs/starlight/components';

<LinkCard
	title="Internationalization"
	href="/guides/i18n/"
	description="Configure Starlight to support multiple languages."
/>
```

<Fragment slot="markdoc">

```markdoc {4}
{% linkcard
   title="Internationalization"
	 href="/guides/i18n/"
	 description="Configure Starlight to support multiple languages." /%}
```

</Fragment>

<LinkCard
	slot="preview"
	title="Internationalization"
	href="/guides/i18n/"
	description="Configure Starlight to support multiple languages."
/>

</Preview>

### Group link cards

Display multiple link cards side-by-side when there’s enough space by grouping them using the [`<CardGrid>`](/components/card-grids/) component.
See the [“Group link cards”](/components/card-grids/#group-link-cards) guide for an example.

## `<LinkCard>` Props

**Implementation:** [`LinkCard.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/LinkCard.astro)

The `<LinkCard>` component accepts the following props, as well as all other [`<a>` element attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a):

### `title`

**required**  
**type:** `string`

The title of the link card to display.

### `href`

**required**  
**type:** `string`

The URL to link to when the card is interacted with.

### `description`

**type:** `string`

An optional description to display below the title.


================================================
FILE: docs/src/content/docs/components/steps.mdx
================================================
---
title: Steps
description: Learn how to style numbered lists of tasks to create step-by-step guides in Starlight.
---

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

To style a numbered list of tasks to create step-by-step guides, use the `<Steps>` component.

import Preview from '~/components/component-preview.astro';

<Preview>

<Steps slot="preview">

1. Create a new Starlight project:

   <Tabs syncKey="pkg">

   <TabItem label="npm">

   ```sh
   npm create astro@latest -- --template starlight
   ```

   </TabItem>

   <TabItem label="pnpm">

   ```sh
   pnpm create astro --template starlight
   ```

   </TabItem>

   <TabItem label="Yarn">

   ```sh
   yarn create astro --template starlight
   ```

   </TabItem>

   </Tabs>

2. Write your first documentation page.

</Steps>

</Preview>

## Import

```tsx
import { Steps } from '@astrojs/starlight/components';
```

## Usage

Use the `<Steps>` component to style numbered lists of tasks.
This is useful for more complex step-by-step guides where each step needs to be clearly highlighted.

Wrap `<Steps>` around a standard Markdown ordered list.
All the usual Markdown syntax is applicable inside `<Steps>`.

<Preview>

````mdx
import { Steps } from '@astrojs/starlight/components';

<Steps>

1. Import the component into your MDX file:

   ```js
   import { Steps } from '@astrojs/starlight/components';
   ```

2. Wrap `<Steps>` around your ordered list items.

</Steps>
````

<Fragment slot="markdoc">

````markdoc
{% steps %}

1. Import the component into your MDX file:

   ```js
   import { Steps } from '@astrojs/starlight/components';
   ```

2. Wrap `<Steps>` around your ordered list items.

{% /steps %}
````

</Fragment>

<Steps slot="preview">

1. Import the component into your MDX file:

   ```js
   import { Steps } from '@astrojs/starlight/components';
   ```

2. Wrap `<Steps>` around your ordered list items.

</Steps>

</Preview>

## `<Steps>` Props

**Implementation:** [`Steps.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Steps.astro)

The `<Steps>` component does not accept any props.


================================================
FILE: docs/src/content/docs/components/tabs.mdx
================================================
---
title: Tabs
description: Learn how to create tabbed interfaces in Starlight to group equivalent information.
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

To create a tabbed interface use the `<Tabs>` and `<TabItem>` components.
Tabs are useful for grouping equivalent information where a user only needs to see one of several options.

import Preview from '~/components/component-preview.astro';

<Preview>

<Tabs slot="preview">
	<TabItem label="Stars">Sirius, Vega, Betelgeuse</TabItem>
	<TabItem label="Moons">Io, Europa, Ganymede</TabItem>
</Tabs>

</Preview>

## Import

```tsx
import { Tabs, TabItem } from '@astrojs/starlight/components';
```

## Usage

Display a tabbed interface using the `<Tabs>` and `<TabItem>` components.
Each `<TabItem>` must have a [`label`](#label) to display to users.

<Preview>

```mdx
import { Tabs, TabItem } from '@astrojs/starlight/components';

<Tabs>
	<TabItem label="Stars">Sirius, Vega, Betelgeuse</TabItem>
	<TabItem label="Moons">Io, Europa, Ganymede</TabItem>
</Tabs>
```

<Fragment slot="markdoc">

```markdoc
{% tabs %}
{% tabitem label="Stars" %}
Sirius, Vega, Betelgeuse
{% /tabitem %}

{% tabitem label="Moons" %}
Io, Europa, Ganymede
{% /tabitem %}
{% /tabs %}
```

</Fragment>

<Tabs slot="preview">
	<TabItem label="Stars">Sirius, Vega, Betelgeuse</TabItem>
	<TabItem label="Moons">Io, Europa, Ganymede</TabItem>
</Tabs>

</Preview>

### Sync tabs

Keep multiple tab groups synchronized by adding the [`syncKey`](#synckey) attribute.

All `<Tabs>` on a page with the same `syncKey` value will display the same active label.
This allows your reader to choose once (e.g. their operating system or package manager), and see their choice persisted across page navigations.

To synchronize related tabs, add an identical `syncKey` property to each `<Tabs>` component and ensure that they all use the same `<TabItem>` labels:

<Preview>

```mdx 'syncKey="constellations"'
import { Tabs, TabItem } from '@astrojs/starlight/components';

_Some stars:_

<Tabs syncKey="constellations">
	<TabItem label="Orion">Bellatrix, Rigel, Betelgeuse</TabItem>
	<TabItem label="Gemini">Pollux, Castor A, Castor B</TabItem>
</Tabs>

_Some exoplanets:_

<Tabs syncKey="constellations">
	<TabItem label="Orion">HD 34445 b, Gliese 179 b, Wasp-82 b</TabItem>
	<TabItem label="Gemini">Pollux b, HAT-P-24b, HD 50554 b</TabItem>
</Tabs>
```

<Fragment slot="markdoc">

```markdoc 'syncKey="constellations"'
_Some stars:_

{% tabs syncKey="constellations" %}
{% tabitem label="Orion" %}
Bellatrix, Rigel, Betelgeuse
{% /tabitem %}

{% tabitem label="Gemini" %}
Pollux, Castor A, Castor B
{% /tabitem %}
{% /tabs %}

_Some exoplanets:_

{% tabs syncKey="constellations" %}
{% tabitem label="Orion" %}
HD 34445 b, Gliese 179 b, Wasp-82 b
{% /tabitem %}

{% tabitem label="Gemini" %}
Pollux b, HAT-P-24b, HD 50554 b
{% /tabitem %}
{% /tabs %}
```

</Fragment>

<Fragment slot="preview">

_Some stars:_

<Tabs syncKey="constellations">
	<TabItem label="Orion">Bellatrix, Rigel, Betelgeuse</TabItem>
	<TabItem label="Gemini">Pollux, Castor A, Castor B</TabItem>
</Tabs>

_Some exoplanets:_

<Tabs syncKey="constellations">
	<TabItem label="Orion">HD 34445 b, Gliese 179 b, Wasp-82 b</TabItem>
	<TabItem label="Gemini">Pollux b, HAT-P-24b, HD 50554 b</TabItem>
</Tabs>

</Fragment>

</Preview>

### Add icons to tabs

Include an icon in a tab item using the [`icon`](#icon) attribute set to the name of [one of Starlight’s built-in icons](/reference/icons/#all-icons) to display an icon next to the label.

<Preview>

```mdx /icon="\w+"/
import { Tabs, TabItem } from '@astrojs/starlight/components';

<Tabs>
	<TabItem label="Stars" icon="star">
		Sirius, Vega, Betelgeuse
	</TabItem>
	<TabItem label="Moons" icon="moon">
		Io, Europa, Ganymede
	</TabItem>
</Tabs>
```

<Fragment slot="markdoc">

```markdoc /icon="\w+"/
{% tabs %}
{% tabitem label="Stars" icon="star" %}
Sirius, Vega, Betelgeuse
{% /tabitem %}

{% tabitem label="Moons" icon="moon" %}
Io, Europa, Ganymede
{% /tabitem %}
{% /tabs %}
```

</Fragment>

<Tabs slot="preview">
	<TabItem label="Stars" icon="star">
		Sirius, Vega, Betelgeuse
	</TabItem>
	<TabItem label="Moons" icon="moon">
		Io, Europa, Ganymede
	</TabItem>
</Tabs>

</Preview>

## `<Tabs>` Props

**Implementation:** [`Tabs.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Tabs.astro)

The `<Tabs>` component groups multiple `<TabItem>` components together and accepts the following props:

### `syncKey`

**type:** `string`

A key used to keep multiple tab groups synchronized across multiple pages.

## `<TabItem>` Props

**Implementation:** [`TabItem.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/TabItem.astro)

A set of tabs is composed of tab items, each with the following props:

### `label`

**required**  
**type:** `string`

A tab item must include a `label` attribute set to the text that will be displayed in the tab.

### `icon`

**type:** `string`

Each tab item can include an `icon` attribute set to the name of [one of Starlight’s built-in icons](/reference/icons/#all-icons) to display an icon next to the label.


================================================
FILE: docs/src/content/docs/components/using-components.mdx
================================================
---
title: Using Components
description: Using components in MDX and Markdoc with Starlight.
sidebar:
  order: 1
---

Components let you easily reuse a piece of UI or styling consistently.
Examples might include a link card or a YouTube embed.
Starlight supports the use of components in [MDX](https://mdxjs.com/) and [Markdoc](https://markdoc.dev/) files and provides some common components for you to use.

[Learn more about building components in the Astro Docs](https://docs.astro.build/en/basics/astro-components/).

## Using a component in MDX

You can use a component by importing it into your MDX file and then rendering it as a JSX tag.
These look like HTML tags but start with an uppercase letter matching the name in your `import` statement:

```mdx
---
# src/content/docs/example.mdx
title: Welcome to my docs
---

import { Icon } from '@astrojs/starlight/components';
import CustomCard from '../../components/CustomCard.astro';

<Icon name="open-book" />

<CustomCard>Components can also contain **nested content**.</CustomCard>
```

Because Starlight is powered by Astro, you can add support for components built with any [supported UI framework (React, Preact, Svelte, Vue, Solid, and Alpine)](https://docs.astro.build/en/guides/framework-components/) in your MDX files.
Learn more about [using components in MDX](https://docs.astro.build/en/guides/integrations-guide/mdx/#using-components-in-mdx) in the Astro docs.

## Using a component in Markdoc

Add support for authoring content in Markdoc by following our [Markdoc set-up guide](/guides/authoring-content/#markdoc).

Using the Starlight Markdoc preset, you can use Starlight’s built-in components with Markdoc’s `{% %}` tag syntax.
Unlike MDX, components in Markdoc do not need to be imported.
The following example renders Starlight’s [card component](/components/cards/) in a Markdoc file:

```markdoc
---
# src/content/docs/example.mdoc
title: Welcome to my docs
---

{% card title="Stars" icon="star" %}
Sirius, Vega, Betelgeuse
{% /card %}
```

See the [Astro Markdoc integration documentation](https://docs.astro.build/en/guides/integrations-guide/markdoc/#render-components) for more information on how to use components in Markdoc files.

## Built-in components

Starlight provides built-in components for common documentation use cases.
These components are available from the `@astrojs/starlight/components` package in MDX files and from the [Starlight Markdoc preset](/guides/authoring-content/#markdoc) in Markdoc files.

See the sidebar for a list of available components and how to use them.

## Compatibility with Starlight’s styles

Starlight applies default styling to your Markdown content, for example, adding margin between elements.
If these styles conflict with your component’s appearance, set the `not-content` class on your component to disable them.

```astro 'class="not-content"'
---
// src/components/Example.astro
---

<div class="not-content">
	<p>Not impacted by Starlight’s default content styling.</p>
</div>
```

## Component props

Use the [`ComponentProps`](https://docs.astro.build/en/guides/typescript/#componentprops-type) type from `astro/types` to reference the `Props` accepted by a component even if they are not exported by the component itself.
This can be helpful when wrapping or extending an existing component.

The following example uses `ComponentProps` to get the type of the props accepted by Starlight’s built-in `Badge` component:

```astro
---
// src/components/Example.astro
import type { ComponentProps } from 'astro/types';
import { Badge } from '@astrojs/starlight/components';

type BadgeProps = ComponentProps<typeof Badge>;
---
```


================================================
FILE: docs/src/content/docs/da/404.md
================================================
---
title: Ikke Fundet
template: splash
editUrl: false
lastUpdated: false
hero:
  title: '404'
  tagline: <strong>Houston, vi har et problem.</strong> Vi kunne ikke finde den side.<br>Check URL'en eller prøv at bruge søgefeltet.
  actions:
    - text: Gå til hjem
      icon: right-arrow
      link: /da/
      variant: primary
---


================================================
FILE: docs/src/content/docs/da/index.mdx
================================================
---
title: Starlight 🌟 Byg dokumentationssider med Astro
description: Starlight hjælper dig med at bygge smukke og hurtige dokumentationssider med Astro.
template: splash
editUrl: false
lastUpdated: false
hero:
  title: Få din dokumentation til at skinne med Starlight
  tagline: Alt du har brug for, for at bygge en skindende dokumentationsside. Hurtig, tilgængelig og nem at bruge.
  image:
    file: ~/assets/hero-star.webp
  actions:
    - text: Kom igang
      icon: right-arrow
      link: /da/getting-started/
    - text: Se på GitHub
      icon: external
      variant: minimal
      link: https://github.com/withastro/starlight
---

import { CardGrid, Card } from '@astrojs/starlight/components';
import AboutAstro from '~/components/about-astro.astro';

<CardGrid stagger>
	<Card title="Documentation, der begejstrer" icon="open-book">
		Inkluderer: Sidenavigation, søg, internationalisering, SEO, nem at læse
		typografi, kodefremhævning, mørk tilstand og mere.
	</Card>
	<Card title="Drevet af Astro" icon="rocket">
		Udnyt den fulde kraft og udevne af Astro. Udvid Starlight med dine yndlings
		Astro integrationer og biblioteker
	</Card>
	<Card title="Markdown, Markdoc og MDX" icon="document">
		Anvend dit yndlings markup sprog. Starlight giver dig indbygget
		Frontmatter-validering med TypeScript type-sikkerhed.
	</Card>
	<Card title="Anvend dine egne UI-komponenter" icon="puzzle">
		Starlight ships as a framework-agnostic, complete docs solution. Extend with
		React, Vue, Svelte, Solid, and more. Starlight bliver leveret som en fuldent
		dokumentations-løsning, der er ligeglad, med hvilket framework du bruger.
		Udvid med React, Vue, Svelte, Solid, og mere.
	</Card>
</CardGrid>

<AboutAstro title="Bragt til dig af">
Astro er et all-in-one web framework, der er bygget til udevne.
Hiv dit indhold ned fra hvor som helst og indsæt det hvor som helst, alt sammen drevet af dine yndlings UI-komponenter og biblioteker.

[Lær mere om Astro](https://astro.build/)

</AboutAstro>


================================================
FILE: docs/src/content/docs/de/404.md
================================================
---
title: Nicht gefunden
template: splash
editUrl: false
lastUpdated: false
hero:
  title: '404'
  tagline: <strong>Houston, wir haben ein Problem.</strong> Wir konnten diese Seite nicht finden.<br>Prüfe die URL oder verwende die Suchleiste.
  actions:
    - text: Zur Startseite
      icon: right-arrow
      link: /de/
      variant: primary
---


================================================
FILE: docs/src/content/docs/de/components/asides.mdx
================================================
---
title: Nebenbemerkungen
description: Lerne, wie du in Starlight zusätzliche Informationen neben dem Hauptinhalt einer Seite anzeigen kannst.
---

import { Aside } from '@astrojs/starlight/components';

Um sekundäre Informationen neben dem Hauptinhalt einer Seite anzuzeigen, verwende die Komponente `<Aside>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<Aside slot="preview">
    Füge nicht wesentliche, ergänzende Informationen in ein `<Aside>`.
</Aside>

</Preview>

## Import

```tsx
import { Aside } from '@astrojs/starlight/components';
```

## Verwendung

Zeige eine Nebenbemerkung (auch bekannt als „Hinweise“, „Ermahnungen“ oder „Aufrufe“) mit Hilfe der Komponente `<Aside>`.

Ein `<Aside>` kann ein optionales [`type`](#type) Attribute haben, welches die Farbe, das Symbol und den Standardtitel der Nebenbemerkung steuert.

<Preview>

````mdx
import { Aside } from '@astrojs/starlight/components';

<Aside>Einige Inhalte am Rande.</Aside>

<Aside type="caution">Einige warnende Inhalte.</Aside>

<Aside type="tip">

Auch andere Inhalte werden durch Nebenbemerkungen unterstützt.

```js
// Ein Codeschnipsel zum Beispiel.
```

</Aside>

<Aside type="danger">Gib dein Passwort nie an Dritte weiter!</Aside>
````

<Fragment slot="markdoc">

````markdoc
{% aside %}
Einige Inhalte am Rande.
{% /aside %}

{% aside type="caution" %}
Einige warnende Inhalte.
{% /aside %}

{% aside type="tip" %}
Auch andere Inhalte werden durch Nebenbemerkungen unterstützt.

```js
// Ein Codeschnipsel zum Beispiel.
```
{% /aside %}

{% aside type="danger" %}
Gib dein Passwort nie an Dritte weiter!
{% /aside %}
````

</Fragment>

<Fragment slot="preview">

    <Aside>Einige Inhalte am Rande.</Aside>

    <Aside type="caution">Einige warnende Inhalte.</Aside>

    <Aside type="tip">

    Auch andere Inhalte werden durch Nebenbemerkungen unterstützt.

    ```js
    // Ein Codeschnipsel zum Beispiel.
    ```

    </Aside>

    <Aside type="danger">Gib dein Passwort nie an Dritte weiter!</Aside>

</Fragment>

</Preview>

Starlight bietet auch eine benutzerdefinierte Syntax für die Darstellung von Nebenbemerkungen in Markdown und MDX als Alternative zur `<Aside>` Komponente.
Siehe den Leitfaden [„Inhalte in Markdown verfassen“](/de/guides/authoring-content/#nebenbemerkungen) für Details zu dieser Syntax.

### Benutzerdefinierte Titel verwenden

Überschreibe die voreingestellten Überschriften der Nebenbemerkungen mit dem Attribut [`title`](#title).

<Preview>

```mdx 'title="Aufgepasst!"'
import { Aside } from '@astrojs/starlight/components';

<Aside type="caution" title="Aufgepasst!">
	Ein Warnhinweis *mit* einem benutzerdefinierten Titel.
</Aside>
```

<Fragment slot="markdoc">

```markdoc 'title="Aufgepasst!"'
{% aside type="caution" title="Aufgepasst!" %}
Ein Warnhinweis *mit* einem benutzerdefinierten Titel.
{% /aside %}
```

</Fragment>

<Aside slot="preview" type="caution" title="Aufgepasst!">
	Ein Warnhinweis *mit* einem benutzerdefinierten Titel.
</Aside>

</Preview>

### Benutzerdefinierte Symbole verwenden

Überschreibe die Standard-Symbole der Nebenbemerkungen, indem du das Attribut [`icon`](#icon) auf den Namen [eines der in Starlight integrierten Symbole](/de/reference/icons/#alle-symbole) setzt.

<Preview>

```mdx 'icon="starlight"'
import { Aside } from '@astrojs/starlight/components';

<Aside type="tip" icon="starlight">
	Ein Hinweis *mit* einem benutzerdefinierten Symbol.
</Aside>
```

<Fragment slot="markdoc">

```markdoc 'icon="starlight"'
{% aside type="tip" icon="starlight" %}
Ein Hinweis *mit* einem benutzerdefinierten Symbol.
{% /aside %}
```

</Fragment>

<Aside slot="preview" type="tip" icon="starlight">
	Ein Hinweis *mit* einem benutzerdefinierten Symbol.
</Aside>

</Preview>

## `<Aside>`-Eigenschaften

**Implementation:** [`Aside.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Aside.astro)

Die Komponente `<Aside>` akzeptiert die folgenden Eigenschaften:

### `type`

**Typ:** `'note' | 'tip' | 'caution' | 'danger'`  
**Standard:** `'note'`

Die Art der Nebenbemerkung, die angezeigt werden soll:

- `note`-Hinweise (die Standardeinstellung) sind blau und zeigen ein Informationssymbol an.
- `tip`-Hinweise sind violett und zeigen ein Raketensymbol an.
- `caution`-Hinweise sind gelb und zeigen ein dreieckiges Warnsymbol an.
- `danger`-Hinweise sind rot und zeigen ein achteckiges Warnsymbol an.

### `title`

**Typ:** `string`

Die Überschrift der anzuzeigenden Nebenbemerkung.
Wenn `title` nicht gesetzt ist, wird der Standardtitel für den aktuellen `type` der Nebenbemerkung verwendet.

### `icon`

**Typ:** [`StarlightIcon`](/de/reference/icons/#starlighticon-typ)

Eine Nebenbemerkung kann ein `icon`-Attribut enthalten, das auf den Namen [eines der in Starlight integrierten Symbole](/de/reference/icons/#alle-symbole) gesetzt ist.


================================================
FILE: docs/src/content/docs/de/components/badges.mdx
================================================
---
title: Abzeichen
description: Lerne, wie du in Starlight Abzeichen verwenden kannst, um zusätzliche Informationen anzuzeigen.
---

import { Badge } from '@astrojs/starlight/components';

Um wenige Informationen, wie z. B. einen Status oder eine Kategorie, anzuzeigen, verwende die Komponente `<Badge>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<Badge slot="preview" text="Neu" />

</Preview>

## Import

```tsx
import { Badge } from '@astrojs/starlight/components';
```

## Verwendung

Zeige ein Abzeichen mit der Komponente `<Badge>` an und übergib den Inhalt, den du anzeigen möchtest, an das Attribut [`text`](#text) der Komponente `<Badge>`.

Standardmäßig wird für das Abzeichen die Akzentfarbe des Themes deiner Website verwendet.
Um eine eingebaute Abzeichen-Farbe zu verwenden, setze das Attribut [`variant`](#variant) auf einen der unterstützten Werte.

<Preview>

```mdx
import { Badge } from '@astrojs/starlight/components';

- <Badge text="Hinweis" variant="note" />
- <Badge text="Erfolg" variant="success" />
- <Badge text="Tipp" variant="tip" />
- <Badge text="Warnung" variant="caution" />
- <Badge text="Gefahr" variant="danger" />
```

<Fragment slot="markdoc">

```markdoc
- {% badge text="Hinweis" variant="note" /%}
- {% badge text="Erfolg" variant="success" /%}
- {% badge text="Tipp" variant="tip" /%}
- {% badge text="Warnung" variant="caution" /%}
- {% badge text="Gefahr" variant="danger" /%}
```

</Fragment>

<Fragment slot="preview">
	- <Badge text="Hinweis" variant="note" />
	- <Badge text="Erfolg" variant="success" />
	- <Badge text="Tipp" variant="tip" />
	- <Badge text="Warnung" variant="caution" />
	- <Badge text="Gefahr" variant="danger" />
</Fragment>

</Preview>

### Verschiedene Größen verwenden

Verwende das Attribut [`size`](#size), um die Größe des Abzeichentextes zu steuern.

<Preview>

```mdx /size="\w+"/
import { Badge } from '@astrojs/starlight/components';

- <Badge text="Neu" size="small" />
- <Badge text="Neu und verbessert" size="medium" />
- <Badge text="Neu, verbessert und größer" size="large" />
```

<Fragment slot="markdoc">

```markdoc /size="\w+"/
- {% badge text="Neu" size="small" /%}
- {% badge text="Neu und verbessert" size="medium" /%}
- {% badge text="Neu, verbessert und größer" size="large" /%}
```

</Fragment>

<Fragment slot="preview">
	- <Badge text="Neu" size="small" />
	- <Badge text="Neu und verbessert" size="medium" />
	- <Badge text="Neu, verbessert und größer" size="large" />
</Fragment>

</Preview>

### Abzeichen anpassen

Passe Abzeichen an, indem du andere `<span>`-Attribute wie `class` oder `style` mit benutzerdefiniertem CSS verwendest.

<Preview>

```mdx "style={{ fontStyle: 'italic' }}"
import { Badge } from '@astrojs/starlight/components';

<Badge text="Individuell" variant="success" style={{ fontStyle: 'italic' }} />
```

<Fragment slot="markdoc">

```markdoc 'style="font-style: italic;"'
{% badge text="Individuell" variant="success" style="font-style: italic;" /%}
```

</Fragment>

<Badge
	slot="preview"
	text="Individuell"
	variant="success"
	style={{ fontStyle: 'italic' }}
/>

</Preview>

## `<Badge>`-Eigenschaften

**Implementation:** [`Badge.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Badge.astro)

Die `<Badge>`-Komponente akzeptiert die folgenden Eigenschaften und auch alle [anderen `<span>`-Attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes):

### `text`

**Erforderlich**  
**Typ:** `string`

Der Textinhalt, der in dem Abzeichen angezeigt werden soll.

### `variant`

**Typ:** `'note' | 'danger' | 'success' | 'caution' | 'tip' | 'default'`  
**Standard:** `'default'`

Die zu verwendende Farbvariante des Abzeichens: `note` (blau), `tip` (lila), `danger` (rot), `caution` (orange), `success` (grün) oder `default` (Akzentfarbe des Themes).

### `size`

**Typ:** `'small' | 'medium' | 'large'`

Bestimmt die Größe des anzuzeigenden Abzeichens.


================================================
FILE: docs/src/content/docs/de/components/card-grids.mdx
================================================
---
title: Kartenraster
description: Erfahre, wie du in Starlight mehrere Karten in ein Raster packen kannst.
sidebar:
  order: 4
---

import { Card, CardGrid, LinkCard } from '@astrojs/starlight/components';

Um mehrere [`<Card>`](/de/components/cards/) oder [`<LinkCard>`](/de/components/link-cards/) Komponenten in einem Raster zu verpacken, verwende die Komponente `<CardGrid>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<CardGrid slot="preview">
	<Card title="Sterne" icon="star">
		Sirius, Wega, Betelgeuse
	</Card>
	<Card title="Monde" icon="moon">
		Io, Europa, Ganymed
	</Card>
</CardGrid>

</Preview>

## Import

```tsx
import { CardGrid } from '@astrojs/starlight/components';
```

## Verwendung

### Karten gruppieren

Zeige mehrere [`<Card>`](/de/components/cards/) Komponenten nebeneinander an, wenn genügend Platz vorhanden ist, indem du sie mit der `<CardGrid>` Komponente gruppierst.

<Preview>

```mdx {3,10}
import { Card, CardGrid } from '@astrojs/starlight/components';

<CardGrid>
	<Card title="Schau dir das an" icon="open-book">
		Interessante Inhalte, die du hervorheben möchtest.
	</Card>
	<Card title="Anderer Inhalt" icon="information">
		Weitere Informationen, die du weitergeben möchtest.
	</Card>
</CardGrid>
```

<Fragment slot="markdoc">

```markdoc {1,9}
{% cardgrid %}
{% card title="Schau dir das an" icon="open-book" %}
Interessante Inhalte, die du hervorheben möchtest.
{% /card %}

{% card title="Anderer Inhalt" icon="information" %}
Weitere Informationen, die du weitergeben möchtest.
{% /card %}
{% /cardgrid %}
```

</Fragment>

<CardGrid slot="preview">
	<Card title="Schau dir das an" icon="open-book">
		Interessante Inhalte, die du hervorheben möchtest.
	</Card>
	<Card title="Anderer Inhalt" icon="information">
		Weitere Informationen, die du weitergeben möchtest.
	</Card>
</CardGrid>

</Preview>

### Link-Karten gruppieren

Zeige mehrere [`<LinkCard>`](/de/components/link-cards/) Komponenten nebeneinander an, wenn genügend Platz vorhanden ist, indem du sie mit der `<CardGrid>` Komponente gruppierst.

<Preview>

```mdx {3,6}
import { LinkCard, CardGrid } from '@astrojs/starlight/components';

<CardGrid>
	<LinkCard title="Markdown verfassen" href="/de/guides/authoring-content/" />
	<LinkCard title="Komponenten" href="/de/components/using-components/" />
</CardGrid>
```

<Fragment slot="markdoc">

```markdoc {1,5}
{% cardgrid %}
{% linkcard title="Markdown verfassen" href="/de/guides/authoring-content/" /%}

{% linkcard title="Komponenten" href="/de/components/using-components/" /%}
{% /cardgrid %}
```

</Fragment>

<CardGrid slot="preview">
	<LinkCard title="Markdown verfassen" href="/de/guides/authoring-content/" />
	<LinkCard title="Komponenten" href="/de/components/using-components/" />
</CardGrid>

</Preview>

### Karten staffeln

Verschiebe die zweite Spalte des Rasters vertikal, um es optisch interessanter zu gestalten, indem du das Attribut [`stagger`](#stagger) zur Komponente `<CardGrid>` hinzufügst.

Dieses Attribut ist auf deiner Homepage nützlich, um die wichtigsten Merkmale deines Projekts anzuzeigen.

<Preview>

```mdx "stagger"
import { Card, CardGrid } from '@astrojs/starlight/components';

<CardGrid stagger>
	<Card title="Schau dir das an" icon="open-book">
		Interessante Inhalte, die du hervorheben möchtest.
	</Card>
	<Card title="Anderer Inhalt" icon="information">
		Weitere Informationen, die du weitergeben möchtest.
	</Card>
</CardGrid>
```

<Fragment slot="markdoc">

```markdoc "stagger=true"
{% cardgrid stagger=true %}
{% card title="Schau dir das an" icon="open-book" %}
Interessante Inhalte, die du hervorheben möchtest.
{% /card %}

{% card title="Anderer Inhalt" icon="information" %}
Weitere Informationen, die du weitergeben möchtest.
{% /card %}
{% /cardgrid %}
```

</Fragment>

<CardGrid slot="preview" stagger>
	<Card title="Schau dir das an" icon="open-book">
		Interessante Inhalte, die du hervorheben möchtest.
	</Card>
	<Card title="Anderer Inhalt" icon="information">
		Weitere Informationen, die du weitergeben möchtest.
	</Card>
</CardGrid>

</Preview>

## `<CardGrid>`-Eigenschaften

**Implementation:** [`CardGrid.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/CardGrid.astro)

Die Komponente `<CardGrid>` akzeptiert die folgenden Eigenschaften:

### `stagger`

**Typ:** `boolean`

Legt fest, ob die Karten im Raster gestaffelt werden sollen oder nicht.


================================================
FILE: docs/src/content/docs/de/components/cards.mdx
================================================
---
title: Karten
description: Lerne, wie du in Starlight Karten verwenden kannst, um Inhalte in einer Box anzuzeigen.
sidebar:
  order: 2
---

import { Card } from '@astrojs/starlight/components';

Um Inhalte in einer Box anzuzeigen, die den Stilen von Starlight entspricht, verwende die Komponente `<Card>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<Card slot="preview" title="Monde" icon="moon">
	Io, Europa, Ganymed
</Card>

</Preview>

## Import

```tsx
import { Card } from '@astrojs/starlight/components';
```

## Verwendung

Zeige eine Karte an, indem du die Komponente `<Card>` verwendest und einen [`title`](#title) für die Karte angibst.

<Preview>

```mdx
import { Card } from '@astrojs/starlight/components';

<Card title="Schau dir das an">
	Interessante Inhalte, die du hervorheben möchtest.
</Card>
```

<Fragment slot="markdoc">

```markdoc
{% card title="Schau dir das an" %}
Interessante Inhalte, die du hervorheben möchtest.
{% /card %}
```

</Fragment>

<Card slot="preview" title="Schau dir das an">
	Interessante Inhalte, die du hervorheben möchtest.
</Card>

</Preview>

### Hinzufügen von Symbolen zu Karten

Füge ein Symbol in eine Karte ein, indem du das Attribut [`icon`](#icon) auf den Namen [eines von Starlights eingebauten Symbolen](/de/reference/icons/#alle-symbole) setzt.

<Preview>

```mdx 'icon="star"'
import { Card } from '@astrojs/starlight/components';

<Card title="Sterne" icon="star">
	Sirius, Wega, Betelgeuse
</Card>
```

<Fragment slot="markdoc">

```markdoc 'icon="star"'
{% card title="Sterne" icon="star" %}
Sirius, Wega, Betelgeuse
{% /card %}
```

</Fragment>

<Card slot="preview" title="Sterne" icon="star">
	Sirius, Wega, Betelgeuse
</Card>

</Preview>

### Karten gruppieren

Zeige mehrere Karten nebeneinander an, wenn genügend Platz vorhanden ist, indem du sie mit der Komponente [`<CardGrid>`](/de/components/card-grids/) gruppierst.
Siehe die Anleitung [„Karten gruppieren“](/de/components/card-grids/#karten-gruppieren) für ein Beispiel.

## `<Card>`-Eigenschaften

**Implementation:** [`Card.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Card.astro)

Die Komponente `<Card>` akzeptiert die folgenden Eigenschaften:

### `title`

**Erforderlich**  
**Typ:** `string`

Der Titel der anzuzeigenden Karte.

### `icon`

**Typ:** `string`

Eine Karte kann ein `icon`-Attribut enthalten, das auf den Namen [eines von Starlights eingebauten Symbolen](/de/reference/icons/#alle-symbole) gesetzt ist.


================================================
FILE: docs/src/content/docs/de/components/code.mdx
================================================
---
title: Code
description: Erfahre, wie du syntaxmarkierten Code in Starlight ohne Markdown-Codeblöcke anzeigen kannst.
---

import { Code } from '@astrojs/starlight/components';

Die Komponente `<Code>` gibt syntaktisch hervorgehobenen Code wieder.
Sie ist nützlich, wenn die Verwendung eines [Markdown-Codeblocks](/de/guides/authoring-content/#codeblöcke) nicht möglich ist, zum Beispiel, um Daten aus externen Quellen wie Dateien, Datenbanken oder APIs darzustellen.

import Preview from '~/components/component-preview.astro';

<Preview>

<Code
	slot="preview"
	code={`## Willkommen

Hallo aus dem **Weltraum**!`}
lang="md"
title="example.md"
ins={3}
/>

</Preview>

## Import

```tsx
import { Code } from '@astrojs/starlight/components';
```

## Verwendung

Verwende die Komponente `<Code>`, um Code mit hervorgehobener Syntax darzustellen, z. B. bei der Anzeige von Code aus externen Quellen.

Siehe die [Ausdrucksstarker Code „Code Komponente“ Dokumentation](https://expressive-code.com/key-features/code-component/) für alle Details über die Verwendung der `<Code>` Komponente und die Liste der verfügbaren Eigenschaften.

<Preview>

```mdx
import { Code } from '@astrojs/starlight/components';

export const exampleCode = `console.log('Dies könnte aus einer Datei oder einem CMS stammen!');`;
export const fileName = 'example.js';
export const highlights = ['Datei', 'CMS'];

<Code code={exampleCode} lang="js" title={fileName} mark={highlights} />
```

<Fragment slot="markdoc">

```markdoc
{% code
   code="console.log('Dies könnte aus einer Datei oder einem CMS stammen!');"
   lang="js"
   title="example.js"
   meta="'Datei' 'CMS'" /%}
```

</Fragment>

export const exampleCode = `console.log('Dies könnte aus einer Datei oder einem CMS stammen!');`;
export const fileName = 'example.js';
export const highlights = ['Datei', 'CMS'];

<Code
	slot="preview"
	code={exampleCode}
	lang="js"
	title={fileName}
	mark={highlights}
/>

</Preview>

### Importierten Code anzeigen

Verwende in MDX-Dateien und Astro-Komponenten [Vites Importsuffix `?raw`](https://de.vite.dev/guide/assets#importieren-von-assets-als-zeichenfolge), um jede Codedatei als Zeichenfolge zu importieren.
Du kannst diese importierte Zeichenfolge dann an die Komponente `<Code>` übergeben, um sie auf deiner Seite einzubinden.

<Preview>

```mdx "?raw"
# src/content/docs/example.mdx

import { Code } from '@astrojs/starlight/components';
import importedCode from '/tsconfig.json?raw';

<Code code={importedCode} lang="json" title="tsconfig.json" />
```

import importedCode from '../../../../../../examples/basics/tsconfig.json?raw';

<Code slot="preview" code={importedCode} lang="json" title="tsconfig.json" />

</Preview>

## `<Code>`-Eigenschaften

**Implementation:** [`Code.astro`](https://github.com/expressive-code/expressive-code/blob/main/packages/astro-expressive-code/components/Code.astro)

Die `<Code>`-Komponente akzeptiert alle in der [Ausdrucksstarker Code Dokumentation „Code Komponente“](https://expressive-code.com/key-features/code-component/#available-props) dokumentierten Eigenschaften.


================================================
FILE: docs/src/content/docs/de/components/file-tree.mdx
================================================
---
title: Verzeichnisbaum
description: Lerne, wie du die Struktur eines Verzeichnisses mit Dateisymbolen und einklappbaren Unterverzeichnissen in Starlight anzeigen kannst.
---

import { FileTree } from '@astrojs/starlight/components';

Um die Struktur eines Verzeichnisses mit Dateisymbolen und einklappbaren Unterverzeichnissen anzuzeigen, verwende die Komponente `<FileTree>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<FileTree slot="preview">

- astro.config.mjs eine **wichtige** Datei
- package.json
- README.md
- src
  - components
    - **Header.astro**
  - …
- pages/

</FileTree>

</Preview>

## Import

```tsx
import { FileTree } from '@astrojs/starlight/components';
```

## Verwendung

Zeige einen Dateibaum mit Dateisymbolen und zusammenklappbaren Unterverzeichnissen unter Verwendung der Komponente `<FileTree>` an.

Gib die Struktur deiner Dateien und Verzeichnisse mit einer [ungeordneten Markdown-Liste](https://www.markdownguide.org/basic-syntax/#unordered-lists) innerhalb von `<FileTree>` an.
Erstelle ein Unterverzeichnis mit einer verschachtelten Liste oder füge ein `/` am Ende eines Listenelements hinzu, um es als Verzeichnis ohne spezifischen Inhalt darzustellen.

<Preview>

```mdx
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- astro.config.mjs
- package.json
- src
  - components
    - Header.astro
    - Title.astro
  - pages/

</FileTree>
```

<Fragment slot="markdoc">

```markdoc
{% filetree %}
- astro.config.mjs
- package.json
- src
  - components
    - Header.astro
    - Title.astro
  - pages/
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- astro.config.mjs
- package.json
- src
  - components
    - Header.astro
    - Title.astro
  - pages/

</FileTree>

</Preview>

### Einträge hervorheben

Hebe eine Datei oder ein Verzeichnis hervor, indem du seinen Namen fett druckst, z. B. `**README.md**`.

<Preview>

```mdx {7}
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src
  - components
    - **Header.astro**
    - Title.astro

</FileTree>
```

<Fragment slot="markdoc">

```markdoc {4}
{% filetree %}
- src
  - components
    - **Header.astro**
    - Title.astro
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- src
  - components
    - **Header.astro**
    - Title.astro

</FileTree>

</Preview>

### Kommentare hinzufügen

Füge einen Kommentar zu einer Datei oder einem Verzeichnis hinzu, indem du nach dem Namen weiteren Text hinzufügst.
Inline-Markdown-Formatierung wie Fett- und Kursivdruck wird in Kommentaren unterstützt.

<Preview>

```mdx {7}
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src
  - components
    - Header.astro eine **wichtige** Datei
    - Title.astro

</FileTree>
```

<Fragment slot="markdoc">

```markdoc {4}
{% filetree %}
- src
  - components
    - Header.astro eine **wichtige** Datei
    - Title.astro
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- src
  - components
    - Header.astro eine **wichtige** Datei
    - Title.astro

</FileTree>

</Preview>

### Platzhalter hinzufügen

Füge Platzhalterdateien und Verzeichnisse hinzu, indem du entweder `...` oder `…` als Namen verwendest.
Dies kann nützlich sein, um einem Leser zu zeigen, dass ein Ordner mehr Elemente enthalten soll, ohne sie alle explizit anzugeben.

<Preview>

```mdx {8}
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src
  - components
    - Header.astro
    - …

</FileTree>
```

<Fragment slot="markdoc">

```markdoc {5}
{% filetree %}
- src
  - components
    - Header.astro
    - …
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- src
  - components
    - Header.astro
    - …

</FileTree>

</Preview>

### Sonderzeichen umgehen

Sichere Sonderzeichen wie Unterstriche oder Leerzeichen in Dateinamen, indem du den Dateinamen in Code-Backticks einschließt.

<Preview>

```mdx
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- `__init__.py`
- `Hallo Welt.txt`
- **`LIES MICH ZUERST.md`**

</FileTree>
```

<Fragment slot="markdoc">

```markdoc
{% filetree %}
- `__init__.py`
- `Hallo Welt.txt`
- **`LIES MICH ZUERST.md`**
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- `__init__.py`
- `Hallo Welt.txt`
- **`LIES MICH ZUERST.md`**

</FileTree>

</Preview>

## `<FileTree>`-Eigenschaften

**Implementation:** [`FileTree.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/FileTree.astro)

Die Komponente `<FileTree>` akzeptiert keine Eigenschaften.


================================================
FILE: docs/src/content/docs/de/components/icons.mdx
================================================
---
title: Symbole
description: Erfahre, wie du Symbole in Starlight anzeigen kannst.
---

import { Icon } from '@astrojs/starlight/components';

Um Symbole aus Starlights [eingebautem Symbol-Set](/de/reference/icons/#alle-symbole) anzuzeigen, verwende die `<Icon>` Komponente.

import Preview from '~/components/component-preview.astro';

<Preview>

<Icon
	slot="preview"
	name="open-book"
	color="var(--sl-color-text-accent)"
	size="4rem"
/>

</Preview>

## Import

```tsx
import { Icon } from '@astrojs/starlight/components';
```

## Verwendung

Zeigt ein Symbol mit der Komponente `<Icon>` an.
Ein Symbole benötigt einen [`name`](#name), der auf [eines der in Starlight eingebauten Symbolen](/de/reference/icons/#alle-symbole) gesetzt ist, und kann optional ein [`label`](#label) enthalten, um Kontext für Screenreader zu liefern.

<Preview>

```mdx
import { Icon } from '@astrojs/starlight/components';

<Icon name="star" />
<Icon name="starlight" label="Das Starlight-Logo" />
```

<Fragment slot="markdoc">

```markdoc
{% icon name="star" /%}
{% icon name="starlight" label="Das Starlight-Logo" /%}
```

</Fragment>

<Fragment slot="preview">
	<Icon name="star" />
	<Icon name="starlight" label="Das Starlight-Logo" />
</Fragment>

</Preview>

### Anpassen von Symbolen

Die Attribute [`size`](#size) und [`color`](#color) können verwendet werden, um das Aussehen des Symbols mit CSS-Einheiten und Farbwerten anzupassen.
Das Attribut [`class`](#class) kann verwendet werden, um dem Symbol eigene CSS-Klassen hinzuzufügen.

<Preview>

```mdx
import { Icon } from '@astrojs/starlight/components';

<Icon name="star" color="goldenrod" size="2rem" />
<Icon name="rocket" color="var(--sl-color-text-accent)" />
```

<Fragment slot="markdoc">

```markdoc
{% icon name="star" color="goldenrod" size="2rem" /%}
{% icon name="rocket" color="var(--sl-color-text-accent)" /%}
```

</Fragment>

<Fragment slot="preview">
	<Icon name="star" color="goldenrod" size="2rem" />
	<Icon name="rocket" color="var(--sl-color-text-accent)" />
</Fragment>

</Preview>

## `<Icon>`-Eigenschaften

**Implementation:** [`Icon.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Icon.astro)

Die Komponente `<Icon>` akzeptiert die folgenden Eigenschaften:

### `name`

**Erforderlich**  
**Typ:** [`StarlightIcon`](/de/reference/icons/#starlighticon-typ)

Der Name des anzuzeigenden Symbols wird auf [eines der in Starlight integrierten Symbole](/de/reference/icons/#alle-symbole) gesetzt.

### `label`

**Typ:** `string`

Eine optionale Beschriftung, die den Kontext für unterstützende Technologien wie Bildschirm­lesegeräte liefert.

Wenn `label` nicht gesetzt ist, wird das Symbol von assistiven Technologien vollständig ausgeblendet.
In diesem Fall ist darauf zu achten, dass der Kontext auch ohne das Symbol verständlich ist.
Ein Link, der nur das Symbol enthält, **muss** das Attribut `label` enthalten, um zugänglich zu sein, aber wenn ein Link Text enthält und das Symbol rein dekorativ ist, kann es sinnvoll sein, das `label` wegzulassen.

### `size`

**Typ:** `string`

Die Größe des Symbols in CSS-Einheiten.

### `color`

**Typ:** `string`

Die Farbe des Symbols unter Verwendung eines CSS-Farbwerts.

### `class`

**Typ:** `string`

Benutzerdefinierte CSS-Klassen, die dem Symbol hinzugefügt werden können.


================================================
FILE: docs/src/content/docs/de/components/link-buttons.mdx
================================================
---
title: Link-Buttons
description: Erfahre, wie du in Starlight Link-Buttons für visuell eindeutige Call-to-Action-Links erstellen.
---

import { LinkButton } from '@astrojs/starlight/components';

Um visuell eindeutige Call-to-Action-Links anzuzeigen, verwende die Komponente `<LinkButton>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<LinkButton slot="preview" href="/de/getting-started/">
	Lies die Dokumentationen
</LinkButton>

</Preview>

## Import

```tsx
import { LinkButton } from '@astrojs/starlight/components';
```

## Verwendung

Verwende die Komponente `<LinkButton>`, um einen visuell eindeutigen Call-to-Action-Link anzuzeigen.
Ein Link-Button ist nützlich, um Nutzer zu den relevantesten oder handlungsrelevanten Inhalten zu leiten und wird häufig auf Landing Pages verwendet.

Ein `<LinkButton>` benötigt ein [`href`](#href) Attribut.
Optional kann das Aussehen des Link-Buttons mit dem Attribut [`variant`](#variant) angepasst werden, das auf `primary` (Standard), `secondary` oder `minimal` gesetzt werden kann.

<Preview>

```mdx
import { LinkButton } from '@astrojs/starlight/components';

<LinkButton href="/de/getting-started/">Los geht's</LinkButton>
<LinkButton href="/de/reference/configuration/" variant="secondary">
	Konfiguration Referenz
</LinkButton>
```

<Fragment slot="markdoc">

```markdoc
{% linkbutton href="/de/getting-started/" %}Los geht's{% /linkbutton %}

{% linkbutton href="/de/reference/configuration/" variant="secondary" %}
Konfiguration Referenz
{% /linkbutton %}
```

</Fragment>

<Fragment slot="preview">
	<LinkButton href="/de/getting-started/">Los geht's</LinkButton>
	<LinkButton href="/de/reference/configuration/" variant="secondary">
		Konfiguration Referenz
	</LinkButton>
</Fragment>

</Preview>

### Hinzufügen von Symbolen zu Link-Buttons

Füge ein Symbol in einen Link-Button ein, indem du das Attribut [`icon`](#icon) auf den Namen [eines von Starlights eingebauten Symbolen](/de/reference/icons/#alle-symbole) setzt.

Das Attribut [`iconPlacement`](#iconplacement) kann verwendet werden, um das Symbol vor dem Text zu platzieren, indem man es auf `start` setzt (Standardwert ist `end`).

<Preview>

```mdx {6-7}
import { LinkButton } from '@astrojs/starlight/components';

<LinkButton
	href="https://docs.astro.build"
	variant="secondary"
	icon="external"
	iconPlacement="start"
>
	Verwandt: Astro
</LinkButton>
```

<Fragment slot="markdoc">

```markdoc {4-5}
{% linkbutton
   href="https://docs.astro.build"
	 variant="secondary"
	 icon="external"
	 iconPlacement="start" %}
Verwandt: Astro
{% /linkbutton %}
```

</Fragment>

<LinkButton
	slot="preview"
	href="https://docs.astro.build"
	variant="secondary"
	icon="external"
	iconPlacement="start"
>
	Verwandt: Astro
</LinkButton>

</Preview>

## `<LinkButton>`-Eigenschaften

**Implementation:** [`LinkButton.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/LinkButton.astro)

Die `<LinkButton>`-Komponente akzeptiert die folgenden Eigenschaften und auch alle [anderen `<a>`-Attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a):

### `href`

**Erforderlich**  
**Typ:** `string`

Die URL, auf die der Link-Button zeigt.

### `variant`

**Typ:** `'primary' | 'secondary' | 'minimal'`  
**Standard:** `'primary'`

Das Aussehen des Link-Button.
Setze auf `primary` für einen auffälligen Call-to-Action-Link mit der Akzentfarbe des Themas, auf `secondary` für einen weniger auffälligen Link oder auf `minimal` für einen Link mit minimalem Styling.

### `icon`

**Typ:** `string`

Ein Link-Button kann ein `icon`-Attribut enthalten, das auf den Namen [eines von Starlights eingebauten Symbolen](/de/reference/icons/#alle-symbole) gesetzt ist.

### `iconPlacement`

**Typ:** `'start' | 'end'`  
**Standard:** `'end'`

Bestimmt die Platzierung des Symbols im Verhältnis zum Text des Link-Buttons.


================================================
FILE: docs/src/content/docs/de/components/link-cards.mdx
================================================
---
title: Link-Karten
description: Erfahre, wie du in Starlight Links prominent als Karten anzeigst.
sidebar:
  order: 3
---

import { LinkCard } from '@astrojs/starlight/components';

Um Links zu verschiedenen Seiten prominent anzuzeigen, verwende die Komponente `<LinkCard>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<LinkCard
	slot="preview"
	title="Starlight anpassen"
	description="Lerne, wie du deine Starlight-Website mit deinem Logo, eigenen Schriftarten, Landing-Page-Design und vielem mehr zu deiner eigenen machen kannst."
	href="/de/guides/customization/"
/>

</Preview>

## Import

```tsx
import { LinkCard } from '@astrojs/starlight/components';
```

## Verwendung

Zeige einen Link mithilfe der Komponente `<LinkCard>` deutlich sichtbar an.
Jede `<LinkCard>` erfodert ein [`title`](#title) und ein [`href`](#href)-Attribut.

<Preview>

```mdx
import { LinkCard } from '@astrojs/starlight/components';

<LinkCard
	title="Inhalte in Markdown verfassen"
	href="/de/guides/authoring-content/"
/>
```

<Fragment slot="markdoc">

```markdoc
{% linkcard title="Inhalte in Markdown verfassen" href="/de/guides/authoring-content/" /%}
```

</Fragment>

<LinkCard
	slot="preview"
	title="Inhalte in Markdown verfassen"
	href="/de/guides/authoring-content/"
/>

</Preview>

### Füge eine Linkbeschreibung hinzu

Füge einer Link-Karte mit dem Attribut [`description`](#description) eine kurze Beschreibung hinzu.

<Preview>

```mdx {6}
import { LinkCard } from '@astrojs/starlight/components';

<LinkCard
	title="Internationalisierung"
	href="/de/guides/i18n/"
	description="Konfiguriere Starlight zur Unterstützung mehrerer Sprachen."
/>
```

<Fragment slot="markdoc">

```markdoc {4}
{% linkcard
   title="Internationalisierung"
	 href="/de/guides/i18n/"
	 description="Konfiguriere Starlight zur Unterstützung mehrerer Sprachen." /%}
```

</Fragment>

<LinkCard
	slot="preview"
	title="Internationalisierung"
	href="/de/guides/i18n/"
	description="Konfiguriere Starlight zur Unterstützung mehrerer Sprachen."
/>

</Preview>

### Gruppiere Link-Karten

Zeige mehrere Link-Karten nebeneinander an, wenn genügend Platz vorhanden ist, indem du sie mit der Komponente [`<CardGrid>`](/de/components/card-grids/) gruppierst.
Ein Beispiel findest du im Handbuch [“Gruppiere Link-Karten”](/de/components/card-grids/#link-karten-gruppieren).

## `<LinkCard>`-Eigenschaften

**Implementation:** [`LinkCard.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/LinkCard.astro)

Die Komponente `<LinkCard>` akzeptiert die folgenden Eigenschaften sowie alle anderen [`<a>`-Elementattribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a):

### `title`

**Erforderlich**  
**Typ:** `string`

Der Titel der anzuzeigenden Link-Karte.

### `href`

**Erforderlich**  
**Typ:** `string`

Die URL, auf die bei Interaktion mit der Karte verwiesen werden soll.

### `description`

**Typ:** `string`

Eine optionale Beschreibung, welche unter dem Titel angezeigt wird.


================================================
FILE: docs/src/content/docs/de/components/steps.mdx
================================================
---
title: Schritte
description: Hier erfährst du, wie du nummerierte Listen mit Aufgaben erstellen kannst, um Schritt-für-Schritt-Anleitungen in Starlight zu erstellen.
---

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

Um eine nummerierte Liste von Aufgaben zu gestalten und Schritt-für-Schritt-Anleitungen zu erstellen, verwendest du die Komponente `<Steps>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<Steps slot="preview">

1. Erstelle ein neues Starlight-Projekt:

   <Tabs syncKey="pkg">

   <TabItem label="npm">

   ```sh
   npm create astro@latest -- --template starlight
   ```

   </TabItem>

   <TabItem label="pnpm">

   ```sh
   pnpm create astro --template starlight
   ```

   </TabItem>

   <TabItem label="Yarn">

   ```sh
   yarn create astro --template starlight
   ```

   </TabItem>

   </Tabs>

2. Schreibe deine erste Dokumentationsseite.

</Steps>

</Preview>

## Import

```tsx
import { Steps } from '@astrojs/starlight/components';
```

## Verwendung

Verwende die Komponente `<Steps>`, um nummerierte Listen von Aufgaben zu gestalten.
Dies ist nützlich für komplexere Schritt-für-Schritt-Anleitungen, bei denen jeder Schritt deutlich hervorgehoben werden muss.

Wickle `<Steps>` um eine geordnete Standard-Markdown-Liste.
Die übliche Markdown-Syntax ist innerhalb von `<Steps>` anwendbar.

<Preview>

````mdx
import { Steps } from '@astrojs/starlight/components';

<Steps>

1. Importiere die Komponente in deine MDX-Datei:

   ```js
   import { Steps } from '@astrojs/starlight/components';
   ```

2. Wickle `<Steps>` um deine geordneten Listenelemente.

</Steps>
````

<Fragment slot="markdoc">

````markdoc
{% steps %}

1. Importiere die Komponente in deine MDX-Datei:

   ```js
   import { Steps } from '@astrojs/starlight/components';
   ```

2. Wickle `<Steps>` um deine geordneten Listenelemente.

{% /steps %}
````

</Fragment>

<Steps slot="preview">

1. Importiere die Komponente in deine MDX-Datei:

   ```js
   import { Steps } from '@astrojs/starlight/components';
   ```

2. Wickle `<Steps>` um deine geordneten Listenelemente.

</Steps>

</Preview>

## `<Steps>`-Eigenschaften

**Implementation:** [`Steps.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Steps.astro)

Die Komponente `<Steps>` akzeptiert keine Eigenschaften.


================================================
FILE: docs/src/content/docs/de/components/tabs.mdx
================================================
---
title: Registerkarten
description: Lerne, wie du in Starlight Oberflächen mit Registerkarten erstellst, um gleichwertige Informationen zu gruppieren.
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

Um eine Oberfläche mit Registerkarten zu erstellen, verwende die Komponenten `<Tabs>` und `<TabItem>`.
Registerkarten sind nützlich, um gleichwertige Informationen zu gruppieren, wenn ein Nutzer nur eine von mehreren Optionen sehen muss.

import Preview from '~/components/component-preview.astro';

<Preview>

<Tabs slot="preview">
	<TabItem label="Sterne">Sirius, Wega, Betelgeuse</TabItem>
	<TabItem label="Monde">Io, Europa, Ganymed</TabItem>
</Tabs>

</Preview>

## Import

```tsx
import { Tabs, TabItem } from '@astrojs/starlight/components';
```

## Verwendung

Zeige eine Oberfläche mit Registerkarten an, indem du die Komponenten `<Tabs>` und `<TabItem>` benutzt.
Jedes `<TabItem>` muss ein [`label`](#label) haben, um es den Benutzern anzuzeigen.

<Preview>

```mdx
import { Tabs, TabItem } from '@astrojs/starlight/components';

<Tabs>
	<TabItem label="Sterne">Sirius, Wega, Betelgeuse</TabItem>
	<TabItem label="Monde">Io, Europa, Ganymed</TabItem>
</Tabs>
```

<Fragment slot="markdoc">

```markdoc
{% tabs %}
{% tabitem label="Sterne" %}
Sirius, Wega, Betelgeuse
{% /tabitem %}

{% tabitem label="Monde" %}
Io, Europa, Ganymed
{% /tabitem %}
{% /tabs %}
```

</Fragment>

<Tabs slot="preview">
	<TabItem label="Sterne">Sirius, Wega, Betelgeuse</TabItem>
	<TabItem label="Monde">Io, Europa, Ganymed</TabItem>
</Tabs>

</Preview>

### Registerkarten synchronisieren

Halte mehrere Registerkarten­gruppen synchron, indem du das Attribut [`syncKey`](#synckey) hinzufügst.

Alle `<Tabs>` auf einer Seite mit demselben Wert für `syncKey` zeigen dasselbe aktive Label an.
Auf diese Weise kann dein Leser eine Auswahl treffen (z. B. sein Betriebssystem oder den Paketmanager), die dann beim Navigieren durch die Seiten beibehalten wird.

Um zusammenhängende Tabs zu synchronisieren, füge eine identische `syncKey`-Eigenschaft zu jeder `<Tabs>`-Komponente hinzu und stelle sicher, dass sie alle die gleichen `<TabItem>`-Beschriftungen verwenden:

<Preview>

```mdx 'syncKey="constellations"'
import { Tabs, TabItem } from '@astrojs/starlight/components';

_Ein paar Sterne:_

<Tabs syncKey="constellations">
	<TabItem label="Orion">Bellatrix, Rigel, Betelgeuse</TabItem>
	<TabItem label="Zwillinge">Pollux, Castor A, Castor B</TabItem>
</Tabs>

_Ein paar Exoplaneten:_

<Tabs syncKey="constellations">
	<TabItem label="Orion">HD 34445 b, Gliese 179 b, Wasp-82 b</TabItem>
	<TabItem label="Zwillinge">Pollux b, HAT-P-24b, HD 50554 b</TabItem>
</Tabs>
```

<Fragment slot="markdoc">

```markdoc 'syncKey="constellations"'
_Ein paar Sterne:_

{% tabs syncKey="constellations" %}
{% tabitem label="Orion" %}
Bellatrix, Rigel, Betelgeuse
{% /tabitem %}

{% tabitem label="Zwillinge" %}
Pollux, Castor A, Castor B
{% /tabitem %}
{% /tabs %}

_Ein paar Exoplaneten:_

{% tabs syncKey="constellations" %}
{% tabitem label="Orion" %}
HD 34445 b, Gliese 179 b, Wasp-82 b
{% /tabitem %}

{% tabitem label="Zwillinge" %}
Pollux b, HAT-P-24b, HD 50554 b
{% /tabitem %}
{% /tabs %}
```

</Fragment>

<Fragment slot="preview">

_Ein paar Sterne:_

<Tabs syncKey="constellations">
	<TabItem label="Orion">Bellatrix, Rigel, Betelgeuse</TabItem>
	<TabItem label="Zwillinge">Pollux, Castor A, Castor B</TabItem>
</Tabs>

_Ein paar Exoplaneten:_

<Tabs syncKey="constellations">
	<TabItem label="Orion">HD 34445 b, Gliese 179 b, Wasp-82 b</TabItem>
	<TabItem label="Zwillinge">Pollux b, HAT-P-24b, HD 50554 b</TabItem>
</Tabs>

</Fragment>

</Preview>

### Hinzufügen von Symbolen zu Registerkarten

Füge ein Symbol in ein Tab-Element ein, indem du das Attribut [`icon`](#icon) auf den Namen [eines der in Starlight eingebauten Symbole](/de/reference/icons/#alle-symbole) setzt, um ein Symbol neben dem Label anzuzeigen.

<Preview>

```mdx /icon="\w+"/
import { Tabs, TabItem } from '@astrojs/starlight/components';

<Tabs>
	<TabItem label="Sterne" icon="star">
		Sirius, Wega, Betelgeuse
	</TabItem>
	<TabItem label="Monde" icon="moon">
		Io, Europa, Ganymed
	</TabItem>
</Tabs>
```

<Fragment slot="markdoc">

```markdoc /icon="\w+"/
{% tabs %}
{% tabitem label="Sterne" icon="star" %}
Sirius, Wega, Betelgeuse
{% /tabitem %}

{% tabitem label="Monde" icon="moon" %}
Io, Europa, Ganymed
{% /tabitem %}
{% /tabs %}
```

</Fragment>

<Tabs slot="preview">
	<TabItem label="Sterne" icon="star">
		Sirius, Wega, Betelgeuse
	</TabItem>
	<TabItem label="Monde" icon="moon">
		Io, Europa, Ganymed
	</TabItem>
</Tabs>

</Preview>

## `<Tabs>`-Eigenschaften

**Implementation:** [`Tabs.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Tabs.astro)

Die Komponente `<Tabs>` fasst mehrere `<TabItem>`-Komponenten zusammen und akzeptiert die folgenden Eigenschaften:

### `syncKey`

**Typ:** `string`

Ein Schlüssel, der verwendet wird, um mehrere Registerkarten­gruppen über mehrere Seiten hinweg zu synchronisieren.

## `<TabItem>`-Eigenschaften

**Implementation:** [`TabItem.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/TabItem.astro)

Ein Satz von Tabs besteht aus Tab-Elementen, die jeweils die folgenden Eigenschaften haben:

### `label`

**Erforderlich**  
**Typ:** `string`

Eine Registerkarte muss ein Attribut `label` enthalten, das auf den Text gesetzt ist, der in der Registerkarte angezeigt werden soll.

### `icon`

**Typ:** `string`

Jedes Tab-Element kann ein `icon`-Attribut enthalten, das auf den Namen [eines von Starlights eingebauten Symbolen](/de/reference/icons/#alle-symbole) gesetzt ist, um ein Symbol neben dem Label anzuzeigen.


================================================
FILE: docs/src/content/docs/de/components/using-components.mdx
================================================
---
title: Verwendung von Komponenten
description: Verwendung von Komponenten in MDX und Markdoc mit Starlight.
sidebar:
  order: 1
---

Mit Komponenten kannst du auf einfache Weise einen Teil der Benutzeroberfläche oder ein Styling konsistent wiederverwendem.
Beispiele könnten eine Link-Karte oder eine YouTube-Einbettung sein.
Starlight unterstützt die Verwendung von Komponenten in [MDX](https://mdxjs.com/)- und [Markdoc](https://markdoc.dev/)-Dateien und stellt dir einige gängige Komponenten zur Verfügung, die du verwenden kannst.

[Erfahre mehr über die Erstellung von Komponenten in den Astro Docs](https://docs.astro.build/de/basics/astro-components/).

## Verwendung einer Komponente in MDX

Du kannst eine Komponente verwenden, indem du sie in deine MDX-Datei importierst und sie dann als JSX-Tag wiedergibst.
Diese sehen wie HTML-Tags aus, beginnen aber mit einem Großbuchstaben, der dem Namen in der `Import`-Anweisung entspricht:

```mdx
---
# src/content/docs/example.mdx
title: Willkommen bei meiner Dokumentation
---

import { Icon } from '@astrojs/starlight/components';
import CustomCard from '../../components/CustomCard.astro';

<Icon name="open-book" />

<CustomCard>
	Komponenten können auch **verschachtelte Inhalte** enthalten.
</CustomCard>
```

Da Starlight von Astro unterstützt wird, kannst du in deinen MDX-Dateien Unterstützung für Komponenten hinzufügen, die mit einem beliebigen [unterstützten UI-Framework (React, Preact, Svelte, Vue, Solid und Alpine)](https://docs.astro.build/de/guides/framework-components/) erstellt wurden.
Weitere Informationen über [Verwendung von Komponenten in MDX](https://docs.astro.build/de/guides/integrations-guide/mdx/#using-components-in-mdx) findest du in der Astro-Dokumentation.

## Verwendung einer Komponente in Markdoc

Füge Unterstützung für das Verfassen von Inhalten in Markdoc hinzu, indem du unsere [Markdoc-Einrichtungs­anleitung](/de/guides/authoring-content/#markdoc) befolgst.

Mit der Starlight-Markdoc-Voreinstellung kannst du die in Starlight eingebauten Komponenten mit der Markdoc-Tag-Syntax `{% %}` verwenden.
Im Gegensatz zu MDX müssen die Komponenten in Markdoc nicht importiert werden.
Das folgende Beispiel stellt Starlights [Kartenkomponente](/de/components/cards/) in einer Markdoc-Datei dar:

```markdoc
---
# src/content/docs/example.mdoc
title: Willkommen bei meiner Dokumentation
---

{% card title="Stars" icon="star" %}
Sirius, Wega, Betelgeuse
{% /card %}
```

Weitere Informationen zur Verwendung von Komponenten in Markdoc-Dateien findst du in der [Astro Markdoc Integrations­dokumentation](https://docs.astro.build/de/guides/integrations-guide/markdoc/#render-components).

## Integrierte Komponenten

Starlight bietet eingebaute Komponenten für gängige Dokumentations­anwendungen.
Diese Komponenten sind aus dem Paket `@astrojs/starlight/components` in MDX-Dateien und aus der [Starlight-Markdoc-Voreinstellung](/de/guides/authoring-content/#markdoc) in Markdoc-Dateien verfügbar.

In der Seitenleiste findst du eine Liste der verfügbaren Komponenten und deren Verwendung.

## Kompatibilität mit den Stilen von Starlight

Starlight wendet Standardstile auf deinen Markdown-Inhalt an, z. B. fügt es einen Rand zwischen den Elementen hinzu.
Wenn diese Stile mit dem Erscheinungsbild deiner Komponente in Konflikt stehen, setze die Klasse `not-content` für deine Komponente, um sie zu deaktivieren.

```astro 'class="not-content"'
---
// src/components/Example.astro
---

<div class="not-content">
	<p>Die Standard-Inhaltsgestaltung von Starlight wirkt sich nicht aus.</p>
</div>
```

## Komponenten­eigenschaften

Verwende den Typ [`ComponentProps`](https://docs.astro.build/de/guides/typescript/#componentprops-type) aus `astro/types`, um auf die von einer Komponente akzeptierten `Props` zu verweisen, auch wenn sie nicht von der Komponente selbst exportiert werden.
Dies kann hilfreich sein, wenn man eine existierende Komponente verpackt oder erweitert.

Das folgende Beispiel benutzt `ComponentProps`, um den Typ der Eigenschaften zu ermitteln, die von Starlights eingebauter Komponente `Badge` akzeptiert werden:

```astro
---
// src/components/Example.astro
import type { ComponentProps } from 'astro/types';
import { Badge } from '@astrojs/starlight/components';

type BadgeProps = ComponentProps<typeof Badge>;
---
```


================================================
FILE: docs/src/content/docs/de/environmental-impact.md
================================================
---
title: Umweltfreundliche Dokumentation
description: Erfahre, wie Starlight dir helfen kann, umweltfreundlichere Dokumentationen zu erstellen und deinen ökologischen Fußabdruck zu verringern.
---

Schätzungen über die Auswirkungen der Webindustrie auf das Klima liegen zwischen [2%][sf] und [4% der weltweiten Kohlenstoff­emissionen][bbc], was in etwa den Emissionen der Luftfahrtindustrie entspricht.
Es gibt viele komplexe Faktoren bei der Berechnung der ökologischen Auswirkungen einer Website, aber dieser Leitfaden enthält einige Tipps, wie du den ökologischen Fußabdruck deiner Docs-Website verringern kannst.

Die gute Nachricht ist, dass die Wahl von Starlight ein guter Anfang ist.
Laut dem Website Carbon Calculator ist diese Website [sauberer als 98% der getesteten Websites][sl-carbon] und erzeugt 0,01g CO₂ pro Seitenbesuch.

## Seitengewicht

Je mehr Daten eine Website überträgt, desto mehr Energieressourcen benötigt sie.
Im April 2023 musste ein Nutzer laut [Daten aus dem HTTP-Archiv][http] für die durchschnittliche Website mehr als 2.000 KB herunterladen.

Starlight erstellt Seiten, die so leicht wie möglich sind.
So lädt ein Benutzer beim ersten Besuch weniger als 50 KB an komprimierten Daten herunter - nur 2,5% des Medianwerts des HTTP-Archivs.
Mit einer guten Caching-Strategie können nachfolgende Besuche sogar nur 10 KB herunterladen.

### Bilder

Während Starlight eine gute Grundlage bietet, können Bilder, die du deinen Dokumentationsseiten hinzufügst, das Seitengewicht schnell erhöhen.
Starlight nutzt die [optimierte Asset-Unterstützung][Assets] von Astro, um lokale Bilder in deinen Markdown- und MDX-Dateien zu optimieren.

### UI-Komponenten

Komponenten, die mit UI-Frameworks wie React oder Vue erstellt wurden, können leicht große Mengen an JavaScript zu einer Website hinzufügen.
Da Starlight auf Astro aufbaut, laden Komponenten wie diese dank [Astro Islands][islands] standardmäßig **kein clientseitiges JavaScript**.

### Caching

Caching wird verwendet, um zu kontrollieren, wie lange ein Browser Daten speichert und wiederverwendet, die er bereits heruntergeladen hat.
Eine gute Caching-Strategie stellt sicher, dass ein Benutzer neue Inhalte so schnell wie möglich erhält, wenn sich diese ändern, vermeidet aber auch, dass derselbe Inhalt unnötigerweise immer wieder heruntergeladen wird, wenn er sich nicht geändert hat.

Die gebräuchlichste Art, das Zwischenspeichern zu konfigurieren, ist der [`Cache-Control` HTTP-Header][cache].
Wenn du Starlight verwendest, kannst du eine lange Cache-Zeit für alles im Verzeichnis `/_astro/` einstellen.
Dieses Verzeichnis enthält CSS, JavaScript und andere gebündelte Inhalte, die sicher für immer zwischengespeichert werden können, wodurch unnötige Downloads vermieden werden:

```
Cache-Control: public, max-age=604800, immutable
```

Wie du das Caching konfigurierst, hängt von deinem Webhost ab. Zum Beispiel wendet Vercel diese Caching-Strategie für dich an, ohne dass eine Konfiguration erforderlich ist, während du [benutzerdefinierte Header für Netlify][ntl-headers] einstellen kannst, indem du eine `public/_headers`-Datei zu deinem Projekt hinzufügst:

```
/_astro/*
  Cache-Control: public
  Cache-Control: max-age=604800
  Cache-Control: immutable
```

[cache]: https://csswizardry.com/2019/03/cache-control-for-civilians/
[ntl-headers]: https://docs.netlify.com/routing/headers/

## Stromverbrauch

Die Art und Weise, wie eine Website aufgebaut ist, kann sich auf den Stromverbrauch auswirken, den sie auf dem Gerät des Benutzers benötigt.
Durch die Verwendung von minimalem JavaScript reduziert Starlight die Rechenleistung, die das Telefon, Tablet oder der Computer eines Nutzers zum Laden und Rendern von Seiten benötigt.

Sei jedoch vorsichtig, wenn du Funktionen wie analytische Tracking-Skripte oder JavaScript-lastige Inhalte wie Videoeinbettungen hinzufügst, da diese den Stromverbrauch der Seite erhöhen können.
Wenn du Analysen benötigst, solltest du eine schlanke Option wie [Cabin][cabin], [Fathom][fathom] oder [Plausible][plausible] wählen.
Einbettungen wie YouTube- und Vimeo-Videos können verbessert werden, indem man auf [Laden des Videos bei Benutzerinteraktion][lazy-video] wartet.
Pakete wie [`astro-embed`][embed] können bei gängigen Diensten helfen.

:::tip[Wusstest du schon?]
Das Analysieren und Kompilieren von JavaScript ist eine der aufwändigsten Aufgaben, die ein Browser zu erledigen hat.
Verglichen mit dem Rendern eines JPEG-Bildes derselben Größe kann die [Verarbeitung von JavaScript mehr als 30 Mal so lange dauern][cost-of-js].
:::

[cabin]: https://withcabin.com/
[fathom]: https://usefathom.com/
[plausible]: https://plausible.io/
[lazy-video]: https://web.dev/iframe-lazy-loading/
[embed]: https://www.npmjs.com/package/astro-embed
[cost-of-js]: https://medium.com/dev-channel/the-cost-of-javascript-84009f51e99e

## Hosting

Wo eine Website gehostet wird, kann einen großen Einfluss darauf haben, wie umweltfreundlich deine Dokumentationswebsite ist.
Rechenzentren und Serveranlagen können große ökologische Auswirkungen haben, einschließlich eines hohen Stromverbrauchs und eines intensiven Wasserverbrauchs.

Wenn du dich für einen Hoster entscheidest, der erneuerbare Energien einsetzt, wird deine Website weniger Kohlenstoff­emissionen verursachen. Das [Green Web Directory][gwb] ist ein Tool, das dir helfen kann, Hosting-Unternehmen zu finden.

[gwb]: https://www.thegreenwebfoundation.org/directory/

## Gegenüberstellungen

Bist du neugierig, wie andere Dokumentations-Frameworks im Vergleich abschneiden?
Diese Tests mit dem [Website Carbon Calculator][wcc] vergleichen ähnliche Seiten, die mit verschiedenen Tools erstellt wurden.

| Framework                   | CO₂ pro Seitenaufruf | Bewertung |
| --------------------------- | -------------------- | :-------: |
| [Starlight][sl-carbon]      | 0.01g                |    A+     |
| [Sphinx][sx-carbon]         | 0.01g                |    A+     |
| [Read the Docs][rtd-carbon] | 0.03g                |    A+     |
| [VitePress][vp-carbon]      | 0.04g                |     A     |
| [docsify][dy-carbon]        | 0.05g                |     A     |
| [mdBook][md-carbon]         | 0.05g                |     A     |
| [Nextra][nx-carbon]         | 0.05g                |     A     |
| [MkDocs][mk-carbon]         | 0.07g                |     A     |
| [Fumadocs][fs-carbon]       | 0.07g                |     A     |
| [Docusaurus][ds-carbon]     | 0.10g                |     B     |
| [Docus][dc-carbon]          | 0.11g                |     B     |
| [GitBook][gb-carbon]        | 0.42g                |     F     |
| [Mintlify][mt-carbon]       | 0.48g                |     F     |

<small>Daten erhoben am 7. August 2025. Klicke auf einen Link, um aktuelle Zahlen zu sehen.</small>

[sl-carbon]: https://www.websitecarbon.com/website/starlight-astro-build-getting-started/
[vp-carbon]: https://www.websitecarbon.com/website/vitepress-dev-guide-what-is-vitepress/
[dc-carbon]: https://www.websitecarbon.com/website/docus-dev-en-getting-started-project-structure/
[sx-carbon]: https://www.websitecarbon.com/website/sphinx-doc-org-en-master-usage-quickstart-html/
[mk-carbon]: https://www.websitecarbon.com/website/mkdocs-org-getting-started/
[md-carbon]: https://www.websitecarbon.com/website/rust-lang-github-io-mdbook/
[nx-carbon]: https://www.websitecarbon.com/website/nextra-site-docs-docs-theme-start/
[fs-carbon]: https://www.websitecarbon.com/website/fumadocs-dev-docs-ui/
[dy-carbon]: https://www.websitecarbon.com/website/docsify-js-org/
[ds-carbon]: https://www.websitecarbon.com/website/docusaurus-io-docs/
[rtd-carbon]: https://www.websitecarbon.com/website/docs-readthedocs-io-en-stable-index-html/
[gb-carbon]: https://www.websitecarbon.com/website/gitbook-com-docs/
[mt-carbon]: https://www.websitecarbon.com/website/mintlify-com-docs-quickstart/

## Weitere Ressourcen

### Werkzeuge

- [Website Carbon Calculator][wcc]
- [GreenFrame](https://greenframe.io/)
- [Ecograder](https://ecograder.com/)
- [WebPageTest Kohlenstoff­kontrolle](https://www.webpagetest.org/carbon-control/)
- [Ecoping](https://ecoping.earth/)

### Artikel und Vorträge

- [„Building a greener web“](https://youtu.be/EfPoOt7T5lg), Vortrag von Michelle Barker
- [„Sustainable Web Development Strategies Within An Organization“](https://www.smashingmagazine.com/2022/10/sustainable-web-development-strategies-organization/), Artikel von Michelle Barker
- [„A sustainable web for everyone“](https://2021.stateofthebrowser.com/speakers/tom-greenwood/), Vortrag von Tom Greenwood
- [„How Web Content Can Affect Power Usage“](https://webkit.org/blog/8970/how-web-content-can-affect-power-usage/), Artikel von Benjamin Poulain und Simon Fraser

[sf]: https://www.sciencefocus.com/science/what-is-the-carbon-footprint-of-the-internet/
[bbc]: https://www.bbc.com/future/article/20200305-why-your-internet-habits-are-not-as-clean-as-you-think
[http]: https://httparchive.org/reports/state-of-the-web
[assets]: https://docs.astro.build/de/guides/images/
[islands]: https://docs.astro.build/de/concepts/islands/
[wcc]: https://www.websitecarbon.com/


================================================
FILE: docs/src/content/docs/de/getting-started.mdx
================================================
---
title: Erste Schritte
description: Lerne, wie du deine nächste Dokumentations­website mit Starlight und Astro erstellst.
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

Starlight ist ein voll funktionsfähiges Dokumentations­framework, welches auf [Astro](https://astro.build) aufbaut.
Diese Anleitung wird dir helfen, mit einem neuen Projekt zu beginnen.
Sieh dir die [manuellen Einrichtungs­anweisungen](/de/manual-setup/) an, um Starlight zu einem bestehenden Astro-Projekt hinzuzufügen.

## Schnellstart

### Erstelle ein neues Projekt

Du kannst ein neues Astro + Starlight Projekt mit dem folgenden Befehl erstellen:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight
```

</TabItem>
</Tabs>

Damit wird ein neues [Projektverzeichnis](/de/guides/project-structure/) mit allen erforderlichen Dateien und Konfigurationen für deine Website erstellt.

:::tip[In Aktion sehen]
Probiere Starlight in deinem Browser aus:
[öffne die Vorlage in StackBlitz](https://stackblitz.com/github/withastro/starlight/tree/main/examples/basics).
:::

### Starte den Entwicklungsserver

Wenn du lokal arbeitest, kannst du mit dem [Astro-Entwicklungsserver](https://docs.astro.build/de/reference/cli-reference/#astro-dev) eine Vorschau deiner Arbeit angezeigt bekommen und dein Browser wird automatisch aktualisiert, wenn du Änderungen vornimmst.

Führe in deinem Projektverzeichnis den folgenden Befehl aus, um den Entwicklungsserver zu starten:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm run dev
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dev
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dev
```

</TabItem>
</Tabs>

Daraufhin wird eine Meldung mit der URL deiner lokalen Vorschau in deinem Terminal angezeigt.
Öffne diese URL, um deine Website zu betrachten.

### Inhalt hinzufügen

Starlight ist bereit für dich, neuen Inhalt hinzuzufügen oder deine vorhandenen Dateien mitzubringen!

Füge neue Seiten zu deiner Website hinzu, indem du Markdown-Dateien im Verzeichnis `src/content/docs/` erstellst.

Lies mehr über dateibasiertes Routing und Unterstützung für MDX- und Markdoc-Dateien in der Anleitung [„Seiten“](/de/guides/pages/).

### Nächste Schritte

- **Konfigurieren:** Erfahre mehr über die allgemeinen Optionen in [„Starlight anpassen“](/de/guides/customization/).
- **Navigieren:** Richte dir deine Seitenleiste mit der Anleitung [„Seitenleisten-Navigation“](/de/guides/sidebar/) ein.
- **Komponenten:** Entdecke die eingebauten Karten, Registerkarten und mehr in der Anleitung [„Komponenten“](/de/components/using-components/).
- **Erweitern:** Schau dir die Community-Erweiterungen in unseren Katalogen [„Plugins“](/de/resources/plugins/) und [„Themes“](/de/resources/themes/) an.
- **Veröffentlichen:** Veröffentliche deine Arbeit mit der Anleitung [„Bereitstellen deiner Website“](https://docs.astro.build/de/guides/deploy/) in der Astro-Dokumentation.

## Starlight aktualisieren

:::tip[Tipp]
Da es sich bei Starlight um eine Beta-Software handelt, wird es regelmäßig Updates und Verbesserungen geben. Achte darauf Starlight regelmäßig zu aktualisieren!
:::

Starlight ist eine Astro-Integration. Dieses und andere Astro-Pakete kannst du aktualisieren, indem du den folgenden Befehl in deinem Terminal ausführst:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npx @astrojs/upgrade
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dlx @astrojs/upgrade
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dlx @astrojs/upgrade
```

</TabItem>
</Tabs>

Eine vollständige Liste der Änderungen findest du im [Starlight Changelog](https://github.com/withastro/starlight/blob/main/packages/starlight/CHANGELOG.md).

## Fehlerbehebung Starlight

Benutze die Referenzseiten [Projekt­konfiguration](/de/reference/configuration/) und [Individuelle Seitenfrontmatter-Konfiguration](/de/reference/frontmatter/), um sicherzustellen, dass deine Starlight-Website richtig konfiguriert ist und funktioniert.
In den Anleitungen in der Seitenleiste findest du Hilfe beim Hinzufügen von Inhalten und Anpassen deiner Starlight-Website.

Wenn du deine Antwort nicht in dieser Dokumentation finden kannst, besuche bitte die [Astro-Dokumentation](https://docs.astro.build) für eine vollständige Dokumentation des darunterliegenden Frameworks.
Deine Frage lässt sich vielleicht beantworten, wenn du verstehst, wie Astro im Allgemeinen funktioniert, da Astro das Framework ist, auf dem Starlight basiert.

Du kannst auch nach bekannten [Starlight-Problemen auf GitHub](https://github.com/withastro/starlight/issues) suchen und im [Astro Discord](https://astro.build/chat/) Hilfe von unserer aktiven, freundlichen Community erhalten! Poste Fragen in unserem `#support` Forum mit dem „starlight“ Tag oder besuche unseren speziellen `#starlight`-Kanal, um über die aktuelle Entwicklung und mehr zu diskutieren!


================================================
FILE: docs/src/content/docs/de/guides/authoring-content.mdx
================================================
---
title: Inhalte in Markdown verfassen
description: Ein Überblick über die von Starlight unterstützte Markdown-Syntax.
---

Starlight unterstützt die gesamte Bandbreite der [Markdown](https://daringfireball.net/projects/markdown/) Syntax in `.md` Dateien sowie Frontmatter [YAML](https://dev.to/paulasantamaria/introduction-to-yaml-125f) um Metadaten wie Titel und Beschreibung zu definieren.

Bitte prüfe die [MDX-Dokumentation](https://mdxjs.com/docs/what-is-mdx/#markdown) oder [Markdoc-Dokumentation](https://markdoc.dev/docs/syntax), wenn du diese Dateiformate verwendest, da die Unterstützung und Verwendung von Markdown unterschiedlich sein kann.

## Frontmatter

Du kannst einzelne Seiten in Starlight anpassen, indem du Werte in deinen Frontmatter festlegst.
Frontmatter wird oben in deinen Dateien zwischen `---`-Trennzeichen festgelegt:

```md title="src/content/docs/example.md"
---
title: Mein Seitentitel
---

Nach dem zweiten `---` folgt der Seiteninhalt.
```

Jede Seite muss mindestens einen `title` enthalten.
Alle verfügbaren Felder und Informationen zum Hinzufügen benutzerdefinierter Felder findst du in der [Frontmatter-Referenz](/de/reference/frontmatter/).

## Inline-Stile

Text kann **fett**, _italic_, oder ~~durchgestrichen~~ sein.

```md
Text kann **fett**, _italic_, oder ~~durchgestrichen~~ sein.
```

Du kannst [auf eine andere Seite](/de/getting-started/) verlinken.

```md
Du kannst [auf eine andere Seite](/de/getting-started/) verlinken.
```

Du kannst `inline code` mit Backticks hervorheben.

```md
Du kannst `inline code` mit Backticks hervorheben.
```

## Bilder

Bilder in Starlight verwenden [Astros eingebaute optimierte Asset-Unterstützung](https://docs.astro.build/de/guides/images/).

Markdown und MDX unterstützen die Markdown-Syntax für die Anzeige von Bildern, einschließlich Alt-Text für Bildschirmleser und unterstützende Technologien.

![Eine Illustration von Planeten und Sternen mit dem Wort "Astro"](https://raw.githubusercontent.com/withastro/docs/main/public/default-og-image.png)

```md
![Eine Illustration von Planeten und Sternen mit dem Wort "astro"](https://raw.githubusercontent.com/withastro/docs/main/public/default-og-image.png)
```

Relative Bildpfade werden auch für in deinem Projekt lokal gespeicherte Bilder unterstützt.

```md
// src/content/docs/page-1.md

![Ein Raketenschiff im Weltraum](../../assets/images/rocket.svg)
```

## Überschriften

Mit einer Überschrift kannst du den Inhalt strukturieren. Überschriften in Markdown werden durch eine Reihe von `#` am Anfang der Zeile gekennzeichnet.

### Wie du Seiteninhalte in Starlight strukturierst

Starlight ist so konfiguriert, dass es automatisch den Seitentitel als Überschrift verwendet und eine "Übersicht"-Überschrift an den Anfang des Inhalts­verzeichnisses jeder Seite setzt. Wir empfehlen, jede Seite mit normalem Text zu beginnen und die Seitenüberschriften ab `<h2>` zu verwenden:

```md
---
title: Markdown Anleitung
description: Wie man Markdown in Starlight benutzt
---

Diese Seite beschreibt, wie man Markdown in Starlight benutzt.

## Inline-Stile

## Überschriften
```

### Automatische Überschriften-Ankerlinks

Wenn du Überschriften in Markdown verwendst, erhaltst du automatisch Ankerlinks, sodass du direkt auf bestimmte Abschnitte deiner Seite verlinken kannst:

```md
---
title: Meine Seite mit Inhalt
description: Wie man Starlights eingebaute Ankerlinks benutzt
---

## Einleitung

Ich kann auf [meine Schlussfolgerung](#schlussfolgerung) weiter unten auf derselben Seite verlinken.

## Schlussfolgerung

`https://meine-site.com/seite1/#einleitung` navigiert direkt zu meiner Einleitung.
```

Überschriften der Ebene 2 (`<h2>`) und der Ebene 3 (`<h3>`) werden automatisch im Inhaltsverzeichnis der Seite angezeigt.

Erfahre mehr darüber, wie Astro Kopfzeilen-IDs verarbeitet, in [der Astro-Dokumentation](https://docs.astro.build/de/guides/markdown-content/#%C3%BCberschriften-ids).

## Nebenbemerkungen

Nebenbemerkungen (auch bekannt als "Ermahnungen" oder "Callouts") sind nützlich, um sekundäre Informationen neben dem Hauptinhalt einer Seite anzuzeigen.

Starlight bietet eine eigene Markdown-Syntax für die Darstellung von Nebeninformationen. Seitenblöcke werden mit einem Paar dreifacher Doppelpunkte `:::` angezeigt, um den Inhalt zu umschließen, und können vom Typ `note`, `tip`, `caution` oder `danger` sein.

Du kannst alle anderen Markdown-Inhaltstypen innerhalb einer Nebenbemerkung verschachteln, allerdings eignen sich diese am besten für kurze und prägnante Inhaltsstücke.

### Nebenbemerkung `note`

:::note
Starlight ist ein Toolkit für Dokumentations-Websites, das mit [Astro](https://astro.build/de) erstellt wurde. Du kannst mit diesem Befehl beginnen:

```sh
npm create astro@latest -- --template starlight
```

:::

````md
:::note
Starlight ist ein Toolkit für Dokumentations-Websites, das mit [Astro](https://astro.build/de) erstellt wurde. Du kannst mit diesem Befehl beginnen:

```sh
npm create astro@latest -- --template starlight
```

:::
````

### Benutzerdefinierte Nebenbemerkungs­titel

Du kannst einen benutzerdefinierten Titel für die Nebenbemerkung in eckigen Klammern nach dem Typen angeben, z. B. `:::tip[Wusstest du schon?]`.

:::tip[Wusstest du schon?]
Astro hilft dir, schnellere Websites mit ["Inselarchitektur"](https://docs.astro.build/de/concepts/islands/) zu erstellen.
:::

```md
:::tip[Wusstest du schon?]
Astro hilft dir, schnellere Websites mit ["Inselarchitektur"](https://docs.astro.build/de/concepts/islands/) zu erstellen.
:::
```

### Benutzerdefinierte Symbole für Nebenbemerkungen

Du kannst ein benutzerdefiniertes Symbol für die Nebenbemerkungen in geschweiften Klammern nach dem Typ der Nebeninformation oder dem [benutzerdefinierten Titel](#benutzerdefinierte-nebenbemerkungstitel) angeben, z. B. `:::tip{icon="heart"}` oder `:::tip[Wusstest du schon?]{icon="heart"}`.
Der Name des Symbols muss dem Namen [eines der in Starlight integrierten Symbole](/de/reference/icons/#alle-symbole) entsprechen.

:::tip{icon="heart"}
Astro hilft dir, schnellere Websites mit ["Inselarchitektur"](https://docs.astro.build/de/concepts/islands/) zu erstellen.
:::

```md
:::tip{icon="heart"}
Astro hilft dir, schnellere Websites mit ["Inselarchitektur"](https://docs.astro.build/de/concepts/islands/) zu erstellen.
:::
```

### Weitere Typen

Vorsichts- und Gefahrenhinweise sind hilfreich, um die Aufmerksamkeit des Benutzers auf Details zu lenken, über die er stolpern könnte.
Wenn du diese häufig verwenden, kann das auch ein Zeichen dafür sein, dass die Sache, die du dokumentierst, von einem neuen Design profitieren könnte.

:::caution
Wenn du nicht sicher bist, ob du eine großartige Dokumentationswebsite willst, überlege es dir zweimal, bevor du [Starlight](/de/) verwendest.
:::

:::danger
Deine Benutzer können dank hilfreicher Starlight-Funktionen produktiver sein und dein Produkt einfacher nutzen.

- Übersichtliche Navigation
- Benutzer-konfigurierbares Farben-Theme
- [i18n-Unterstützung](/de/guides/i18n/)

:::

```md
:::caution
Wenn du nicht sicher bist, ob du eine großartige Dokumentationswebsite willst, überlege es dir zweimal, bevor du [Starlight](/de/) verwendest.
:::

:::danger
Deine Benutzer können dank hilfreicher Starlight-Funktionen produktiver sein und dein Produkt einfacher nutzen.

- Übersichtliche Navigation
- Benutzer-konfigurierbares Farben-Theme
- [i18n-Unterstützung](/de/guides/i18n/)

:::
```

## Blockzitate

> Dies ist ein Blockzitat, das üblicherweise verwendet wird, wenn eine andere Person oder ein Dokument zitiert wird.
>
> Blockzitate werden durch ein ">" am Anfang jeder Zeile gekennzeichnet.

```md
> Dies ist ein Blockzitat, das üblicherweise verwendet wird, wenn eine andere Person oder ein Dokument zitiert wird.
>
> Blockzitate werden durch ein ">" am Anfang jeder Zeile gekennzeichnet.
```

## Codeblöcke

Ein Codeblock wird durch einen Block mit drei Backticks <code>```</code> am Anfang und Ende gekennzeichnet. Du kannst die verwendete Programmiersprache nach den ersten drei Backticks angeben.

```js
// Javascript-Code mit Syntaxhervorhebung.
var fun = function lang(l) {
	dateformat.i18n = require('./lang/' + l);
	return true;
};
```

````md
```js
// Javascript-Code mit Syntaxhervorhebung.
var fun = function lang(l) {
	dateformat.i18n = require('./lang/' + l);
	return true;
};
```
````

### Expressive Code-Merkmale

Starlight verwendet [Expressive Code](https://expressive-code.com/), um die Formatierungs­möglichkeiten für Codeblöcke zu erweitern.
Die Textmarker und Fensterrahmen-Plugins von Expressive Code sind standardmäßig aktiviert.
Die Darstellung von Codeblöcken kann mit Starlights [`expressiveCode` Konfigurations­option](/de/reference/configuration/#expressivecode) konfiguriert werden.

#### Textmarkierungen

Du kannst bestimmte Zeilen oder Teile deiner Codeblöcke hervorheben, indem du [Expressive Code Textmarkierungen](https://expressive-code.com/key-features/text-markers/) in der ersten Zeile deines Codeblocks verwendest.
Verwende geschweifte Klammern (`{ }`), um ganze Zeilen hervorzuheben, und Anführungszeichen, um Textabschnitte zu markieren.

Es gibt drei Hervorhebungsstile: neutral, um auf den Code aufmerksam zu machen, grün, um eingefügten Code zu kennzeichnen, und rot, um gelöschten Code zu kennzeichnen.
Sowohl Text als auch ganze Zeilen können mit der Standardmarkierung oder in Kombination mit `ins=` und `del=` markiert werden, um die gewünschte Hervorhebung zu erzielen.

Expressive Code bietet mehrere Optionen zur Anpassung des visuellen Erscheinungsbildes deiner Codebeispiele.
Viele dieser Optionen können kombiniert werden, um sehr anschauliche Codebeispiele zu erstellen.
Bitte schaue dir die [Expressive Code Dokumentation](https://expressive-code.com/key-features/text-markers/#configuration) an, um dich über die umfangreichen Optionen zu informieren.
Einige der gebräuchlichsten Beispiele sind unten aufgeführt:

- [Markiere ganze Zeilen und Zeilenbereiche mit dem Marker `{ }`](https://expressive-code.com/key-features/text-markers/#marking-full-lines--line-ranges):

  ```js {2-3}
  function demo() {
  	// Diese Zeile (#2) und die nächste Zeile sind hervorgehoben
  	return 'Dies ist Zeile #3 dieses Ausschnittes';
  }
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```js {2-3}
  function demo() {
  	// Diese Zeile (#2) und die nächste Zeile sind hervorgehoben
  	return 'Dies ist Zeile #3 dieses Ausschnittes';
  }
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```js {% meta="{2-3}" %}
  function demo() {
  	// Diese Zeile (#2) und die nächste Zeile sind hervorgehoben
  	return 'Dies ist Zeile #3 dieses Ausschnittes';
  }
  ```
  ````

  </TabItem>

  </Tabs>

- [Markieren von Textabschnitten mit der Markierung `" "` oder regulären Ausdrücken](https://expressive-code.com/key-features/text-markers/#marking-individual-text-inside-lines):

  ```js "einzelne Begriffe" /Auch.*unterstützt/
  // Auch einzelne Begriffe können hervorgehoben werden
  function demo() {
  	return 'Auch reguläre Ausdrücke (RegEx) werden unterstützt';
  }
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```js "einzelne Begriffe" /Auch.*unterstützt/
  // Auch einzelne Begriffe können hervorgehoben werden
  function demo() {
  	return 'Auch reguläre Ausdrücke (RegEx) werden unterstützt';
  }
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```js {% meta="'einzelne Begriffe' /Auch.*unterstützt/" %}
  // Auch einzelne Begriffe können hervorgehoben werden
  function demo() {
  	return 'Auch reguläre Ausdrücke (RegEx) werden unterstützt';
  }
  ```
  ````

  </TabItem>

  </Tabs>

- [Text oder Zeilen mit `ins` oder `del` als eingefügt oder gelöscht markieren](https://expressive-code.com/key-features/text-markers/#selecting-inline-marker-types-mark-ins-del):

  ```js "return true;" ins="eingefügte" del="gelöschte"
  function demo() {
  	console.log('Dies sind eingefügte und gelöschte Markertypen');
  	// Die return-Anweisung verwendet den Standard-Markierungstyp
  	return true;
  }
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```js "return true;" ins="eingefügte" del="gelöschte"
  function demo() {
  	console.log('Dies sind eingefügte und gelöschte Markertypen');
  	// Die return-Anweisung verwendet den Standard-Markierungstyp
  	return true;
  }
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```js {% meta="'return true;' ins='eingefügte' del='gelöschte'" %}
  function demo() {
  	console.log('Dies sind eingefügte und gelöschte Markertypen');
  	// Die return-Anweisung verwendet den Standard-Markierungstyp
  	return true;
  }
  ```
  ````

  </TabItem>

  </Tabs>

- [Kombiniere die Syntaxhervorhebung mit einer `diff`-ähnlichen Syntax](https://expressive-code.com/key-features/text-markers/#combining-syntax-highlighting-with-diff-like-syntax):

  ```diff lang="js"
    function thisIsJavaScript() {
      // Dieser gesamte Block wird als JavaScript hervorgehoben,
      // und wir können ihm immer noch Diff-Markierungen hinzufügen!
  -   console.log('Zu entfernender alter Code')
  +   console.log('Neuer, glänzender Code!')
    }
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```diff lang="js"
    function thisIsJavaScript() {
      // Dieser gesamte Block wird als JavaScript hervorgehoben,
      // und wir können ihm immer noch Diff-Markierungen hinzufügen!
  -   console.log('Zu entfernender alter Code')
  +   console.log('Neuer, glänzender Code!')
    }
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```diff {% meta="lang='js'" %}
    function thisIsJavaScript() {
      // Dieser gesamte Block wird als JavaScript hervorgehoben,
      // und wir können ihm immer noch Diff-Markierungen hinzufügen!
  -   console.log('Zu entfernender alter Code')
  +   console.log('Neuer, glänzender Code!')
    }
  ```
  ````

  </TabItem>

  </Tabs>

#### Rahmen und Überschriften

Codeblöcke können innerhalb eines fensterähnlichen Rahmens dargestellt werden.
Ein Rahmen, der wie ein Terminalfenster aussieht, wird für Shell-Skriptsprachen (z. B. `bash` oder `sh`) verwendet.
Andere Sprachen werden in einem Rahmen im Stil eines Code-Editors angezeigt, wenn sie einen Titel enthalten.

Der optionale Titel eines Code-Blocks kann entweder mit einem `title="..."`-Attribut gesetzt werden, das den öffnenden Backticks und dem Sprachbezeichner des Code-Blocks folgt, oder mit einem Dateinamenkommentar in den ersten Zeilen des Codes.

- [Hinzufügen einer Registerkarte für den Dateinamen mit einem Kommentar](https://expressive-code.com/key-features/frames/#code-editor-frames)

  ```js
  // meine-test-datei.js
  console.log('Hallo Welt!');
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```js
  // meine-test-datei.js
  console.log('Hallo Welt!');
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````md
  ```js
  // meine-test-datei.js
  console.log('Hallo Welt!');
  ```
  ````

  </TabItem>

  </Tabs>

- [Hinzufügen eines Titels zu einem Terminalfenster](https://expressive-code.com/key-features/frames/#terminal-frames)

  ```bash title="Installieren von Abhängigkeiten…"
  npm install
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```bash title="Installieren von Abhängigkeiten…"
  npm install
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```bash {% title="Installieren von Abhängigkeiten…" %}
  npm install
  ```
  ````

  </TabItem>

  </Tabs>

- [Fensterrahmen mit `frame="none"` deaktivieren](https://expressive-code.com/key-features/frames/#overriding-frame-types)

  ```bash frame="none"
  echo "Dies wird trotz Verwendung der Bash-Sprache nicht als Terminal dargestellt"
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```bash frame="none"
  echo "Dies wird trotz Verwendung der Bash-Sprache nicht als Terminal dargestellt"
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```bash {% frame="none" %}
  echo "Dies wird trotz Verwendung der Bash-Sprache nicht als Terminal dargestellt"
  ```
  ````

  </TabItem>

  </Tabs>

## Details

Details (auch bekannt als „Offenlegungen“ oder „Akkordeons“) sind nützlich, um Inhalte zu verbergen, die nicht unmittelbar relevant sind.
Die Nutzer können auf eine kurze Zusammenfassung klicken, um den gesamten Inhalt zu sehen.

Verwende die Standard-HTML-Elemente [`<details>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details) und [`<summary>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/summary) in deinem Markdown-Inhalt, um ein Offenlegungs-Widget zu erstellen.

Du kannst jede andere Markdown-Syntax innerhalb eines `<details>`-Elements verschachteln.

<details>
<summary>Wo und wann ist das Sternbild Andromeda am besten zu sehen?</summary>

Das Sternbild [Andromeda](<https://de.wikipedia.org/wiki/Andromeda_(Sternbild)>) ist am Nachthimmel im Monat November in Breitengraden zwischen `+90°` und `−40°` am besten sichtbar.

</details>

```md
<details>
<summary>Wo und wann ist das Sternbild Andromeda am besten zu sehen?</summary>

Das Sternbild [Andromeda](<https://de.wikipedia.org/wiki/Andromeda_(Sternbild)>) ist am Nachthimmel im Monat November in Breitengraden zwischen `+90°` und `−40°` am besten sichtbar.

</details>
```

## Fußnoten

[Fußnoten](https://www.markdownguide.org/extended-syntax/#footnotes) sind nützlich, um kurze Hinweise oder Erklärungen hinzuzufügen, ohne den Textfluss zu stören. Sie werden hochgestellt als nummerierte Links im Text angezeigt, die zu den entsprechenden Erläuterungen am Ende der Seite führen.

Erstelle eine Fußnote mit eckigen Klammern, einem Caret (auch bekannt als Zirkumflex oder Dach) und einer Nummer:

```md
Hier ist eine Fußnote[^1] mit nachfolgendem Referenztext.

[^1]: Meine Referenz.
```

## Andere allgemeine Markdown-Funktionen

Starlight unterstützt alle anderen Markdown-Autorensyntaxen, wie Listen und Tabellen. Einen schnellen Überblick über alle Markdown-Syntaxelemente findest du im [Markdown Cheat Sheet von The Markdown Guide](https://www.markdownguide.org/cheat-sheet/).

## Erweiterte Markdown- und MDX-Konfiguration

Starlight verwendet Astros Markdown- und MDX-Renderer, der auf remark und rehype aufbaut. Du kannst eine Unterstützung für eigene Syntax und Verhalten hinzufügen, indem du `remarkPlugins` oder `rehypePlugins` in deiner Astro-Konfigurationsdatei hinzufügst. Weitere Informationen findest du unter ["Markdown konfigurieren"](https://docs.astro.build/de/guides/markdown-content/#markdown-plugins) in der Astro-Dokumentation.

## Markdoc

Starlight unterstützt die Erstellung von Inhalten in Markdoc mithilfe der experimentellen [Astro Markdoc-Integration](https://docs.astro.build/de/guides/integrations-guide/markdoc/) und der Starlight-Markdoc-Voreinstellung.

### Erstelle ein neues Projekt mit Markdoc

Starte ein neues Starlight-Projekt mit vorkonfiguriertem Markdoc mit `create astro`:

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight/markdoc
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight/markdoc
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight/markdoc
```

</TabItem>
</Tabs>

### Markdoc zu einem bestehenden Projekt hinzufügen

Wenn du bereits eine Starlight-Website hast und Markdoc hinzufügen möchtest, befolge diese Schritte.

<Steps>

1.  Füge Astros Markdoc-Integration hinzu:

    <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npx astro add markdoc
    ```

    </TabItem>

    <TabItem label="pnpm">

    ```sh
    pnpm astro add markdoc
    ```

    </TabItem>

    <TabItem label="Yarn">

    ```sh
    yarn astro add markdoc
    ```

    </TabItem>

    </Tabs>

2.  Installiere die Starlight-Markdoc-Voreinstellung:

    <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npm install @astrojs/starlight-markdoc
    ```

    </TabItem>

    <TabItem label="pnpm">

    ```sh
    pnpm add @astrojs/starlight-markdoc
    ```

    </TabItem>

    <TabItem label="Yarn">

    ```sh
    yarn add @astrojs/starlight-markdoc
    ```

    </TabItem>

    </Tabs>

3.  Erstelle eine Markdoc-Konfigurationsdatei unter `markdoc.config.mjs` und verwende die Starlight-Markdoc-Voreinstellung:

    ```js
    import { defineMarkdocConfig } from '@astrojs/markdoc/config';
    import starlightMarkdoc from '@astrojs/starlight-markdoc';

    export default defineMarkdocConfig({
    	extends: [starlightMarkdoc()],
    });
    ```

</Steps>

Weitere Informationen zur Syntax und den Funktionen von Markdoc findest du in der [Markdoc-Dokumentation](https://markdoc.dev/docs/syntax) oder im [Astro Markdoc-Integrations­handbuch](https://docs.astro.build/de/guides/integrations-guide/markdoc/).

### Konfigurieren der Markdoc-Voreinstellung

Die Voreinstellung `starlightMarkdoc()` akzeptiert die folgenden Konfigurationsoptionen:

#### `headingLinks`

**Typ:** `boolean`  
**Standard:** `true`

Legt fest, ob Überschriften mit einem anklickbaren Ankerlink dargestellt werden oder nicht.
Entspricht der Option [`markdown.headingLinks`](/de/reference/configuration/#markdown), die für Markdown- und MDX-Dateien gilt.

```js "headingLinks: false"
export default defineMarkdocConfig({
	// Deaktiviere die Standardunterstützung für Überschrift-Ankerlinks
	extends: [starlightMarkdoc({ headingLinks: false })],
});
```


================================================
FILE: docs/src/content/docs/de/guides/css-and-tailwind.mdx
================================================
---
title: CSS & Styling
description: Lerne, wie du deine Starlight-Website mit benutzerdefiniertem CSS gestalten oder mit Tailwind CSS integrieren kannst.
---

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

Du kannst deine Starlight-Website mit benutzerdefinierten CSS-Dateien gestalten oder das Starlight Tailwind-Plugin verwenden.

Eine schnelle Möglichkeit, das Standardtheme deiner Website zu ändern, findest du unter [Cummunity-Themes](/de/resources/themes/).

## Benutzerdefinierte CSS-Styles (Stile)

Passe die Styles deiner Starlight-Website an, indem du zusätzliche CSS-Dateien bereitstellst, um die Standard-Styles von Starlight zu verändern oder zu erweitern.

<Steps>

1. Füge eine CSS-Datei zu deinem `src/`-Verzeichnis hinzu.
   Du kannst zum Beispiel eine größere Standard-Spaltenbreite und eine größere Textgröße für den Seitentitel festlegen:

   ```css
   /* src/styles/custom.css */
   :root {
   	--sl-content-width: 50rem;
   	--sl-text-5xl: 3.5rem;
   }
   ```

2. Füge den Pfad zu deiner CSS-Datei in Starlights `customCss`- Array in `astro.config.mjs` ein:

   ```diff lang="js"
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Dokumentation mit benutzerdefiniertem CSS',
   			customCss: [
   +				// Relativer Pfad zu deiner benutzerdefinierten CSS-Datei
   +				'./src/styles/custom.css',
   			],
   		}),
   	],
   });
   ```

</Steps>

Du kannst dir alle CSS-Eigenschaften, die von Starlight verwendet werden und die du einstellen kannst, um deine Website anzupassen, in der [Datei `props.css` auf GitHub](https://github.com/withastro/starlight/blob/main/packages/starlight/style/props.css) ansehen.

### Kaskadenschichten

Starlight verwendet intern [Kaskadenschichten](https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Cascade_layers), um die Reihenfolge der Stile zu verwalten.
Dies gewährleistet eine vorhersehbare CSS-Reihenfolge und ermöglicht einfachere Überschreibungen.
Jedes benutzerdefinierte CSS ohne Schichten überschreibt die Standardstile von Starlight.

Wenn du Kaskadenschichten verwendest, kannst du [`@layer`](https://developer.mozilla.org/en-US/docs/Web/CSS/@layer) in deinem benutzerdefinierten CSS verwenden, um die Rangfolge der verschiedenen Schichten in Bezug auf die Stile der Schicht `starlight` festzulegen:

```css "starlight"
/* src/styles/custom.css */
@layer my-reset, starlight, my-overrides;
```

Das obige Beispiel definiert eine benutzerdefinierte Schicht namens `my-reset`, die vor allen Starlight-Schichten angewendet wird, und eine weitere Schicht namens `my-overrides`, die nach allen Starlight-Schichten angewendet wird.
Alle Stile in der Schicht `my-overrides` haben Vorrang vor den Stilen von Starlight, aber Starlight kann immer noch Stile ändern, die in der Schicht `my-reset` festgelegt wurden.

## Tailwind CSS

Die Unterstützung für Tailwind CSS v4 in Astro-Projekten wird durch das [Tailwind Vite-Plugin](https://tailwindcss.com/docs/installation/using-vite) bereitgestellt.
Starlight bietet komplementäres CSS, um Tailwind für die Kompatibilität mit den Styles von Starlight zu konfigurieren.

Das Starlight Tailwind CSS wendet die folgende Konfiguration an:

- Konfiguriert Tailwinds `dark:`-Varianten so, dass sie mit Starlights Dark Mode funktionieren.
- Verwendet Tailwind [Themenfarben und Schriftarten](#starlight-mit-tailwind-designen) in Starlights UI.
- Stellt wesentliche Teile der Preflight-Reset-Stile von Tailwind wieder her.

### Erstelle ein neues Projekt mit Tailwind

Starte ein neues Starlight-Projekt mit Tailwind CSS vorkonfiguriert, indem du `create astro` verwendest:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight/tailwind
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight/tailwind
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight/tailwind
```

</TabItem>
</Tabs>

### Tailwind zu einem bestehenden Projekt hinzufügen

Wenn du bereits eine Starlight-Website hast und Tailwind CSS hinzufügen möchtest, folge dieser Anleitung.

<Steps>

1.  Richte Tailwind in deinem Projekt ein, indem du den folgenden Befehl ausführst und den Anweisungen in deinem Terminal folgst:

    <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npx astro add tailwind
    ```

    </TabItem>

    <TabItem label="pnpm">

    ```sh
    pnpm astro add tailwind
    ```

    </TabItem>

    <TabItem label="Yarn">

    ```sh
    yarn astro add tailwind
    ```

    </TabItem>

    </Tabs>

2.  Installiere das Tailwind-Kompatibilitätspaket von Starlight:

    <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npm install @astrojs/starlight-tailwind
    ```

    </TabItem>

    <TabItem label="pnpm">

    ```sh
    pnpm add @astrojs/starlight-tailwind
    ```

    </TabItem>

    <TabItem label="Yarn">

    ```sh
    yarn add @astrojs/starlight-tailwind
    ```

    </TabItem>

    </Tabs>

3.  Ersetze den Inhalt der Datei `src/styles/global.css`, die von Astro für die Kompatibilität mit Starlight gerüstet wurde:

    ```css
    /* src/styles/global.css */
    @layer base, starlight, theme, components, utilities;

    @import '@astrojs/starlight-tailwind';
    @import 'tailwindcss/theme.css' layer(theme);
    @import 'tailwindcss/utilities.css' layer(utilities);
    ```

    Diese Tailwind-Theme-Konfiguration legt die Reihenfolge der [Kaskadenschichten](#kaskadenschichten) von Starlight fest, importiert das ergänzende CSS von Starlight für Tailwind und importiert die Theme- und Utility-Stile von Tailwind.
    Wenn dein Projekt eine zusätzliche Tailwind-Konfiguration erfordert, schau dir den Abschnitt [„Mehrere Tailwind-Konfigurationen verwenden“](#mehrere-tailwind-konfigurationen-verwenden) an.

4.  Aktualisiere die Starlight-Konfiguration, um die Tailwind-CSS-Datei als erstes Element im Array `customCss` hinzuzufügen:

        ```js ins={11-12}
        // astro.config.mjs
        import { defineConfig } from 'astro/config';
        import starlight from '@astrojs/starlight';
        import tailwindcss from '@tailwindcss/vite';

        export default defineConfig({
          integrations: [
            starlight({
              title: 'Dokumentation mit Tailwind',
              customCss: [
                // Pfad zu deinen grundlegenden Tailwind-Styles
                './src/styles/global.css',
              ],
            }),
          ],
          vite: { plugins: [tailwindcss()] },
        });
        ```

</Steps>

### Starlight mit Tailwind designen

Wenn du ein [neues Starlight-Projekt mit Tailwind erstellst](#erstelle-ein-neues-projekt-mit-tailwind) oder [Tailwind zu einem bestehenden Starlight-Projekt hinzufügst](#tailwind-zu-einem-bestehenden-projekt-hinzufügen), verwendet Starlight die Werte aus deiner [Tailwind-Themenkonfiguration](https://tailwindcss.com/docs/theme) in der Datei `src/styles/global.css`, um die Benutzeroberfläche zu gestalten.

Wenn diese Option aktiviert ist, überschreiben die folgenden benutzerdefinierten CSS-Eigenschaften die Standardstile von Starlight:

- `--color-accent-*` - wird für Links und die Hervorhebung des aktuellen Elements verwendet
- `--color-gray-*` - wird für Hintergrundfarben und Rahmen verwendet
- `--font-sans` - wird für UI und Inhaltstext verwendet
- `--font-mono` - wird für Code-Beispiele verwendet

```css {9-12,14-17,19-22,34-37}
/* src/styles/global.css */
@layer base, starlight, theme, components, utilities;

@import '@astrojs/starlight-tailwind';
@import 'tailwindcss/theme.css' layer(theme);
@import 'tailwindcss/utilities.css' layer(utilities);

@theme {
	/* 
	Deine bevorzugte Schriftart.
	Starlight verwendet standardmäßig eine Systemschriftart.
	*/
	--font-sans: 'Atkinson Hyperlegible';
	/* 
	Deine bevorzugte Code-Schriftart.
	Starlight verwendet standardmäßig die Systemschriftart Monospace.
	*/
	--font-mono: 'IBM Plex Mono';
	/* 
	Deine bevorzugte Akzentfarbe.
	Indigo entspricht am ehesten den Standardeinstellungen von Starlight.
	*/
	--color-accent-50: var(--color-indigo-50);
	--color-accent-100: var(--color-indigo-100);
	--color-accent-200: var(--color-indigo-200);
	--color-accent-300: var(--color-indigo-300);
	--color-accent-400: var(--color-indigo-400);
	--color-accent-500: var(--color-indigo-500);
	--color-accent-600: var(--color-indigo-600);
	--color-accent-700: var(--color-indigo-700);
	--color-accent-800: var(--color-indigo-800);
	--color-accent-900: var(--color-indigo-900);
	--color-accent-950: var(--color-indigo-950);
	/* 
	Deine bevorzugte Grauskala.
	Zink kommt den Standardeinstellungen von Starlight am nächsten.
	*/
	--color-gray-50: var(--color-zinc-50);
	--color-gray-100: var(--color-zinc-100);
	--color-gray-200: var(--color-zinc-200);
	--color-gray-300: var(--color-zinc-300);
	--color-gray-400: var(--color-zinc-400);
	--color-gray-500: var(--color-zinc-500);
	--color-gray-600: var(--color-zinc-600);
	--color-gray-700: var(--color-zinc-700);
	--color-gray-800: var(--color-zinc-800);
	--color-gray-900: var(--color-zinc-900);
	--color-gray-950: var(--color-zinc-950);
}
```

### Mehrere Tailwind-Konfigurationen verwenden

Mehrere Tailwind-Konfigurationen können verwendet werden, um verschiedene Stile auf verschiedene Teile deiner Website anzuwenden, z. B. wenn du [Starlight in einem Unterpfad verwendest](/de/manual-setup/#starlight-mit-einem-anderen-pfad-verwenden) oder wenn du [benutzerdefinierte Seiten](/de/guides/pages/#benutzerdefinierte-seiten) zu deiner Website hinzufügst.
Du möchtest vielleicht die Preflight-Reset-Stile von Tailwind auf deinen benutzerdefinierten Seiten verwenden und trotzdem die Kompatibilitätsschicht von Starlight auf Starlight-Seiten anwenden.

Die folgende Tailwind-CSS-Konfiguration richtet Tailwind ohne Plugins oder zusätzliche Einstellungen ein und kann als Ausgangspunkt für Seiten verwendet werden, die nicht mit Starlight erstellt wurden:

```css title="src/styles/custom-pages-tailwind.css"
/* Lade Tailwind ohne die zusätzlichen CSS-Dateien von Starlight. */
@import 'tailwindcss';
```

<Steps>

1. Nimm für Starlight-Seiten deine bevorzugte Tailwind-CSS-Konfiguration, indem du [„Tailwind zu einem bestehenden Projekt hinzufügen“](#tailwind-zu-einem-bestehenden-projekt-hinzufügen) befolgst.

2. Für andere Seiten nimm einfach deine Tailwind CSS-Einstellungen, indem du sie dort importierst. Das macht man oft in einer Layout-Komponente, damit die Tailwind-Stile auf allen Seiten mit dem gleichen Layout funktionieren.
   ```astro
   ---
   // src/layouts/CustomPageLayout.astro
   import '../styles/custom-pages-tailwind.css';
   ---
   ```

</Steps>

Weitere Infos zu Tailwind-Theme-Konfigurationen findest du in der [Tailwind CSS-Dokumentation](https://tailwindcss.com/docs/theme).

## Themes

Das Farbtheme von Starlight kann gesteuert werden, indem die Standard­einstellungen überschrieben werden.
Diese Variablen werden in der gesamten Benutzeroberfläche verwendet, wobei eine Reihe von Grautönen für Text- und Hintergrundfarben sowie eine Akzentfarbe für Links und zur Hervorhebung aktueller Elemente in der Navigation verwendet werden.

### Farbdesign-Editor

Verwende die Schieberegler unten, um die Akzent- und Graufarbpalette von Starlight zu ändern.
Die dunklen und hellen Vorschaubereiche zeigen die resultierenden Farben, und die gesamte Seite wird ebenfalls aktualisiert, um deine Änderungen anzuzeigen.

Verwende die Option Kontraststufe, um festzulegen, welche der Richtlinie für die Zugänglichkeit von Webinhalten [Farbkontrast­standards](https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable/Color_contrast) erfüllt werden soll.

Wenn du mit deinen Änderungen zufrieden bist, kopiere den CSS- oder Tailwind-Code unten und verwende ihn in deinem Projekt.

import ThemeDesigner from '~/components/theme-designer.astro';

<ThemeDesigner
	labels={{
		presets: {
			label: 'Voreinstellungen',
			ocean: 'Ozean',
			forest: 'Wald',
			oxide: 'Oxid',
			nebula: 'Nebel',
			default: 'Standard',
			random: 'Zufällig',
		},
		contrast: {
			label: 'Kontraststufe',
		},
		editor: {
			accentColor: 'Akzent',
			grayColor: 'Grau',
			hue: 'Farbton',
			chroma: 'Sättigung',
			pickColor: 'Wähle Farbe',
		},
		preview: {
			darkMode: 'Dark mode',
			lightMode: 'Light mode',
			bodyText:
				'Der Fließtext wird in einem Grauton mit hohem Kontrast zum Hintergrund dargestellt.',
			linkText: 'Links sind farbig.',
			dimText:
				'Einige Texte, wie z. B. das Inhaltsverzeichnis, haben einen geringeren Kontrast.',
			inlineCode: 'Inline-Code hat einen eindeutigen Hintergrund.',
		},
	}}
>
	<Fragment slot="css-docs">
		Füge das folgende CSS in deinem Projekt in eine [benutzerdefinierte
		CSS-Datei](#benutzerdefinierte-css-styles-stile) ein, um dieses Theme auf
		deiner Website anzuwenden.
	</Fragment>
	<Fragment slot="tailwind-docs">
		Füge die folgenden CSS-Variablen in den `@theme`-Block in deiner
		[Tailwind-CSS Datei](#starlight-mit-tailwind-designen) hinzu, um dieses
		Thema auf deiner Seite anzuwenden.
	</Fragment>
</ThemeDesigner>


================================================
FILE: docs/src/content/docs/de/guides/customization.mdx
================================================
---
title: Starlight anpassen
description: Lerne, wie du deine Starlight-Website mit deinem Logo, eigenen Schriftarten, Landing-Page-Design und vielem mehr zu deiner eigenen machen kannst.
---

import { Tabs, TabItem, FileTree, Steps } from '@astrojs/starlight/components';

Starlight bietet sinnvolle Standard-Styling und -Funktionen, so dass du schnell loslegen kannst, ohne dass eine Konfiguration erforderlich ist.
Wenn du das Aussehen deiner Starlight-Website anpassen willst, findest du in dieser Anleitung alle nötigen Informationen.

## Dein Logo hinzufügen

Das Hinzufügen eines eigenen Logos im Header ist ein schneller Weg, um einer Starlight-Website dein individuelles Branding zu geben.

<Steps>

1. Füge deine Logodatei in das Verzeichnis `src/assets/` ein:

   <FileTree>

   - src/
     - assets/
       - **mein-logo.svg**
     - content/
   - astro.config.mjs

   </FileTree>

2. Füge den Pfad zu deinem Logo als Starlights [`logo.src`](/de/reference/configuration/#logo) Option in `astro.config.mjs` ein:

   ```diff lang="js"
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Dokumentation mit meinem Logo',
   			logo: {
   +				src: './src/assets/mein-logo.svg',
   			},
   		}),
   	],
   });
   ```

</Steps>

Standardmäßig wird das Logo neben dem `title` deiner Website angezeigt.
Wenn dein Logobild bereits den Titel der Website enthält, kannst du den Titeltext optisch ausblenden, indem du die Option `replacesTitle` setzt.
Der `title`-Text wird für Bildschirmleser weiterhin angezeigt, so dass die Kopfzeile zugänglich bleibt.

```js {5}
starlight({
  title: 'Dokumentation mit meinem Logo',
  logo: {
    src: './src/assets/mein-logo.svg',
    replacesTitle: true,
  },
}),
```

### Light- und Dark-Mode Logovarianten

Du kannst verschiedene Versionen deines Logos im Light- und Dark-Mode anzeigen.

<Steps>

1. Füge eine Bilddatei für jede Variante zu `src/assets/` hinzu:

   <FileTree>

   - src/
     - assets/
       - **light-logo.svg**
       - **dark-logo.svg**
     - content/
   - astro.config.mjs

   </FileTree>

2. Füge den Pfad zu deiner Logovarianten als die Optionen `light` und `dark` anstelle von `src` in `astro.config.mjs` ein:

   ```diff lang="js"
   starlight({
     title: 'Dokumentation mit meinem Logo',
     logo: {
   +    light: './src/assets/light-logo.svg',
   +    dark: './src/assets/dark-logo.svg',
     },
   }),
   ```

</Steps>

## Sitemap aktivieren

Starlight hat eine eingebaute Unterstützung für die Erstellung einer Sitemap. Aktiviere die Sitemap-Generierung, indem du deine URL als `site` in `astro.config.mjs` angibst:

```js {4}
// astro.config.mjs

export default defineConfig({
	site: 'https://stargazers.club',
	integrations: [starlight({ title: 'Website mit Sitemap' })],
});
```

Erfahre in den Astro Docs, wie du [einen Sitemap-Link zur `robots.txt` hinzufügst] (https://docs.astro.build/de/guides/integrations-guide/sitemap/#sitemap-link-in-robotstxt).

## Seitenlayout

Starlight-Seiten verwenden standardmäßig ein Layout mit einer globalen Navigation und einem Inhaltsverzeichnis, das die aktuellen Seitenüberschriften anzeigt.

Du kannst ein breiteres Seitenlayout ohne Navigationen verwenden, indem du [`template: splash`](/de/reference/frontmatter/#template) im Frontmatter einer Seite setzt.
Dies funktioniert besonders gut für Landingpages, und du kannst es in Aktion auf der [Homepage dieser Website](/de/) sehen.

```md {5}
---
# src/content/docs/index.md

title: Meine Landing Page
template: splash
---
```

## Inhaltsverzeichnis

Starlight zeigt auf jeder Seite ein Inhaltsverzeichnis an, um es den Lesern zu erleichtern, zu der gesuchten Überschrift zu springen.
Du kannst das Inhaltsverzeichnis global in der Starlight-Integration oder seitenweise im Frontmatter anpassen - oder sogar deaktivieren.

Standardmäßig werden die Überschriften `<h2>` und `<h3>` in das Inhaltsverzeichnis aufgenommen. Ändere die Überschriftsebenen für die gesamte Website mit den Optionen `minHeadingLevel` und `maxHeadingLevel` in deinem [globalen `tableOfContents`](/de/reference/configuration/#tableofcontents). Überschreibe diese Standardwerte auf einer individuellen Seite, indem du die entsprechenden [Frontmatter `tableOfContents`](/de/reference/frontmatter/#tableofcontents) Eigenschaften hinzufügst:

<Tabs syncKey="config-type">
  <TabItem label="Frontmatter">

```md {4-6}
---
# src/content/docs/example.md
title: Seite mit nur H2s im Inhaltsverzeichnis
tableOfContents:
  minHeadingLevel: 2
  maxHeadingLevel: 2
---
```

  </TabItem>
  <TabItem label="Globale Konfiguration">

```js {7}
// astro.config.mjs

defineConfig({
	integrations: [
		starlight({
			title: 'Dokumentation mit benutzerdefinierten Inhaltsverzeichnissen',
			tableOfContents: { minHeadingLevel: 2, maxHeadingLevel: 2 },
		}),
	],
});
```

  </TabItem>
</Tabs>

Deaktiviere das Inhaltsverzeichnis vollständig, indem du die Option `tableOfContents` auf `false` setzt:

<Tabs syncKey="config-type">
  <TabItem label="Frontmatter">

```md {4}
---
# src/content/docs/example.md
title: Seite ohne Inhaltsverzeichnis
tableOfContents: false
---
```

  </TabItem>
  <TabItem label="Globale Konfiguration">

```js {7}
// astro.config.mjs

defineConfig({
	integrations: [
		starlight({
			title: 'Dokumentation mit global deaktiviertem Inhaltsverzeichnis',
			tableOfContents: false,
		}),
	],
});
```

  </TabItem>
</Tabs>

## Soziale Links

Starlight bietet integrierte Unterstützung für das Hinzufügen von Links zu deinen Social-Media-Accounts in der Kopfzeile der Website über die Option [`social`](/de/reference/configuration/#social) in der Starlight-Integration.

Jeder Eintrag im Array `social` muss ein Objekt mit drei Eigenschaften sein:

- `icon`: eines der [eingebauten Symbolen](/de/reference/icons/) von Starlight, z. B. `"github"`.
- `label`: eine zugängliche Bezeichnung für den Link, z. B. `"GitHub"`.
- `href`: die URL für den Link, z. B. `"https://github.com/withastro/starlight"`.

Das folgende Beispiel fügt Links zum Astro Discord Chat und zum Starlight GitHub Repository hinzu:

```js {9-16}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Dokumentation mit sozialen Links',
			social: [
				{ icon: 'discord', label: 'Discord', href: 'https://astro.build/chat' },
				{
					icon: 'github',
					label: 'GitHub',
					href: 'https://github.com/withastro/starlight',
				},
			],
		}),
	],
});
```

## Bearbeitungslinks

Starlight kann einen "Seite bearbeiten"-Link in der Fußzeile jeder Seite anzeigen.
Dies macht es dem Leser leicht, die zu bearbeitende Datei zu finden, um deine Dokumentation zu verbessern.
Insbesondere bei Open-Source-Projekten kann dies dazu beitragen, Beiträge aus deiner Community zu fördern.

Um Edit-Links zu aktivieren, setze [`editLink.baseUrl`](/de/reference/configuration/#editlink) auf die URL, die du zum Bearbeiten deines Repositorys in der Starlight-Integrations­konfiguration verwendest.
Der Wert von `editLink.baseUrl` wird dem Pfad zur aktuellen Seite vorangestellt, um den vollständigen Bearbeitungslink zu bilden.

Übliche Muster sind:

- GitHub: `https://github.com/BENUTZERNAME/REPOSITORY_NAME/edit/BRANCH_NAME/`
- GitLab: `https://gitlab.com/BENUTZERNAME/REPOSITORY_NAME/-/edit/BRANCH_NAME/`

Wenn sich dein Starlight-Projekt nicht im Stammverzeichnis deines Repositorys befindet, füge den Pfad zum Projekt am Ende der Basis-URL ein.

Dieses Beispiel zeigt den Bearbeitungslink, der für die Starlight-Dokumentation konfiguriert ist, die sich im Unterverzeichnis `docs/` im `main`-Branch des `withastro/starlight`-Repository auf GitHub befinden:

```js {9-11}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Dokumentation mit Bearbeitungslinks',
			editLink: {
				baseUrl: 'https://github.com/withastro/starlight/edit/main/docs/',
			},
		}),
	],
});
```

## Benutzerdefinierte 404-Seite

Starlight-Websites zeigen standardmäßig eine einfache 404-Seite an.
Du kannst dies anpassen, indem du eine `404.md` (oder `404.mdx`) Datei zu deinem `src/content/docs/` Verzeichnis hinzufügst:

<FileTree>

- src/
  - content/
    - docs/
      - **404.md**
      - index.md
- astro.config.mjs

</FileTree>

Du kannst alle Seitenlayout- und Anpassungstechniken von Starlight in deiner 404-Seite verwenden. Zum Beispiel verwendet die Standard 404-Seite die [`splash` Vorlage](#seitenlayout) und [`hero`](/de/reference/frontmatter/#hero) Komponente in Frontmatter:

```md {4,6-8}
---
# src/content/docs/404.md
title: '404'
template: splash
editUrl: false
hero:
  title: '404'
  tagline: Seite nicht gefunden. Überprüfe die URL oder versuche es mit der Suchfunktion.
---
```

### Deaktivieren der Standard-404-Seite

Wenn dein Projekt ein komplett angepasstes 404-Layout benötigt, kannst du eine `src/pages/404.astro`-Route erstellen und die [`disable404Route`](/de/reference/configuration/#disable404route) Konfigurations­option setzen, um die Standard-Route von Starlight zu deaktivieren:

```js {9}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Dokumentation mit benutzerdefinierten 404',
			disable404Route: true,
		}),
	],
});
```

## Benutzerdefinierte Schriftarten

Standardmäßig verwendet Starlight serifenlose Schriften, die auf dem lokalen Gerät des Benutzers verfügbar sind, für den gesamten Text.
Dadurch wird sichergestellt, dass die Dokumentation schnell in einer Schriftart geladen wird, die jedem Benutzer vertraut ist, ohne dass zusätzliche Bandbreite für das Herunterladen großer Schriftdateien benötigt wird.

Wenn du deiner Starlight-Website eine eigene Schriftart hinzufügen musst, kannst du die Schriftarten in eigenen CSS-Dateien oder mit anderen [Astro-Styling-Techniken](https://docs.astro.build/de/guides/styling/) einrichten.

### Schriftarten einrichten

Wenn du bereits über Schriftartdateien verfügst, folge der [Anleitung zum Einrichten lokaler Schriftartdateien](#lokale-schriftartendateien-einrichten).
Um Google Fonts zu verwenden, folge der [Anleitung Fontsource einrichten](#einrichten-einer-fontsource-schriftart).

#### Lokale Schriftartendateien einrichten

<Steps>

1. Füge deine Schriftdateien in ein `src/fonts/`-Verzeichnis ein und erstelle eine leere `font-face.css`-Datei:

   <FileTree>

   - src/
     - content/
     - fonts/
       - **CustomFont.woff2**
       - **font-face.css**
   - astro.config.mjs

   </FileTree>

2. Füge eine [`@font-face`-Deklaration](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face) für jede deiner Schriftarten in `src/fonts/font-face.css` ein.
   Verwende einen relativen Pfad zu der Schriftartdatei in der Funktion `url()`.

   ```css
   /* src/fonts/font-face.css */

   @font-face {
   	font-family: 'Custom Font';
   	/* Verwende einen relativen Pfad zur lokalen Schriftdatei in `url()`. */
   	src: url('./CustomFont.woff2') format('woff2');
   	font-weight: normal;
   	font-style: normal;
   	font-display: swap;
   }
   ```

3. Füge den Pfad zu deiner `font-face.css`-Datei zu Starlights `customCss`-Array in `astro.config.mjs` hinzu:

   ```diff lang="js"
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Dokumentation mit benutzerdefinierter Schriftart',
   			customCss: [
   +				// Relativer Pfad zu deiner @font-face CSS-Datei.
   +				'./src/fonts/font-face.css',
   			],
   		}),
   	],
   });
   ```

</Steps>

#### Einrichten einer Fontsource-Schriftart

Das [Fontsource](https://fontsource.org/) Projekt vereinfacht die Verwendung von Google Fonts und anderen Open-Source-Schriften.
Es bietet npm-Module, die du für die gewünschten Schriftarten installieren kannst, und enthält fertige CSS-Dateien, die du deinem Projekt hinzufügen kannst.

<Steps>

1.  Suche die Schriftart, die du verwenden möchten, im [Fontsource-Katalog](https://fontsource.org/).
    In diesem Beispiel wird [IBM Plex Serif](https://fontsource.org/fonts/ibm-plex-serif) verwendet.

2.  Installiere das Paket für deine gewählte Schriftart.
    Du findest den Namen des Pakets, indem du auf der Fontsource-Website auf `Installieren` klickst.

         <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npm install @fontsource/ibm-plex-serif
    ```

           </TabItem>

        <TabItem label="pnpm">

    ```sh
    pnpm add @fontsource/ibm-plex-serif
    ```

           </TabItem>

        <TabItem label="Yarn">

    ```sh
    yarn add @fontsource/ibm-plex-serif
    ```

           </TabItem>

      </Tabs>

3.  Füge die CSS-Dateien von Fontsource zum Array `customCss` von Starlight in `astro.config.mjs` hinzu:

    ```diff lang="js"
    // astro.config.mjs
    import { defineConfig } from 'astro/config';
    import starlight from '@astrojs/starlight';

    export default defineConfig({
    	integrations: [
    		starlight({
    			title: 'Dokumentation mit benutzerdefinierter Schriftart',
    			customCss: [
    +				// Schriftquelldateien für normale und halbfette Schriftschnitte.
    +				'@fontsource/ibm-plex-serif/400.css',
    +				'@fontsource/ibm-plex-serif/600.css',
    			],
    		}),
    	],
    });
    ```

    Fontsource liefert mehrere CSS-Dateien für jede Schriftart. Siehe die [Fontsource-Dokumentation](https://fontsource.org/docs/getting-started/install#4-weights-and-styles) über das Einbinden verschiedener Schriftstärken und Styles, um zu verstehen, welche zu verwenden sind.

</Steps>

### Schriftarten verwenden

Um deine eingerichtete Schriftart auf deiner Website anzuwenden, verwende den Namen der gewählten Schriftart in einer [benutzerdefinierten CSS-Datei](/de/guides/css-and-tailwind/#benutzerdefinierte-css-styles-stile).
Um zum Beispiel die Standard-Schriftart von Starlight überall zu überschreiben, setze die benutzerdefinierte Eigenschaft `--sl-font`:

```css
/* src/styles/custom.css */

:root {
	--sl-font: 'IBM Plex Serif', serif;
}
```

Du kannst auch spezifischeres CSS schreiben, wenn du deine Schriftart selektiver anwenden willst.
Zum Beispiel, um eine Schriftart nur auf den Hauptinhalt zu setzen, aber nicht auf die Seitennavigation:

```css
/* src/styles/custom.css */

main {
	font-family: 'IBM Plex Serif', serif;
}
```

Folge der [Anleitung für benutzerdefiniertes CSS-Styles](/de/guides/css-and-tailwind/#benutzerdefinierte-css-styles-stile), um deine Styles zu deiner Website hinzuzufügen.


================================================
FILE: docs/src/content/docs/de/guides/i18n.mdx
================================================
---
title: Internationalisierung (i18n)
description: Lerne, wie du deine Starlight-Website so konfigurierst, dass sie mehrere Sprachen unterstützt.
---

import { FileTree, Steps } from '@astrojs/starlight/components';

Starlight bietet eingebaute Unterstützung für mehrsprachige Websites, einschließlich Routing, Fallback-Inhalte und vollständige Unterstützung von rechts-nach-links (RTL) Sprachen.

## Konfiguriere i18n

<Steps>

1. Teile Starlight mit, welche Sprachen du unterstützt, indem du [`locales`](/de/reference/configuration/#locales) und [`defaultLocale`](/de/reference/configuration/#defaultlocale) an die Starlight Integration übergibst:

   ```js {9-26}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Meine Dokumentation',
   			// Lege Englisch als Standardsprache für diese Website fest.
   			defaultLocale: 'en',
   			locales: {
   				// Englische Dokumentation in `src/content/docs/en/`
   				en: {
   					label: 'English',
   				},
   				// Vereinfachte chinesische Dokumentation in `src/content/docs/zh-cn/`
   				'zh-cn': {
   					label: '简体中文',
   					lang: 'zh-CN',
   				},
   				// Arabische Dokumentation in `src/content/docs/ar/`
   				ar: {
   					label: 'العربية',
   					dir: 'rtl',
   				},
   			},
   		}),
   	],
   });
   ```

   Dein `defaultLocale` wird für Fallback-Inhalte und UI-Labels verwendet, wähle also die Sprache, in der du am ehesten mit dem Schreiben von Inhalten beginnen wirst oder für die du bereits Inhalte hast.

2. Erstelle ein Verzeichnis für jede Sprache in `src/content/docs/`.
   Für die oben gezeigte Konfiguration erstellst du zum Beispiel die folgenden Verzeichnisse:

   <FileTree>

   - src/
     - content/
       - docs/
         - ar/
         - en/
         - zh-cn/

   </FileTree>

3. Du kannst nun Inhaltsdateien in deinen Sprach­verzeichnissen hinzufügen. Verwende den gleichen Dateinamen, um Seiten in verschiedenen Sprachen zuzuordnen und nutze Starlights volle i18n-Funktionen, einschließlich Fallback-Inhalte, Übersetzungs­hinweise und mehr.

   Erstelle zum Beispiel `ar/index.md` und `en/index.md`, um die Homepage für Arabisch bzw. Englisch darzustellen.

</Steps>

Für fortgeschrittene i18n-Szenarien unterstützt Starlight auch die Konfiguration der Internationalisierung mit [Astro's `i18n`-Konfigurations­option](https://docs.astro.build/de/guides/internationalization/#configure-i18n-routing).

### Verwende ein Root-Verzeichnis

Du kannst ein Root-Verzeichnis verwenden, um eine Sprache ohne i18n-Präfix in ihrem Pfad anzubieten. Wenn zum Beispiel Englisch dein Stammverzeichnis ist, würde ein englischer Seitenpfad unter `/about` anstelle von `/en/about` zu finden sein.

Um ein Stammverzeichnis festzulegen, verwende den Key `root` in deiner `locales`-Konfiguration. Wenn das Root-Verzeichnis auch das Standard-Verzeichnis für deinen Inhalt ist, entferne `defaultLocale` oder setze es auf `'root'`.

```js {9,11-14}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Meine Dokumentation',
			defaultLocale: 'root', // optional
			locales: {
				root: {
					label: 'English',
					lang: 'en', // lang ist für Stammverzeichnis erforderlich
				},
				'zh-cn': {
					label: '简体中文',
					lang: 'zh-CN',
				},
			},
		}),
	],
});
```

Wenn du ein `root`-Verzeichnis verwendest, speichere die Seiten für diese Sprache direkt in `src/content/docs/`, anstatt in einem speziellen Sprachordner. Zum Beispiel sind hier die Homepage-Dateien für Englisch und Chinesisch, wenn man die obige Konfiguration verwendet:

<FileTree>

- src/
  - content/
    - docs/
      - **index.md**
      - zh-cn/
        - **index.md**

</FileTree>

#### Einsprachige Websites

Standardmäßig ist Starlight eine einsprachige (englische) Website. Um eine einsprachige Website in einer anderen Sprache zu erstellen, setze diese als `root` in deiner `locales` Konfiguration:

```diff lang="js" {10-13}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'My Docs',
			locales: {
				root: {
					label: '简体中文',
					lang: 'zh-CN',
				},
			},
		}),
	],
});
```

Dies ermöglicht es dir, die Standardsprache von Starlight zu überschreiben, ohne andere Internationalisierungs­funktionen für mehrsprachige Websites zu aktivieren, wie z. B. die Sprachauswahl.

## Fallback-Inhalt

Starlight erwartet, dass du äquivalente Seiten in allen deinen Sprachen erstellst. Wenn du zum Beispiel eine `de/about.md` Datei hast, erstelle eine `about.md` für jede andere Sprache, die du unterstützt. Dies ermöglicht Starlight, automatisch Ersatzinhalte für Seiten zu liefern, die noch nicht übersetzt wurden.

Wenn für eine Sprache noch keine Übersetzung verfügbar ist, zeigt Starlight den Lesern den Inhalt dieser Seite in der Standardsprache (eingestellt über `defaultLocale`). Wenn du z. B. noch keine französische Version deiner "About"-Seite erstellt hast und deine Standardsprache Englisch ist, werden Besucher von `/fr/about` den englischen Inhalt von `/en/about` sehen, mit einem Hinweis, dass diese Seite noch nicht übersetzt wurde. Auf diese Weise kannst du Inhalte in deiner Standardsprache hinzufügen und sie dann nach und nach übersetzen, wenn du Lust dazu hast.

## Übersetze den Seitentitel

Standardmäßig verwendet Starlight denselben Titel für alle Sprachen.
Wenn du den Titel für jedes Gebietsschema anpassen möchtest, kannst du in den Optionen von Starlight ein Objekt an [`title`](/de/reference/configuration/#title-erforderlich) übergeben:

```diff lang="js"
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
-			title: 'My Docs',
+			title: {
+				en: 'My Docs',
+				'zh-CN': '我的文档',
+			},
			defaultLocale: 'en',
			locales: {
				en: { label: 'English' },
				'zh-cn': { label: '简体中文', lang: 'zh-CN' },
			},
		}),
	],
});
```

## Starlights UI übersetzen

import LanguagesList from '~/components/languages-list.astro';
import UIStringsList from '~/components/ui-strings-list.astro';

Starlight bietet nicht nur übersetzte Inhaltsdateien, sondern auch die Möglichkeit, die Standard-Benutzeroberfläche zu übersetzen (z. B. die Überschrift "Auf dieser Seite" im Inhaltsverzeichnis), so dass deine Leser deine Website vollständig in der ausgewählten Sprache erleben können.

<LanguagesList startsSentence /> werden standardmäßig übersetzt, und wir freuen
uns über [Beiträge zur Aufnahme weiterer
Standardsprachen](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md).

Du kannst Übersetzungen für zusätzliche Sprachen, die du unterstützt, über die `i18n` Datensammlung zur Verfügung stellen - oder unsere Standard­bezeichnungen überschreiben.

<Steps>

1. Konfiguriere die `i18n` Datensammlung in `src/content.config.ts`, wenn sie nicht bereits konfiguriert ist:

   ```diff lang="js" ins=/, (i18nLoader|i18nSchema)/
   // src/content.config.ts
   import { defineCollection } from 'astro:content';
   import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
   import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';

   export const collections = {
   	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
   +	i18n: defineCollection({ loader: i18nLoader(), schema: i18nSchema() }),
   };
   ```

2. Erstelle eine JSON-Datei in `src/content/i18n/` für jedes zusätzliche Gebietsschema, für das du UI-Übersetzungsstrings bereitstellen möchtest.
   Dies würde zum Beispiel Übersetzungsdateien für Arabisch und vereinfachtes Chinesisch hinzufügen:

   <FileTree>

   - src/
     - content/
       - i18n/
         - ar.json
         - zh-CN.json

   </FileTree>

3. Füge Übersetzungen für die Schlüssel hinzu, die in den JSON-Dateien übersetzt werden sollen. Übersetze nur die Werte und belasse die Schlüssel auf Englisch (z. B. `"search.label": "Buscar"`).

   Dies sind die englischen Standardwerte der vorhandenen Strings, mit denen Starlight ausgeliefert wird:

   <UIStringsList />

   Die Codeblöcke von Starlight werden von der [Expressive Code](https://expressive-code.com/) Bibliothek unterstützt.
   Du kannst die Übersetzungen für die UI-Strings in derselben JSON-Datei mit Hilfe von `expressiveCode`-Schlüsseln festlegen:

   ```json
   {
   	"expressiveCode.copyButtonCopied": "Copied!",
   	"expressiveCode.copyButtonTooltip": "Copy to clipboard",
   	"expressiveCode.terminalWindowFallbackTitle": "Terminal window"
   }
   ```

   Die Suchfunktion von Starlight wird von der [Pagefind-Bibliothek](https://pagefind.app/) unterstützt.
   Du kannst die Übersetzungen für Pagefinds UI in der gleichen JSON Datei mit `pagefind`-Schlüsseln setzen:

   ```json
   {
   	"pagefind.clear_search": "Clear",
   	"pagefind.load_more": "Load more results",
   	"pagefind.search_label": "Search this site",
   	"pagefind.filters_label": "Filters",
   	"pagefind.zero_results": "No results for [SEARCH_TERM]",
   	"pagefind.many_results": "[COUNT] results for [SEARCH_TERM]",
   	"pagefind.one_result": "[COUNT] result for [SEARCH_TERM]",
   	"pagefind.alt_search": "No results for [SEARCH_TERM]. Showing results for [DIFFERENT_TERM] instead",
   	"pagefind.search_suggestion": "No results for [SEARCH_TERM]. Try one of the following searches:",
   	"pagefind.searching": "Searching for [SEARCH_TERM]..."
   }
   ```

</Steps>

### Übersetzungsschema erweitern

Füge benutzerdefinierte Schlüssel zu den Übersetzungs­wörterbüchern deiner Website hinzu, indem du die Option `extend` in den `i18nSchema()`-Optionen setzt.
Im folgenden Beispiel wird ein neuer, optionaler Schlüssel `custom.label` zu den Standardschlüsseln hinzugefügt:

```diff lang="js"
// src/content.config.ts
import { defineCollection, z } from 'astro:content';
import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';

export const collections = {
	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
	i18n: defineCollection({
		loader: i18nLoader(),
		schema: i18nSchema({
+			extend: z.object({
+				'custom.label': z.string().optional(),
+			}),
		}),
	}),
};
```

Mehr über Inhaltssammlungs­schemas erfährst du in [„Ein Sammelschema definieren“](https://docs.astro.build/de/guides/content-collections/#defining-the-collection-schema) in der Astro-Dokumentation.

## UI-Übersetzungen verwenden

Du kannst auf Starlights [eingebaute UI-Strings](/de/guides/i18n/#starlights-ui-übersetzen) sowie auf [benutzerdefinierte](/de/guides/i18n/#übersetzungsschema-erweitern) und [plugin-provided](/de/reference/plugins/#injecttranslations) UI-Strings über eine einheitliche API zugreifen, die von [i18next](https://www.i18next.com/) unterstützt wird.
Dazu gehört die Unterstützung von Funktionen wie [Interpolation](https://www.i18next.com/translation-function/interpolation) und [Pluralisierung](https://www.i18next.com/translation-function/plurals).

In Astro-Komponenten ist diese API als Teil des [globalen `Astro`-Objekts](https://docs.astro.build/de/reference/api-reference/#locals) als `Astro.locals.t` verfügbar:

```astro title="example.astro"
<p dir={Astro.locals.t.dir()}>
	{Astro.locals.t('404.text')}
</p>
```

Du kannst die API auch bei [Endpunkten](https://docs.astro.build/de/guides/endpoints/) verwenden, wo das Objekt `locals` als Teil des [Endpunkt-Kontextes](https://docs.astro.build/de/reference/api-reference/#locals) verfügbar ist:

```ts title="src/pages/404.ts"
export const GET = (context) => {
	return new Response(context.locals.t('404.text'));
};
```

Im Kontext eines Starlight-Plugins kannst du den Helfer [`useTranslations()`](/de/reference/plugins/#usetranslations) verwenden, um auf diese API für eine bestimmte Sprache zuzugreifen.
Weitere Informationen findest du in der [Plugins Referenz](/de/reference/plugins/).

### Rendering eines UI-Strings

Rendere UI-Strings mit der Funktion `locals.t()`.
Dies ist eine Instanz der i18next-Funktion `t()`, die einen UI-String-Schlüssel als erstes Argument nimmt und die entsprechende Übersetzung für die aktuelle Sprache zurückgibt.

Nehmen wir zum Beispiel eine benutzerdefinierte Übersetzungsdatei mit folgendem Inhalt:

```json title="src/content/i18n/de.json"
{
	"link.astro": "Astro Dokumentation",
	"link.astro.custom": "Astro-Dokumentation für {{feature}}"
}
```

Der erste UI-String kann gerendert werden, indem man `'link.astro'` an die Funktion `t()` übergibt:

```astro {3}
<!-- src/components/Example.astro -->
<a href="https://docs.astro.build/">
	{Astro.locals.t('link.astro')}
</a>
<!-- Rendert: <a href="...">Astro Dokumentation</a> -->
```

Der zweite UI-String verwendet die [Interpolations­syntax](https://www.i18next.com/translation-function/interpolation) von i18next für den Platzhalter `{{feature}}`.
Der Wert für `feature` muss in einem Optionsobjekt gesetzt werden, das als zweites Argument an `t()` übergeben wird:

```astro {3}
<!-- src/components/Example.astro -->
<a href="https://docs.astro.build/en/guides/astro-db/">
	{Astro.locals.t('link.astro.custom', { feature: 'Astro DB' })}
</a>
<!-- Rendert: <a href="...">Astro-Dokumentation für Astro DB</a> -->
```

In der [i18next-Dokumentation](https://www.i18next.com/overview/api#t) findest du weitere Informationen darüber, wie du die Funktion `t()` mit Interpolation, Formatierung und mehr verwenden kannst.

### Fortgeschrittene APIs

#### `t.all()`

Die Funktion `locals.t.all()` gibt ein Objekt zurück, das alle für das aktuelle Gebietsschema verfügbaren UI-Strings enthält.

```astro
---
// src/components/Example.astro
const allStrings = Astro.locals.t.all();
//    ^
//    {
//      "skipLink.label": "Zum Inhalt springen",
//      "search.label": "Suche",
//      …
//    }
---
```

#### `t.exists()`

Um zu überprüfen, ob ein Übersetzungs­schlüssel existiert, verwende die Funktion `locals.t.exists()` mit dem Übersetzungs­schlüssel als erstem Argument.
Gib ein optionales zweites Argument an, wenn du überprüfen möchtest, ob eine Übersetzung für eine bestimmte Sprache vorhanden ist.

```astro
---
// src/components/Example.astro
const keyExists = Astro.locals.t.exists('a.key');
//    ^ true
const keyExistsInFrench = Astro.locals.t.exists('other.key', { lngs: ['fr'] });
//    ^ false
---
```

Siehe [Verweis auf `exists()` in der i18next-Dokumentation](https://www.i18next.com/overview/api#exists) für weitere Informationen.

#### `t.dir()`

Die Funktion `locals.t.dir()` gibt die Textrichtung des aktuellen oder eines bestimmten Gebietsschemas zurück.

```astro
---
// src/components/Example.astro
const currentDirection = Astro.locals.t.dir();
//    ^
//    'ltr'
const arabicDirection = Astro.locals.t.dir('ar');
//    ^
//    'rtl'
---
```

Weitere Informationen findest du in der [`dir()`-Referenz in der i18next-Dokumentation](https://www.i18next.com/overview/api#dir).

## Zugriff auf das aktuelle Gebietsschema

Du kannst [`Astro.currentLocale`](https://docs.astro.build/de/reference/api-reference/#currentlocale) verwenden, um das aktuelle Gebietsschema in `.astro` Komponenten zu lesen.

Das folgende Beispiel liest das aktuelle Gebietsschema aus und verwendet es mit Hilfe der [`getRelativeLocaleUrl()`](https://docs.astro.build/de/reference/modules/astro-i18n/#getrelativelocaleurl)-Methode, um einen Link zu einer Informationsseite in der aktuellen Sprache zu erzeugen:

```astro
---
// src/components/AboutLink.astro
import { getRelativeLocaleUrl } from 'astro:i18n';
---

<a href={getRelativeLocaleUrl(Astro.currentLocale ?? 'en', 'about')}>Über uns</a
>
```


================================================
FILE: docs/src/content/docs/de/guides/overriding-components.mdx
================================================
---
title: Komponenten ersetzen
description: In Starlight kannst du eingebauten Komponenten ersetzen, um eigene Elemente in die Benutzeroberfläche deiner Dokumentationswebsite einzufügen.
---

import { Steps } from '@astrojs/starlight/components';

Starlights Standard-UI und Konfigurations­optionen sind so gestaltet, dass sie flexibel sind und für eine Reihe von Inhalten funktionieren. Ein Großteil des Standardaussehens von Starlight kann mit [CSS](/de/guides/css-and-tailwind/) und [Konfigurations­optionen](/de/guides/customization/) angepasst werden.

Wenn du mehr brauchst als das, was von Haus aus möglich ist, unterstützt Starlight die Erstellung eigener Komponenten, um die Standardkomponenten zu erweitern oder zu ersetzen.

## Wann solltest du ersetzen

Die Standardkomponenten von Starlight zu überschreiben kann nützlich sein, wenn:

- Du das Aussehen eines Teils der Starlight-Benutzeroberfläche auf eine Weise ändern möchest, was mit [eigenem CSS](/de/guides/css-and-tailwind/) nicht möglich ist.
- Du das Verhalten eines Teils der Starlight-Benutzeroberfläche ändern möchtest.
- Du zusätzliche UI neben Starlights bestehender UI hinzufügen willst.

## Wie kann man das ersetzen

<Steps>

1. Wähle die Starlight-Komponente, die du überschreiben möchtest.
   Du kannst eine vollständige Liste der Komponenten in der [Komponenten-Ersetzung Referenz](/de/reference/overrides/) finden.

   :::tip
   Du bist dir nicht sicher, welche Komponente du überschreiben musst? Benutze die [interaktive Starlight Overrides Map](https://starlight-overrides-map.netlify.app/), um die Namen von Starlights UI-Komponenten zu erfahren.
   :::

   In diesem Beispiel wird die Starlight-Komponente [`SocialIcons`](/de/reference/overrides/#socialicons) in der Navigationsleiste der Website außer Kraft gesetzt.

2. Erstelle eine Astro-Komponente, mit der du die Starlight-Komponente ersetzt.
   Dieses Beispiel rendert einen Kontakt-Link.

   ```astro
   ---
   // src/components/EmailLink.astro

   const email = 'houston@example.com';
   ---

   <a href=`mailto:${email}`>Schreib mir</a>
   ```

3. Sage Starlight, dass deine benutzerdefinierte Komponente in der Konfigurations­option [`components`](/de/reference/configuration/#components) in `astro.config.mjs` verwendet werden soll:

   ```js {9-12}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Meine Dokumentation nutzt eigene Komponenten',
   			components: {
   				// Ersetze den Standardkomponent `SocialIcons`
   				SocialIcons: './src/components/EmailLink.astro',
   			},
   		}),
   	],
   });
   ```

</Steps>

## Eine integrierte Komponente wiederverwenden

Du kannst mit den Standard-UI-Komponenten von Starlight genauso arbeiten, wie du es mit deinen eigenen tun würdest: Importieren und Rendern in deinen eigenen benutzerdefinierten Komponenten. Dadurch kannst du die gesamte grundlegende Benutzeroberfläche von Starlight in deinem Design beibehalten und gleichzeitig zusätzliche Benutzeroberflächen hinzufügen.

Das folgende Beispiel zeigt eine benutzerdefinierte Komponente, die einen E-Mail-Link zusammen mit der Standardkomponente `SocialIcons` rendert:

```astro {3,7}
---
// src/components/EmailLink.astro
import Default from '@astrojs/starlight/components/SocialIcons.astro';
---

<a href="mailto:houston@example.com">Schreib mir</a>
<Default><slot /></Default>
```

Wenn du eine eingebaute Komponente innerhalb einer benutzerdefinierten Komponente renderst, füge ein [`<slot />`](https://docs.astro.build/de/basics/astro-components/#slots) innerhalb der Standardkomponente hinzu. Dadurch wird sichergestellt, dass Astro weiß, wo die Komponente gerendert werden soll, wenn sie Kindelemente erhält.

Wenn du die Komponenten [`PageFrame`](/de/reference/overrides/#pageframe) oder [`TwoColumnContent`](/de/reference/overrides/#twocolumncontent) wiederverwendst, die [benannte Slots](https://docs.astro.build/de/basics/astro-components/#benannte-slots) enthalten, musst du auch diese Slots [übertragen](https://docs.astro.build/de/basics/astro-components/#slots-weitergeben).

Das folgende Beispiel zeigt eine benutzerdefinierte Komponente, die die Komponente `TwoColumnContent` wiederverwendet. Diese integrierte Komponente enthält einen zusätzlichen benannten Slot, nämlich `right-sidebar`, welcher übertragen werden muss:

```astro {8}
---
// src/components/CustomContent.astro
import Default from '@astrojs/starlight/components/TwoColumnContent.astro';
---

<Default>
	<slot />
	<slot name="right-sidebar" slot="right-sidebar" />
</Default>
```

## Seitendaten verwenden

Wenn du eine Starlight-Komponente überschreibst, kannst du auf das globale [`starlightRoute`-Objekt](/de/guides/route-data/) zugreifen, das alle Daten für die aktuelle Seite enthält.
Dadurch kannst du diese Werte verwenden, um zu steuern, wie deine Komponentenvorlage gerendert wird.

Im folgenden Beispiel zeigt eine Ersatzkomponente [`PageTitle`](/de/reference/overrides/#pagetitle) den Titel der aktuellen Seite an, wie er im Frontmatter des Inhalts festgelegt wird:

```astro {4} "{title}"
---
// src/components/Title.astro

const { title } = Astro.locals.starlightRoute.entry.data;
---

<h1 id="_top">{title}</h1>

<style>
	h1 {
		font-family: 'Comic Sans';
	}
</style>
```

Weitere Informationen zu allen verfügbaren Eigenschaften findest du in der [Routendaten-Referenz](/de/reference/route-data/).

### Nur auf bestimmten Seiten überschreiben

Komponenten­überschreibungen gelten für alle Seiten. Du kannst jedoch bedingt mit Werten aus `starlightRoute` rendern, um zu bestimmen, wann deine benutzerdefinierte Benutzeroberfläche, wann die Standard­benutzeroberfläche von Starlight oder sogar etwas völlig anderes angezeigt werden soll.

Im folgenden Beispiel zeigt eine Komponente, die Starlights [`Footer`](/de/reference/overrides/#fußzeile) überschreibt, nur auf der Startseite „Verwendet Starlight 🌟“ an und zeigt ansonsten auf allen anderen Seiten die Standardfußzeile an:

```astro
---
// src/components/ConditionalFooter.astro
import Default from '@astrojs/starlight/components/Footer.astro';

const isHomepage = Astro.locals.starlightRoute.id === '';
---

{
	isHomepage ? (
		<footer>Verwendet Starlight 🌟</footer>
	) : (
		<Default>
			<slot />
		</Default>
	)
}
```

Weitere Informationen zum bedingten Rendering findest du im [Astro-Leitfaden zur Vorlagensyntax](https://docs.astro.build/de/basics/astro-syntax/#dynamisches-html).


================================================
FILE: docs/src/content/docs/de/guides/pages.mdx
================================================
---
title: Seiten
description: Lerne, wie du mit Starlight die Seiten deiner Dokumentationswebsite erstellst und verwaltest.
sidebar:
  order: 1
tableOfContents:
  maxHeadingLevel: 4
---

Starlight generiert die HTML-Seiten deiner Website auf der Grundlage deines Inhalts, wobei flexible Optionen über das Markdown-Frontmatter bereitgestellt werden.
Außerdem haben Starlight-Projekte vollen Zugriff auf [Astros leistungsstarke Werkzeuge zur Seitengenerierung](https://docs.astro.build/de/basics/astro-pages/).
Dieser Leitfaden zeigt, wie die Seitenerstellung in Starlight funktioniert.

## Seiten mit Inhalten

### Dateiformate

Starlight unterstützt das Verfassen von Inhalten in Markdown und MDX, ohne dass eine Konfiguration erforderlich ist.
Du kannst die Unterstützung für Markdoc hinzufügen, indem du dem [„Markdoc“ Leitfaden](/de/guides/authoring-content/#markdoc) folgst.

### Seiten hinzufügen

Füge neue Seiten zu deiner Website hinzu, indem du `.md` oder `.mdx` Dateien in `src/content/docs/` erstellst.
Verwende Unterordner, um deine Dateien zu organisieren und um mehrere Pfadsegmente zu erstellen.

Die folgende Dateistruktur erzeugt zum Beispiel Seiten unter `example.com/hello-world` und `example.com/reference/faq`:

import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src/
  - content/
    - docs/
      - hello-world.md
      - reference/
        - faq.md

</FileTree>

### Typsicheres Frontmatter

Alle Starlight-Seiten haben ein anpassbares [gemeinsames Set von Frontmatter-Eigenschaften](/de/reference/frontmatter/), um zu steuern, wie die Seite aussieht:

```md
---
title: Hallo, Welt!
description: Dies ist eine Seite in meiner Starlight-Website
---
```

Wenn du etwas Wichtiges vergisst, wird dich Starlight darauf aufmerksam machen.

## Benutzerdefinierte Seiten

Für fortgeschrittene Anwendungsfälle kannst du benutzerdefinierte Seiten hinzufügen, indem du ein Verzeichnis `src/pages/` erstellst.
Das Verzeichnis `src/pages/` verwendet [Astros dateibasiertes Routing](https://docs.astro.build/de/basics/astro-pages/#dateibasiertes-routing) und unterstützt neben anderen Seitenformaten auch `.astro`-Dateien.
Das ist hilfreich, wenn du Seiten mit einem völlig eigenen Layout erstellen oder eine Seite aus einer anderen Datenquelle generieren willst.

In diesem Projekt werden zum Beispiel Markdown-Inhalte in `src/content/docs/` mit Astro- und HTML-Routen in `src/pages/` gemischt:

<FileTree>

- src/
  - content/
    - docs/
      - hello-world.md
  - pages/
    - custom.astro
    - archived.html

</FileTree>

Mehr dazu findest du in der [„Seiten“-Anleitung in der Astro-Dokumentation](https://docs.astro.build/de/basics/astro-pages/).

### Das Starlight-Design in eigenen Seiten verwenden

Um das Starlight-Layout in benutzerdefinierten Seiten zu verwenden, umhüllst du deinen Seiteninhalt mit der [Komponente `<StarlightPage />`](#starlightpage-komponente).
Das kann hilfreich sein, wenn du Inhalte dynamisch generierst, aber trotzdem das Starlight-Design verwenden willst.

Um Ankerlinks zu Überschriften hinzuzufügen, die den Markdown-Ankerlinkstilen von Starlight entsprechen, kannst du die [`<AnchorHeading>`-Komponente](#anchorheading-komponente) in deinen eigenen Seiten verwenden.

```astro
---
// src/pages/custom-page/example.astro
import StarlightPage from '@astrojs/starlight/components/StarlightPage.astro';
import AnchorHeading from '@astrojs/starlight/components/AnchorHeading.astro';
import CustomComponent from './CustomComponent.astro';
---

<StarlightPage frontmatter={{ title: 'Meine eigene Seite' }}>
	<p>
		Dies ist eine benutzerdefinierte Seite mit einer benutzerdefinierten
		Komponente:
	</p>
	<CustomComponent />

	<AnchorHeading level="2" id="erfahre-menr">Erfahre mehr</AnchorHeading>
	<p>
		<a href="https://starlight.astro.build/">
			Lies mehr in der Starlight-Dokumentation
		</a>
	</p>
</StarlightPage>
```

#### `<StarlightPage>`-Komponente

Die Komponente `<StarlightPage />` rendert eine ganze Seite mit dem Layout und den Stilen von Starlight.

```astro
---
import StarlightPage from '@astrojs/starlight/components/StarlightPage.astro';
---

<StarlightPage frontmatter={{ title: 'Meine eigene Seite' }}>
	<!-- Benutzerdefinierter Seiteninhalt -->
</StarlightPage>
```

Die Komponente `<StarlightPage />` akzeptiert die folgenden Eigenschaften.

##### `frontmatter`

**erforderlich**  
**Typ:** `StarlightPageFrontmatter`

Setzt die [Frontmatter Eigenschaften](/de/reference/frontmatter/) für diese Seite, ähnlich wie Frontmatter in Markdown-Seiten.
Die Eigenschaft [`title`](/de/reference/frontmatter/#title-erforderlich) ist erforderlich und alle anderen Eigenschaften sind optional.

Die folgenden Eigenschaften unterscheiden sich von Markdown frontmatter:

- Die Eigenschaft [`slug`](/de/reference/frontmatter/#slug) wird nicht unterstützt und wird automatisch anhand der URL der benutzerdefinierten Seite gesetzt.
- Die Option [`editUrl`](/de/reference/frontmatter/#editurl) erfordert eine URL, um einen Bearbeitungslink anzuzeigen.
- Die Frontmatter-Eigenschaft [`sidebar`](/de/reference/frontmatter/#sidebar), mit der du festlegen kannst, wie die Seite in [autogenerierten Linkgruppen](/de/reference/configuration/#sidebar) erscheint, ist nicht verfügbar. Seiten, die die Komponente `<StarlightPage />` verwenden, sind nicht Teil einer Sammlung und können nicht zu einer automatisch generierten Seitenleistengruppe hinzugefügt werden.
- Die Option [`draft`](/de/reference/frontmatter/#draft) zeigt nur einen [Hinweis](/de/reference/overrides/#draftcontentnotice) an, dass die Seite ein Entwurf ist, schließt sie aber nicht automatisch von der Produktion aus.

##### `sidebar`

**Typ:** [`SidebarItem[]`](/de/reference/configuration/#sidebaritem)  
**Standard:** die Seitenleiste, die auf der Grundlage der [globalen `Sidebar`-Konfiguration](/de/reference/configuration/#sidebar) erzeugt wird

Legt eine benutzerdefinierte Navigationsleiste für diese Seite fest.
Wenn sie nicht gesetzt wird, verwendet die Seite die globale Standard-Seitenleiste.

Die folgende Seite ersetzt zum Beispiel die Standard-Seitenleiste durch einen Link zur Homepage und eine Gruppe von Links zu verschiedenen anderen benutzerdefinierten Seiten.

```astro {3-13}
<StarlightPage
	frontmatter={{ title: 'Orion' }}
	sidebar={[
		{ label: 'Home', link: '/' },
		{
			label: 'Constellations',
			items: [
				{ label: 'Andromeda', link: '/andromeda/' },
				{ label: 'Orion', link: '/orion/' },
				{ label: 'Ursa Minor', link: '/ursa-minor/', badge: 'Platzhalter' },
			],
		},
	]}
>
	Beispiel-Inhalt.
</StarlightPage>
```

In der Anleitung [„Seitenleisten-Navigation“](/de/guides/sidebar/) erfährst du mehr über die verfügbaren Optionen zum Anpassen der Seitenleiste.

##### `hasSidebar`

**Typ:** `boolean`  
**Standard:** `false` wenn [`frontmatter.template`](/de/reference/frontmatter/#template) `'splash'` ist, sonst `true`

Legt fest, ob die Seitenleiste auf dieser Seite angezeigt werden soll oder nicht.

##### `headings`

**Typ:** `{ depth: number; slug: string; text: string }[]`  
**Standard:** `[]`

Gib ein Array mit allen Überschriften auf dieser Seite an.
Starlight wird das Inhaltsverzeichnis der Seite aus diesen Überschriften generieren, wenn sie angegeben sind.

##### `dir`

**Typ:** `'ltr' | 'rtl'`  
**Standard:** die Schreibrichtung für das aktuelle Gebietsschema

Legt die Schreibrichtung für den Inhalt dieser Seite fest.

##### `lang`

**Typ:** `String`  
**Standard:** die Sprache des aktuellen Gebietsschemas

Setzt das BCP-47 Sprach-Tag für den Inhalt dieser Seite, z. B. `en`, `zh-CN` oder `pt-BR`.

##### `isFallback`

**Typ:** `boolean`  
**Standard:** `false`

Gibt an, ob diese Seite [Fallback-Inhalt](/de/guides/i18n/#fallback-inhalt) verwendet, weil es für die aktuelle Sprache keine Übersetzung gibt.

#### `<AnchorHeading>`-Komponente

Die Komponente `<AnchorHeading />` rendert ein HTML-Überschriftenelement mit einem klickbaren Anker-Link, der den Markdown-Styles von Starlight entspricht.

```astro
---
import AnchorHeading from '@astrojs/starlight/components/AnchorHeading.astro';
---

<AnchorHeading level="2" id="unterüberschrift">Unterüberschrift</AnchorHeading>
```

Sie akzeptiert die folgenden Requisiten sowie alle anderen gültigen [globalen HTML-Attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes).

##### `level`

**erforderlich**  
**Typ:** `1 | 2 | 3 | 4 | 5 | 6`

Die zu rendernde Überschriftsebene.
Zum Beispiel würde `level="1"` ein `<h1>`-Element darstellen.

##### `id`

**erforderlich**  
**Typ:** `string`

Die eindeutige ID für diese Überschrift.
Dieser wird als `id`-Attribut der gerenderten Überschrift verwendet und das Ankersymbol verlinkt darauf.


================================================
FILE: docs/src/content/docs/de/guides/project-structure.mdx
================================================
---
title: Projektstruktur
description: Lerne, wie du Dateien in deinem Starlight-Projekt organisierst.
---

Diese Anleitung zeigt dir, wie ein Starlight-Projekt organisiert ist und was die verschiedenen Dateien in deinem Projekt tun.

Starlight-Projekte folgen im Allgemeinen der gleichen Datei- und Verzeichnisstruktur wie andere Astro-Projekte. Siehe [Astros Dokumentation zur Projektstruktur](https://docs.astro.build/de/basics/project-structure/) für weitere Details.

## Dateien und Verzeichnisse

- `astro.config.mjs` - Die Astro-Konfigurationsdatei; enthält die Starlight-Integration und -Konfiguration.
- `src/content.config.ts` - Konfigurationsdatei für Inhaltssammlungen; fügt Starlights Frontmatter-Schema zu deinem Projekt hinzu.
- `src/content/docs/` - Inhaltsdateien. Starlight verwandelt jede `.md`, `.mdx` oder `.mdoc` Datei in diesem Verzeichnis in eine Seite auf deiner Website.
- `src/content/i18n/` (optional) - Übersetzungsdaten zur Unterstützung der [Internationalisierung](/de/guides/i18n/).
- `src/` - Anderer Quellcode und Dateien (Komponenten, Stile, Bilder, etc.) für dein Projekt.
- `public/` - Statische Assets (Schriftarten, Favicon, PDFs, etc.), die nicht von Astro verarbeitet werden.

## Beispielhafte Projektinhalte

Ein Starlight-Projektverzeichnis könnte wie folgt aussehen:

import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- public/
  - favicon.svg
- src/
  - assets/
    - logo.svg
    - screenshot.jpg
  - components/
    - CustomButton.astro
    - InteractiveWidget.jsx
  - content/
    - docs/
      - guides/
        - 01-getting-started.md
        - 02-advanced.md
      - index.mdx
  - content.config.ts
- astro.config.mjs
- package.json
- tsconfig.json

</FileTree>


================================================
FILE: docs/src/content/docs/de/guides/route-data.mdx
================================================
---
title: Routendaten
description: Erfahre, wie das Seitendatenmodell von Starlight zum Rendern deiner Seiten verwendet wird und wie du es anpassen kannst.
---

import { Steps } from '@astrojs/starlight/components';

Wenn Starlight eine Seite in deiner Dokumentation rendert, erstellt es zunächst ein Routendatenobjekt, das den Inhalt der Seite darstellt.
In diesem Leitfaden wird erklärt, wie Routendaten erzeugt werden, wie du sie verwendest und wie du sie anpassen kannst, um das Standardverhalten von Starlight zu ändern.

Eine vollständige Liste der verfügbaren Eigenschaften findest du in der [„Routendaten-Referenz“](/de/reference/route-data/).

## Was sind Routendaten?

Starlight-Routendaten sind in einem Objekt enthalten, welches alle Informationen enthält, die zum Rendern einer einzelnen Seite benötigt werden.
Es enthält Informationen für die aktuelle Seite sowie Daten, die aus deiner Starlight-Konfiguration generiert werden.

## Routendaten verwenden

Alle Starlight-Komponenten verwenden Routendaten, um zu entscheiden, was für jede Seite gerendert werden soll.
Zum Beispiel wird die Zeichenkette [`siteTitle`](/de/reference/route-data/#sitetitle) verwendet, um den Titel der Seite anzuzeigen, und das Array [`sidebar`](/de/reference/route-data/#sidebar) wird verwendet, um die globale Navigation der Seitenleiste darzustellen.

Du kannst auf diese Daten über das Global `Astro.locals.starlightRoute` in Astro-Komponenten zugreifen:

```astro title="example.astro" {2}
---
const { siteTitle } = Astro.locals.starlightRoute;
---

<p>Der Titel dieser Seite lautet „{siteTitle}“</p>
```

Das kann zum Beispiel nützlich sein, wenn du [Komponenten­überschreibungen](/de/guides/overriding-components/) erstellst, um die Anzeige anzupassen.

## Anpassen der Routendaten

Starlights Routendaten funktionieren sofort und müssen nicht konfiguriert werden.
Für fortgeschrittene Anwendungsfälle möchtest du jedoch vielleicht die Routendaten für einige oder alle Seiten anpassen, um die Darstellung deiner Website zu verändern.

Das ist ein ähnliches Konzept wie die [Komponenten­ersetzung](/de/guides/overriding-components/), aber anstatt zu ändern, wie Starlight deine Daten rendert, änderst du die Daten, die Starlight rendert.

### Wann du die Routendaten anpassen solltest

Das Anpassen von Routendaten kann nützlich sein, wenn du die Art und Weise, wie Starlight deine Daten verarbeitet, auf eine Weise ändern möchtest, die mit den bestehenden Konfigurations­optionen nicht möglich ist.

Du kannst zum Beispiel die Elemente in der Seitenleiste filtern oder die Titel für bestimmte Seiten anpassen.
Bei Änderungen wie dieser müssen die Standardkomponenten von Starlight nicht geändert werden, sondern nur die Daten, die an diese Komponenten übergeben werden.

### Wie du die Routendaten anpasst

Du kannst die Routendaten mithilfe einer speziellen Form von „Middleware“ anpassen.
Dies ist eine Funktion, die jedes Mal aufgerufen wird, wenn Starlight eine Seite rendert, und die Werte im Routendatenobjekt ändern kann.

<Steps>

1. Erstelle eine neue Datei, die eine `onRequest`-Funktion mit Starlights `defineRouteMiddleware()`-Dienstprogramm exportiert:

   ```ts
   // src/routeData.ts
   import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

   export const onRequest = defineRouteMiddleware(() => {});
   ```

2. Teile Starlight in der Datei `astro.config.mjs` mit, wo sich deine Routendaten-Middleware-Datei befindet:

   ```js ins={9}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Meine wunderbare Dokumentationswebsite',
   			routeMiddleware: './src/routeData.ts',
   		}),
   	],
   });
   ```

3. Aktualisiere deine `onRequest`-Funktion, um die Routendaten zu ändern.

   Das erste Argument, das deine Middleware erhält, ist [Astros `context`-Objekt](https://docs.astro.build/de/reference/api-reference/).
   Es enthält alle Informationen über die aktuell gerenderte Seite, einschließlich der aktuellen URL und `locals`.

   In diesem Beispiel werden wir unsere Dokumentation spannender machen, indem wir ein Ausrufezeichen am Ende jedes Seitentitels hinzufügen.

   ```ts
   // src/routeData.ts
   import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

   export const onRequest = defineRouteMiddleware((context) => {
   	// Hol dir den Eintrag der Inhaltssammlung für diese Seite.
   	const { entry } = context.locals.starlightRoute;
   	// Aktualisiere den Titel, um ein Ausrufezeichen hinzuzufügen.
   	entry.data.title = entry.data.title + '!';
   });
   ```

</Steps>

#### Mehrere Routen-Middleware

Starlight unterstützt auch die Bereitstellung mehrerer Middlewares.
Setze `routeMiddleware` auf ein Array von Pfaden, um mehr als einen Middleware-Handler hinzuzufügen:

```js {9}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Meine Website mit mehreren Middlewares',
			routeMiddleware: ['./src/middleware-one.ts', './src/middleware-two.ts'],
		}),
	],
});
```

#### Warten auf spätere Routen-Middleware

Um darauf zu warten, dass die Middleware später im Stapel ausgeführt wird, bevor du deinen Code ausführst, kannst du den `next()` Callback abwarten, der als zweites Argument an deine Middleware-Funktion übergeben wird.
Das kann z. B. nützlich sein, um zu warten, bis die Middleware eines Plugins läuft, bevor du Änderungen vornimmst.

```ts "next" "await next();"
// src/routeData.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

export const onRequest = defineRouteMiddleware(async (context, next) => {
	// Warte darauf, dass die spätere Middleware ausgeführt wird.
	await next();
	// Ändere die Routendaten.
	const { entry } = context.locals.starlightRoute;
	entry.data.title = entry.data.title + '!';
});
```


================================================
FILE: docs/src/content/docs/de/guides/sidebar.mdx
================================================
---
title: Seitenleisten-Navigation
description: Erfahre, wie du die Navigationslinks in der Seitenleiste deiner Starlight-Website einrichten und anpassen kannst.
---

import { FileTree } from '@astrojs/starlight/components';
import SidebarPreview from '~/components/sidebar-preview.astro';

Eine gut organisierte Seitenleiste ist der Schlüssel zu einer guten Dokumentation, da sie eine der Hauptwege ist, auf denen die Benutzer durch deine Website navigieren werden. Starlight bietet eine ganze Reihe von Optionen, um das Layout und den Inhalt der Seitenleiste anzupassen.

## Standard-Seitenleiste

Standardmäßig erzeugt Starlight automatisch eine Seitenleiste, die auf der Dateistruktur deiner Dokumentation basiert und die Eigenschaft `title` jeder Datei als Seitenleisten­eintrag verwendet.

Zum Beispiel wird mit der folgenden Datenstruktur:

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - andromeda.md
        - orion.md
      - stars/
        - betelgeuse.md

</FileTree>

Die folgende Seitenleiste automatisch generiert:

<SidebarPreview
	config={[
		{
			label: 'constellations',
			items: [
				{ label: 'Andromeda', link: '' },
				{ label: 'Orion', link: '' },
			],
		},
		{
			label: 'stars',
			items: [{ label: 'Beteigeuze', link: '' }],
		},
	]}
/>

Erfahre mehr über autogenerierte Seitenleisten im Abschnitt [autogenerierte Gruppen](#automatisch-generierte-gruppen).

## Links und Linkgruppen hinzufügen

Um deiner Seitenleiste Links und Gruppen von Links (innerhalb einer einklappbaren Kopfzeile) zu konfigurieren, verwende die Eigenschaft [`starlight.sidebar`](/de/reference/configuration/#sidebar) in `astro.config.mjs`.

Durch die Kombination von Links und Gruppen kannst du eine Vielzahl von Seitenleisten­layouts erstellen.

### Interne Links

Füge einen Link zu einer Seite in `src/content/docs/` mit Hilfe eines Objekts mit der Eigenschaft `slug` hinzu.
Der Titel der verlinkten Seite wird standardmäßig als Bezeichnung verwendet.

Zum Beispiel wird mit der folgenden Konfiguration:

```js "slug:"
starlight({
	sidebar: [
		{ slug: 'constellations/andromeda' },
		{ slug: 'constellations/orion' },
	],
});
```

Und der folgende Dateistruktur:

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - andromeda.md
        - orion.md

</FileTree>

Die folgende Seitenleiste erstellt:

<SidebarPreview
	config={[
		{ label: 'Andromeda', link: '' },
		{ label: 'Orion', link: '' },
	]}
/>

Um die Werte zu überschreiben, die aus dem Frontmatter einer verlinkten Seite abgeleitet werden, kannst du die Eigenschaften `label`, [`translations`](#internationalisierung) und [`attrs`](#benutzerdefinierte-html-attribute) hinzufügen.

Unter [„Anpassen von automatisch generierten Links“](#autogenerierte-links-im-frontmatter-anpassen) findest du weitere Informationen über die Steuerung des Erscheinungsbildes der Seitenleiste über das Frontmatter der Seite.

#### Kürzel für interne Links

Interne Links können auch angegeben werden, indem nur ein String für den Slug der Seite als Kurzform angegeben wird.

Die folgende Konfiguration entspricht zum Beispiel der obigen Konfiguration, die `slug` verwendet:

```js
starlight({
	sidebar: ['constellations/andromeda', 'constellations/orion'],
});
```

### Andere Links

Füge einen Link zu einer externen oder Nicht-Dokumentations-Seite hinzu, indem du ein Objekt mit den Eigenschaften `label` und `link` verwendest.

```js "label:" "link:"
starlight({
	sidebar: [
		// Ein Link zu einer Nicht-Dokumentations-Seite auf dieser Website.
		{ label: 'Meteor-Laden', link: '/laden/' },
		// Ein externer Link zur NASA-Website.
		{ label: 'NASA', link: 'https://www.nasa.gov/' },
	],
});
```

Die obige Konfiguration erzeugt die folgende Seitenleiste:

<SidebarPreview
	config={[
		{ label: 'Meteor-Laden', link: '' },
		{ label: 'NASA', link: 'https://www.nasa.gov/' },
	]}
/>

### Gruppen

Du kannst deine Seitenleiste strukturieren, indem du zusammengehörige Links unter einer zusammenklappbaren Überschrift gruppierst.
Gruppen können sowohl Links als auch andere Untergruppen enthalten.

Füge eine Gruppe mit einem Objekt mit den Eigenschaften `label` und `items` hinzu.
Das `label` wird als Überschrift für die Gruppe verwendet.
Füge Links oder Untergruppen zu dem `items` Array hinzu.

```js /^\s*(label:|items:)/
starlight({
	sidebar: [
		// Eine Gruppe von Links mit der Bezeichnung 'Konstellationen'.
		{
			label: 'Konstellationen',
			items: [
				'constellations/carina',
				'constellations/centaurus',
				// Eine verschachtelte Gruppe von Links für saisonale Konstellationen.
				{
					label: 'Saisonale',
					items: [
						'constellations/andromeda',
						'constellations/orion',
						'constellations/ursa-minor',
					],
				},
			],
		},
	],
});
```

Die obige Konfiguration erzeugt die folgende Seitenleiste:

<SidebarPreview
	config={[
		{
			label: 'Konstellationen',
			items: [
				{ label: 'Kiel des Schiffes', link: '' },
				{ label: 'Zentaur', link: '' },
				{
					label: 'Saisonale',
					items: [
						{ label: 'Andromeda', link: '' },
						{ label: 'Orion', link: '' },
						{ label: 'Kleiner Bär', link: '' },
					],
				},
			],
		},
	]}
/>

### Automatisch generierte Gruppen

Starlight kann automatisch eine Gruppe in deiner Seitenleiste erzeugen, die auf einem Verzeichnis deiner Dokumente basiert.
Dies ist hilfreich, wenn du nicht jedes Element der Seitenleiste manuell in eine Gruppe eintragen willst.

Standardmäßig werden die Seiten in alphabetischer Reihenfolge nach der Datei [`slug`](/de/reference/route-data/#slug) sortiert.

Füge eine automatisch generierte Gruppe hinzu, indem du ein Objekt mit den Eigenschaften `label` und `autogenerate` verwendest. In der Konfiguration von `autogenerate` muss das `directory` angegeben werden, das für die Einträge in der Seitenleiste verwendet werden soll.

Zum Beispiel wird mit der folgenden Konfiguration:

```js "label:" "autogenerate:"
starlight({
	sidebar: [
		{
			label: 'Konstellationen',
			// Automatisches Erzeugen einer Gruppe von Links für das Verzeichnis 'constellations'.
			autogenerate: { directory: 'constellations' },
		},
	],
});
```

Und der folgende Dateistruktur:

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - carina.md
        - centaurus.md
        - seasonal/
          - andromeda.md

</FileTree>

Die folgende Seitenleiste erzeugt:

<SidebarPreview
	config={[
		{
			label: 'Konstellationen',
			items: [
				{ label: 'Kiel des Schiffes', link: '' },
				{ label: 'Zentaur', link: '' },
				{
					label: 'seasonal',
					items: [{ label: 'Andromeda', link: '' }],
				},
			],
		},
	]}
/>

## Autogenerierte Links im Frontmatter anpassen

Verwende das [`sidebar`-Frontmatter-Feld](/de/reference/frontmatter/#sidebar) in einzelnen Seiten, um automatisch generierte Links anzupassen.

Mit den Frontmatter-Optionen in der Seitenleiste kannst du eine [benutzerdefinierte Bezeichnung](/de/reference/frontmatter/#label) festlegen, [benutzerdefinierte Attribute](/de/reference/frontmatter/#attrs) verwenden, ein [Abzeichen](/de/reference/frontmatter/#badge) zu einem Link hinzufügen, einen Link aus der Seitenleiste [verstecken](/de/reference/frontmatter/#hidden) oder eine [eigene Reihenfolge](/de/reference/frontmatter/#order) definieren.

```md "sidebar:"
---
# src/content/docs/example.md
title: Meine Seite
sidebar:
  # Setzt eine eigene Beschriftung für den Link
  label: Benutzerdefinierte Seitenleistenbeschriftung
  # Legen du eine benutzerdefinierte Reihenfolge für den Link fest (niedrigere Zahlen werden weiter oben angezeigt)
  order: 2
  # Fügen du dem Link ein Abzeichen hinzu
  badge:
    text: Neu
    variant: tip
---
```

Eine autogenerierte Gruppe, die eine Seite mit dem obigen Frontmatter enthält, erzeugt die folgende Seitenleiste:

<SidebarPreview
	config={[
		{
			label: 'Anleitungen',
			items: [
				{ label: 'Eine Seite', link: '' },
				{
					label: 'Benutzerdefinierte Seitenleistenbeschriftung',
					link: '',
					badge: { text: 'Neu', variant: 'tip' },
				},
				{ label: 'Andere Seite', link: '' },
			],
		},
	]}
/>

:::note[Anmerkung]
Die `sidebar` Frontmatter-Konfiguration wird nur für Links in automatisch generierten Gruppen und für Dokumentations-Links verwendet, die mit der Eigenschaft `slug` definiert wurden. Sie gilt nicht für Links, die mit der Eigenschaft `link` definiert wurden.
:::

## Abzeichen

Links, Gruppen und automatisch generierte Gruppen können auch eine `badge`-Eigenschaft enthalten, um ein Abzeichen neben dem jeweiligen Text anzuzeigen.

```js {9,16}
starlight({
	sidebar: [
		{
			label: 'Sterne',
			items: [
				//Ein Link mit einem "Überriese"-Abzeichen.
				{
					slug: 'stars/persei',
					badge: 'Überriese',
				},
			],
		},
		// Eine automatisch generierte Gruppe mit dem "Veraltet"-Abzeichen.
		{
			label: 'Monde',
			badge: 'Veraltet',
			autogenerate: { directory: 'moons' },
		},
	],
});
```

Die obige Konfiguration erzeugt die folgende Seitenleiste:

<SidebarPreview
	config={[
		{
			label: 'Sterne',
			items: [
				{
					label: 'Persei',
					link: '',
					badge: { text: 'Überriese', variant: 'default' },
				},
			],
		},
		{
			label: 'Monde',
			badge: { text: 'Veraltet', variant: 'default' },
			items: [
				{
					label: 'Io',
					link: '',
				},
				{
					label: 'Europa',
					link: '',
				},
				{
					label: 'Ganymed',
					link: '',
				},
			],
		},
	]}
/>

### Abzeichenvarianten

Passe das Design des Abzeichens mit einem Objekt mit den Eigenschaften `text`, `variant` und `class` an.

Der `text` steht für den anzuzeigenden Inhalt (z. B. "Neu").
Überschreibe das `default`-Styling, das die Akzentfarbe deiner Website verwendet, indem du die Eigenschaft `variant` auf einen der folgenden Werte setzt: `note`, `tip`, `danger`, `caution` oder `success`.

Optional kannst du einen benutzerdefinierten Abzeichenstil erstellen, indem du die Eigenschaft `class` auf einen CSS-Klassennamen setzt.

```js {9}
starlight({
	sidebar: [
		{
			label: 'Sterne',
			items: [
				// Ein Link mit einem gelben „Platzhalter“-Abzeichen.
				{
					slug: 'stars/sirius',
					badge: { text: 'Platzhalter', variant: 'caution' },
				},
			],
		},
	],
});
```

Die obige Konfiguration erzeugt die folgende Seitenleiste:

<SidebarPreview
	config={[
		{
			label: 'Sterne',
			items: [
				{
					label: 'Sirius',
					link: '',
					badge: { text: 'Platzhalter', variant: 'caution' },
				},
			],
		},
	]}
/>

Erfahre mehr über [Verwendung und Anpassung von Badges](/de/components/badges/#verwendung).

## Benutzerdefinierte HTML-Attribute

Links können auch eine Eigenschaft `attrs` enthalten, um dem Link-Element benutzerdefinierte HTML-Attribute hinzuzufügen.

Im folgenden Beispiel wird `attrs` verwendet, um ein `target="_blank"`-Attribut hinzuzufügen, so dass der Link in einem neuen Tab geöffnet wird, und um ein benutzerdefiniertes `style`-Attribut anzuwenden, um die Linkbeschriftung kursiv zu machen:

```js {10}
starlight({
	sidebar: [
		{
			label: 'Ressourcen',
			items: [
				// Ein externer Link zur NASA-Website, der in einem neuen Tab geöffnet wird.
				{
					label: 'NASA',
					link: 'https://www.nasa.gov/',
					attrs: { target: '_blank', style: 'font-style: italic' },
				},
			],
		},
	],
});
```

Die obige Konfiguration erzeugt die folgende Seitenleiste:

<SidebarPreview
	config={[
		{
			label: 'Ressourcen',
			items: [
				{
					label: 'NASA',
					link: 'https://www.nasa.gov/',
					attrs: {
						target: '_blank',
						style: 'font-style: italic',
					},
				},
			],
		},
	]}
/>

### Benutzerdefinierte HTML-Attribute für automatisch generierte Links

Du kannst die HTML-Attribute aller Links in [automatisch generierten Gruppen](#automatisch-generierte-gruppen) anpassen, indem du die Eigenschaft `attrs` in der Konfiguration `autogenerate` festlegst.
Einzelne Seiten können eigene Attribute über das [`sidebar.attrs`-Frontmatter-Feld](/de/reference/frontmatter/#attrs) festlegen, welches mit der `autogenerate.attrs`-Konfiguration zusammengeführt wird.

Zum Beispiel wird mit der folgenden Konfiguration:

```js {10}
starlight({
	sidebar: [
		{
			label: 'Konstellationen',
			autogenerate: {
				// Erstelle automatisch eine Gruppe von Links
				// für das Verzeichnis 'constellations'.
				directory: 'constellations',
				// Alle Link-Bezeichnungen in dieser Gruppe kursiv darstellen.
				attrs: { style: 'font-style: italic' },
			},
		},
	],
});
```

Und der folgenden Dateistruktur:

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - carina.md
        - centaurus.md
        - seasonal/
          - andromeda.md

</FileTree>

Die folgende Seitenleiste mit allen automatisch generierten Links in Kursivschrift erstellt:

<SidebarPreview
	config={[
		{
			label: 'Konstellationen',
			items: [
				{
					label: 'Kiel des Schiffes',
					link: '',
					attrs: { style: 'font-style: italic' },
				},
				{
					label: 'Zentaur',
					link: '',
					attrs: { style: 'font-style: italic' },
				},
				{
					label: 'seasonal',
					items: [
						{
							label: 'Andromeda',
							link: '',
							attrs: { style: 'font-style: italic' },
						},
					],
				},
			],
		},
	]}
/>

## Internationalisierung

Verwende die Eigenschaft `translations` für Link- und Gruppeneinträge, um die Link- oder Gruppenbeschriftung für jede unterstützte Sprache zu übersetzen, indem du ein [BCP-47](https://www.w3.org/International/questions/qa-choosing-language-tags) Sprach-Tag, z. B. `"en"`, `"ar"`, oder `"zh-CN"`, als Schlüssel und die übersetzte Beschriftung als Wert angibst.
Die Eigenschaft `label` wird für das Standard­gebietsschema und für Sprachen ohne Übersetzung verwendet.

```js {5-7,11-13,18-20}
starlight({
	sidebar: [
		{
			label: 'Konstellationen',
			translations: {
				'pt-BR': 'Constelações',
			},
			items: [
				{
					label: 'Andromeda',
					translations: {
						'pt-BR': 'Andrômeda',
					},
					slug: 'constellations/andromeda',
				},
				{
					label: 'Skorpion',
					translations: {
						'pt-BR': 'Escorpião',
					},
					slug: 'constellations/scorpius',
				},
			],
		},
	],
});
```

Wenn du die Dokumentation in brasilianischem Portugiesisch durchsuchst, wird die folgende Seitenleiste angezeigt:

<SidebarPreview
	config={[
		{
			label: 'Constelação',
			items: [
				{ label: 'Andrômeda', link: '' },
				{ label: 'Escorpião', link: '' },
			],
		},
	]}
/>

### Internationalisierung mit internen Links

[Interne Links](#interne-links) verwenden standardmäßig automatisch übersetzte Seitentitel aus dem Frontmatter des Inhalts:

```js {9-10}
starlight({
	sidebar: [
		{
			label: 'Konstellationen',
			translations: {
				'pt-BR': 'Constelações',
			},
			items: [
				{ slug: 'constellations/andromeda' },
				{ slug: 'constellations/scorpius' },
			],
		},
	],
});
```

Wenn du die Dokumentation auf brasilianisches Portugiesisch durchsuchst, wird die folgende Seitenleiste angezeigt:

<SidebarPreview
	config={[
		{
			label: 'Constelações',
			items: [
				{ label: 'Andrômeda', link: '' },
				{ label: 'Escorpião', link: '' },
			],
		},
	]}
/>

Bei mehrsprachigen Websites enthält der Wert von `slug` nicht den sprachlichen Teil der URL.
Wenn du zum Beispiel Seiten unter `en/intro` und `pt-br/intro` hast, ist der Slug `intro`, wenn du die Seitenleiste konfigurierst.

### Internationalisierung mit Badges

Für [Abzeichen](#abzeichen) kann die Eigenschaft `text` ein String sein oder für mehrsprachige Seiten ein Objekt mit Werten für jedes unterschiedliche Gebietsschema.
Wenn du die Objektform verwendest, müssen die Schlüssel [BCP-47](https://www.w3.org/International/questions/qa-choosing-language-tags) Tags sein (z. B. `en`, `ar` oder `zh-CN`):

```js {11-16}
starlight({
	sidebar: [
		{
			label: 'Konstellationen',
			translations: {
				'pt-BR': 'Constelações',
			},
			items: [
				{
					slug: 'constellations/andromeda',
					badge: {
						text: {
							de: 'Neu',
							'pt-BR': 'Novo',
						},
					},
				},
			],
		},
	],
});
```

Wenn du die Dokumentation auf brasilianisches Portugiesisch durchsuchst, wird die folgende Seitenleiste angezeigt:

<SidebarPreview
	config={[
		{
			label: 'Constelações',
			items: [
				{
					label: 'Andrômeda',
					link: '',
					badge: { text: 'Novo', variant: 'default' },
				},
			],
		},
	]}
/>

## Zusammenklappen von Gruppen

Gruppen von Links können standardmäßig eingeklappt werden, indem man die Eigenschaft `collapsed` auf `true` setzt.

```js {5-6}
starlight({
	sidebar: [
		{
			label: 'Konstellationen',
			// Schließe die Gruppe standardmäßig.
			collapsed: true,
			items: ['constellations/andromeda', 'constellations/orion'],
		},
	],
});
```

Die obige Konfiguration erzeugt die folgende Seitenleiste:

<SidebarPreview
	config={[
		{
			label: 'Konstellationen',
			collapsed: true,
			items: [
				{ label: 'Andromeda', link: '' },
				{ label: 'Orion', link: '' },
			],
		},
	]}
/>

[Autogenerierte Gruppen](#automatisch-generierte-gruppen) respektieren den `collapsed` Wert ihrer Elterngruppe:

```js {5-7}
starlight({
	sidebar: [
		{
			label: 'Konstellationen',
			// Die Gruppe und ihre automatisch generierte
			// Untergruppen standardmäßig einklappen.
			collapsed: true,
			autogenerate: { directory: 'constellations' },
		},
	],
});
```

Die obige Konfiguration erzeugt die folgende Seitenleiste:

<SidebarPreview
	config={[
		{
			label: 'Konstellationen',
			collapsed: true,
			items: [
				{ label: 'Kiel des Schiffes', link: '' },
				{ label: 'Zentaur', link: '' },
				{
					label: 'seasonal',
					collapsed: true,
					items: [{ label: 'Andromeda', link: '' }],
				},
			],
		},
	]}
/>

Dieses Verhalten kann durch die Definition der Eigenschaft `autogenerate.collapsed` außer Kraft gesetzt werden.

```js {5-7} "collapsed: true"
starlight({
	sidebar: [
		{
			label: 'Konstellationen',
			// Die Gruppe "Konstellationen" nicht einklappen, aber ihre
			// automatisch generierten Untergruppen.
			collapsed: false,
			autogenerate: { directory: 'constellations', collapsed: true },
		},
	],
});
```

Die obige Konfiguration erzeugt die folgende Seitenleiste:

<SidebarPreview
	config={[
		{
			label: 'Konstellationen',
			items: [
				{ label: 'Kiel des Schiffes', link: '' },
				{ label: 'Zentaur', link: '' },
				{
					label: 'seasonal',
					collapsed: true,
					items: [{ label: 'Andromeda', link: '' }],
				},
			],
		},
	]}
/>


================================================
FILE: docs/src/content/docs/de/guides/site-search.mdx
================================================
---
title: Suche
description: Finde heraus, welche Suchfunktionen in Starlight integriert sind und wie du sie anpassen kannst.
tableOfContents:
  maxHeadingLevel: 4
---

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

Standardmäßig enthalten Websites, die Starlight verwenden, eine Volltextsuche mit [Pagefind](https://pagefind.app/), einem schnellen, bandbreitenarmen Suchwerkzeug für statische Websites.

Es ist keine Konfiguration erforderlich, um die Suche zu aktivieren. Erstelle und implementiere deine Website und benutze dann die Suchleiste im Kopfbereich der Website, um nach Inhalten zu suchen.

## Inhalte in den Suchergebnissen ausblenden

### Eine Seite ausschließen

Um eine Seite aus deinem Suchindex auszuschließen, füge [`pagefind: false`](/de/reference/frontmatter/#pagefind) zum Frontmatter der Seite hinzu:

```md title="src/content/docs/not-indexed.md" ins={3}
---
title: Inhalt, der vor der Suche verborgen werden soll.
pagefind: false
---
```

### Einen Teil einer Seite ausschließen

Pagefind ignoriert den Inhalt innerhalb eines Elements mit dem Attribut [`data-pagefind-ignore`](https://pagefind.app/docs/indexing/#removing-individual-elements-from-the-index).

Im folgenden Beispiel wird der erste Absatz in den Suchergebnissen angezeigt, aber der Inhalt von `<div>` wird nicht angezeigt:

```md title="src/content/docs/partially-indexed.md" ins="data-pagefind-ignore"
---
title: Seite teilweise indiziert
---

Dieser Text kann über die Suche gefunden werden.

<div data-pagefind-ignore>

Dieser Text wird von der Suche ausgeblendet.

</div>
```

## Alternative Suchanbieter

### Algolia DocSearch

Wenn du Zugang zum [Algolia DocSearch-Programm](https://docsearch.algolia.com/) hast und es anstelle von Pagefind verwenden möchtest, kannst du das offizielle DocSearch-Plugin von Starlight verwenden.

<Steps>

1. Installiere `@astrojs/starlight-docsearch`:

   <Tabs syncKey="pkg">

   <TabItem label="npm">

   ```sh
   npm install @astrojs/starlight-docsearch
   ```

   </TabItem>

   <TabItem label="pnpm">

   ```sh
   pnpm add @astrojs/starlight-docsearch
   ```

   </TabItem>

   <TabItem label="Yarn">

   ```sh
   yarn add @astrojs/starlight-docsearch
   ```

   </TabItem>

   </Tabs>

2. Füge DocSearch zu deiner Starlight-Konfiguration [`plugins`](/de/reference/configuration/#plugins) in der Datei `astro.config.mjs` hinzu und gib deine `appId`, `apiKey` und `indexName` von Algolia an:

   ```js ins={4,10-16}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';
   import starlightDocSearch from '@astrojs/starlight-docsearch';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Website mit DocSearch',
   			plugins: [
   				starlightDocSearch({
   					appId: 'DEINE_APP_ID',
   					apiKey: 'DEIN_SUCH_API_SCHLÜSSEL',
   					indexName: 'DEIN_INDEX_NAME',
   				}),
   			],
   		}),
   	],
   });
   ```

</Steps>

Mit dieser aktualisierten Konfiguration öffnet die Suchleiste deiner Website nun ein Algolia-Modal anstelle des Standardmodals.

#### DocSearch Konfiguration

Das Starlight DocSearch Plugin unterstützt die Anpassung der DocSearch Komponente mit den folgenden Optionen, die in der Konfiguration des Erweiterungsmoduls angegeben werden:

- `maxResultsPerGroup`: Begrenzt die Anzahl der Ergebnisse, die für jede Suchgruppe angezeigt werden. Der Standardwert ist `5`.
- `disableUserPersonalization`: Verhindere, dass DocSearch die letzten Suchen und Favoriten eines Nutzers im lokalen Speicher speichert. Der Standardwert ist `false`.
- `insights`: Aktiviere das Algolia Insights Plugin und sende Suchereignisse an deinen DocSearch-Index. Der Standardwert ist `false`.
- `searchParameters`: Ein Objekt, das die [Algolia Search Parameters](https://www.algolia.com/doc/api-reference/search-api-parameters/) anpasst.

##### Zusätzliche DocSearch-Optionen

Eine separate Konfigurationsdatei ist erforderlich, um Funktionsoptionen wie `transformItems()` oder `resultsFooterComponent()` an die DocSearch-Komponente zu übergeben.

<Steps>

1. Erstelle eine TypeScript-Datei, die deine DocSearch-Konfiguration exportiert.

   ```ts
   // src/config/docsearch.ts
   import type { DocSearchClientOptions } from '@astrojs/starlight-docsearch';
   export default {
   	appId: 'DEINE_APP_ID',
   	apiKey: 'DEIN_SUCH_API_SCHLÜSSEL',
   	indexName: 'DEIN_INDEX_NAME',
   	getMissingResultsUrl({ query }) {
   		return `https://github.com/algolia/docsearch/issues/new?title=${query}`;
   	},
   	// ...
   } satisfies DocSearchClientOptions;
   ```

2. Übergib den Pfad zu deiner Konfigurationsdatei an das Starlight DocSearch Plugin in der Datei `astro.config.mjs`.

   ```js {11-13}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';
   import starlightDocSearch from '@astrojs/starlight-docsearch';
   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Website mit DocSearch',
   			plugins: [
   				starlightDocSearch({
   					clientOptionsModule: './src/config/docsearch.ts',
   				}),
   			],
   		}),
   	],
   });
   ```

</Steps>

Alle unterstützten Optionen findest du in der [DocSearch JavaScript Client API Referenz](https://docsearch.algolia.com/docs/api/).

#### Die Benutzeroberfläche von DocSearch übersetzen

DocSearch stellt standardmäßig nur englische Benutzeroberflächen-Strings zur Verfügung.
Füge mithilfe des in Starlight integrierten [Internationalisierungs­systems](/de/guides/i18n/#starlights-ui-übersetzen) Übersetzungen der Benutzeroberfläche der Modale für deine Sprache hinzu.

<Steps>

1. Erweitere die Definition der Starlight-Inhaltssammlung `i18n` um das DocSearch-Schema in `src/content.config.ts`:

   ```js ins={5} ins=/{ extend: .+ }/
   // src/content.config.ts
   import { defineCollection } from 'astro:content';
   import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
   import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';
   import { docSearchI18nSchema } from '@astrojs/starlight-docsearch/schema';

   export const collections = {
   	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
   	i18n: defineCollection({
   		loader: i18nLoader(),
   		schema: i18nSchema({ extend: docSearchI18nSchema() }),
   	}),
   };
   ```

2. Füge Übersetzungen zu deinen JSON-Dateien in `src/content/i18n/` hinzu.

   Hier sind die englischen Standardwerte, die von DocSearch verwendet werden:

   ```json title="src/content/i18n/en.json"
   {
   	"docsearch.searchBox.resetButtonTitle": "Clear the query",
   	"docsearch.searchBox.resetButtonAriaLabel": "Clear the query",
   	"docsearch.searchBox.cancelButtonText": "Cancel",
   	"docsearch.searchBox.cancelButtonAriaLabel": "Cancel",
   	"docsearch.searchBox.searchInputLabel": "Search",

   	"docsearch.startScreen.recentSearchesTitle": "Recent",
   	"docsearch.startScreen.noRecentSearchesText": "No recent searches",
   	"docsearch.startScreen.saveRecentSearchButtonTitle": "Save this search",
   	"docsearch.startScreen.removeRecentSearchButtonTitle": "Remove this search from history",
   	"docsearch.startScreen.favoriteSearchesTitle": "Favorite",
   	"docsearch.startScreen.removeFavoriteSearchButtonTitle": "Remove this search from favorites",

   	"docsearch.errorScreen.titleText": "Unable to fetch results",
   	"docsearch.errorScreen.helpText": "You might want to check your network connection.",

   	"docsearch.footer.selectText": "to select",
   	"docsearch.footer.selectKeyAriaLabel": "Enter key",
   	"docsearch.footer.navigateText": "to navigate",
   	"docsearch.footer.navigateUpKeyAriaLabel": "Arrow up",
   	"docsearch.footer.navigateDownKeyAriaLabel": "Arrow down",
   	"docsearch.footer.closeText": "to close",
   	"docsearch.footer.closeKeyAriaLabel": "Escape key",
   	"docsearch.footer.searchByText": "Search by",

   	"docsearch.noResultsScreen.noResultsText": "No results for",
   	"docsearch.noResultsScreen.suggestedQueryText": "Try searching for",
   	"docsearch.noResultsScreen.reportMissingResultsText": "Believe this query should return results?",
   	"docsearch.noResultsScreen.reportMissingResultsLinkText": "Let us know."
   }
   ```

</Steps>

### Community-Suchanbieter

[Community-Plugins](/de/resources/plugins/#community-plugins) können auch Alternativen zum integrierten Suchanbieter Pagefind von Starlight bieten.

#### Typesense DocSearch

Das Community-Plugin [Starlight DocSearch Typesense](https://starlight-docsearch.typesense.org/) bietet eine Open-Source- und selbst hostbare Alternative, die die [DocSearch](https://github.com/typesense/typesense-docsearch.js)-Schnittstelle mit einem [Typesense](https://typesense.org/)-Backend integriert.

Lies die Anleitung [„Erste Schritte“](https://starlight-docsearch.typesense.org/getting-started/) in der Starlight DocSearch Typesense-Dokumentation, um zu erfahren, wie du es in deinem Projekt verwenden kannst.


================================================
FILE: docs/src/content/docs/de/index.mdx
================================================
---
title: Starlight 🌟 Einfache Dokumentations-Websites mit Astro
head:
  - tag: title
    content: Starlight 🌟 Einfache Dokumentations-Websites mit Astro
description: Erstelle schöne, leistungsstarke Dokumentations-Websites mit Starlight und Astro.
template: splash
editUrl: false
lastUpdated: false
hero:
  title: Bringe deine Dokumentation mit Starlight zum Leuchten
  tagline: Alles, was du brauchst, um eine erstklassige Dokumentations-Website zu erstellen. Schnell, barrierefrei und einfach zu bedienen.
  image:
    file: ~/assets/hero-star.webp
  actions:
    - text: Los geht’s
      icon: right-arrow
      link: /de/getting-started/
    - text: Auf GitHub
      icon: external
      variant: minimal
      link: https://github.com/withastro/starlight
---

import { CardGrid, Card } from '@astrojs/starlight/components';
import AboutAstro from '~/components/about-astro.astro';
import TestimonialGrid from '~/components/testimonial-grid.astro';
import Testimonial from '~/components/testimonial.astro';

<CardGrid stagger>
	<Card title="Dokumentation, die begeistert" icon="open-book">
		Website-Navigation, Suche, Internationalisierung, SEO, leicht lesbare
		Typografie, Code-Hervorhebung, Dark-Mode und mehr.
	</Card>
	<Card title="Angetrieben durch Astro" icon="rocket">
		Nutze die volle Kraft und Leistung von Astro. Erweitere Starlight mit deinen
		bevorzugten Astro-Integrationen.
	</Card>
	<Card title="Markdown, Markdoc und MDX" icon="document">
		Bringe dein bevorzugtes Dokumentformat mit. Starlight behält alles im Auge
		mit integrierte Frontmatter-Validierung.
	</Card>
	<Card title="Bringe deine eigenen Komponenten mit" icon="puzzle">
		Starlight wird als frameworkunabhängige, vollständige
		Dokumentations­lösung geliefert. Erweitere mit React, Vue, Svelte, Solid
		und mehr.
	</Card>
</CardGrid>

<TestimonialGrid title="Was die Leute sagen">
  <Testimonial
    name="Rachel"
    handle="rachelnabors"
    cite="https://twitter.com/astrodotbuild/status/1724934718745915558"
  >
    Das Astro-Team hat die Art und Weise, wie Dokumentationen erstellt werden können, ENTWICKELT, und mit ihrem Starlight-Projekt kannst du sie sofort nutzen.
  </Testimonial>
  <Testimonial
    name="Flavio"
    handle="flaviocopes"
    cite="https://twitter.com/flaviocopes/status/1738237658717905108"
  >
    Astros offizielles Starterkit Starlight ist ein unglaubliches Werkzeug für die Erstellung einer Dokumentations-Website
  </Testimonial>
  <Testimonial
    name="Tomek"
    handle="sulco"
    cite="https://twitter.com/sulco/status/1735610348730802342"
  >
    Starlight ist unser Paradebeispiel für einen großartigen DX: Die Geschwindigkeit, der Komfort
    und die Liebe zum Detail sind inspirierend. Es kümmert sich um die Technik und das Aussehen,
    damit du dich auf deine Inhalte konzentrieren kannst 👏.

    Das StackBlitz-Team liebt es!

  </Testimonial>
  <Testimonial
    name="Roberto"
    handle="RmeetsH"
    cite="https://twitter.com/RmeetsH/status/1735783992018760090"
  >
    Starlight hat meine Arbeit grundlegend verändert und mir die Möglichkeit gegeben, mich auf die Erstellung von Inhalten zu konzentrieren.

    Sein intuitives Design vereinfacht nicht nur meinen Arbeitsablauf, sondern verkürzt auch die Einarbeitungszeit für Open-Source-Entwickler.

  </Testimonial>
  <Testimonial
    name="Joel"
    handle="jhooks"
    cite="https://twitter.com/jhooks/status/1727405160547418405"
  >
    Ich habe etwas mehr Zeit mit Starlight für die Kurs-Bauer-Dokumentation verbracht und es ist bisher großartig. Ich kann mich auf das Schreiben in Markdown konzentrieren und muss nicht mehr an der Website herumfummeln.
  </Testimonial>
  <Testimonial
    name="Rick"
    handle="rick_viscomi"
    cite="https://twitter.com/rick_viscomi/status/1665867447910510593"
  >
    Ich habe angefangen, mit Starlight zu spielen. Ich muss sagen, ich bin sehr beeindruckt von der Leistung, die es bietet.

    💯💯💯💯

  </Testimonial>
  <Testimonial
    name="Nicolas"
    handle="beaussan"
    cite="https://twitter.com/beaussan/status/1735625189583466893"
  >
  	Starlight ist der beste Weg, um mit der Dokumentation zu beginnen.
    Leistung und Geschwindigkeit von Astro und den Werkzeugen von Starlight, es ist wie im siebten Himmel.
    Ich benutze es schon seit einer Weile und bin immer noch begeistert!
  </Testimonial>
  <Testimonial
    name="Sylwia"
    handle="SylwiaVargas"
    cite="https://x.com/SylwiaVargas/status/1726556825741578286"
  >
    Ich habe Starlight in meinem letzten Job benutzt und war begeistert. Tolle Komponenten, intuitives Design
    und eine sehr reaktionsfreudige Community (wann immer jemand etwas brauchte,
    haben sie es schnell integriert oder dir eine temporäre Lösung gezeigt). Eine sehr angenehme Erfahrung.
  </Testimonial>
  <Testimonial
    name="Lou Cyx"
    handle="loucyx"
    cite="https://elk.zone/m.webtoo.ls/@loucyx@mastodon.social/111587380021362284"
  >
    Die Dokumentation auf meiner Monorepo-Website sehen dank Starlight besser aus als je zuvor. Es ist extrem einfach zu bedienen, ohne dabei die ganze Leistung von Astro zu verlieren. Danke, dass ihr daran arbeitet!
  </Testimonial>
  <Testimonial
    name="BowTiedWebReaper"
    handle="BowTiedWebReapr"
    cite="https://twitter.com/BowTiedWebReapr/status/1735633399501697517"
  >
    Starlight ist mein bevorzugtes Tool für Dokumentationen. Mit Starlight war es super einfach, meiner bestehenden Astro-Produktwebsite Dokumentation hinzuzufügen, anstatt eine Subdomain für ein anderes Tool zu benötigen.
  </Testimonial>
  <Testimonial
    name="Jeff"
    handle="J_Everhart383"
    cite="https://twitter.com/J_Everhart383/status/1691900590048292908"
  >
    Ich habe die WPEngine Atlas Platform Dokumentation neu aufgebaut. Vertrau mir, wenn ich sage, dass Starlight alles hat, was du brauchst, um eine hervorragende Doku-Plattform zu machen 🙌
  </Testimonial>
  <Testimonial
    name="Chloe"
    handle="solelychloe"
    cite="https://twitter.com/solelychloe/status/1695115277602628082"
  >
    Probiere Starlight aus!

    Ich benutze es für ein paar meiner Websites und es ist großartig.

  </Testimonial>
</TestimonialGrid>

<AboutAstro title="Präsentiert von">
Astro ist ein Web-Framework, das eine Komplettlösung zur Erstellung schneller Websites darstellt. Rufe deine Inhalte von überall ab und stelle sie überall bereit, alles unterstützt durch deine bevorzugten UI-Komponenten und Bibliotheken.

[Erfahre mehr über Astro](https://astro.build/)

</AboutAstro>


================================================
FILE: docs/src/content/docs/de/manual-setup.mdx
================================================
---
title: Manuelle Einrichtung
description: Lerne wie du Starlight manuell konfigurierst, um es zu einem bestehenden Astro-Projekt hinzuzufügen.
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

Der schnellste Weg, eine neue Starlight-Website zu erstellen, ist die Verwendung von `create astro`, wie auf der Seite [Erste Schritte](/de/getting-started/#erstelle-ein-neues-projekt) beschrieben.
Wie du Starlight zu einem bestehenden Astro-Projekt hinzufügst, wird in dieser Anleitung erklärt.

## Starlight einrichten

Um dieser Anleitung folgen zu können, benötigst du ein bestehendes Astro-Projekt.

### Hinzufügen der Starlight-Integration

Starlight ist eine [Astro-Integration](https://docs.astro.build/de/guides/integrations-guide/). Füge sie zu deiner Website hinzu, indem du den Befehl `astro add` im Projektstamm­verzeichnis deines Projekts ausführst:

<Tabs syncKey="pkg">
    <TabItem label="npm">
        ```sh
        npx astro add starlight
        ```

    </TabItem>
    <TabItem label="pnpm">
        ```sh
        pnpm astro add starlight
        ```
    </TabItem>
    <TabItem label="Yarn">
        ```sh
        yarn astro add starlight
        ```
    </TabItem>

</Tabs>

Dies installiert die erforderlichen Abhängigkeiten und fügt Starlight zum Array `integrations` in deiner Astro-Konfigurationsdatei hinzu.

### Konfiguriere die Integration

Die Starlight-Integration wird in der Datei `astro.config.mjs` konfiguriert.

Füge zunächst einen Titel mit der Eigenschaft `title` hinzu:

```js ins={8}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Meine Dokumentation',
		}),
	],
});
```

Alle verfügbaren Optionen findest du in der [Starlight-Konfigurations­referenz](/de/reference/configuration/).

### Konfigurieren von Inhaltssammlungen

Starlight baut auf Astros [Inhaltssammlungen](https://docs.astro.build/de/guides/content-collections/) auf, die in der Datei `src/content.config.ts` konfiguriert werden.

Erstelle oder aktualisiere die Inhalts­konfigurationsdatei und füge eine `docs`-Sammlung hinzu, die Starlights [`docsLoader`](/de/reference/configuration/#docsloader) und [`docsSchema`](/de/reference/configuration/#docsschema) verwendet:

```js ins={3-4,7}
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
};
```

Starlight unterstützt auch die Option [`legacy.collections`](https://docs.astro.build/de/reference/legacy-flags/), bei dem Sammlungen mit der Legacy-Implementierung von Inhaltssammlungen behandelt werden.
Dies ist nützlich, wenn du ein bestehendes Astro-Projekt hast und zum jetzigen Zeitpunkt keine Änderungen an den Sammlungen vornehmen kannst, um einen Loader zu verwenden.

### Inhalte hinzufügen

Starlight ist jetzt konfiguriert und du kannst Inhalte hinzuzufügen.

Erstelle ein Verzeichnis `src/content/docs/` und füge zunächst eine `index.md`-Datei hinzu.
Dies wird die Startseite deiner neuen Website sein:

```md
---
# src/content/docs/index.md
title: Meine Dokumentation
description: Erfahre mehr über mein Projekt auf dieser mit Starlight erstellten Dokumentationswebsite.
---

Willkommen bei meinem Projekt!
```

Starlight verwendet dateibasiertes Routing, was bedeutet, dass jede Markdown-, MDX- oder Markdoc-Datei in `src/content/docs/` zu einer Seite auf deiner Website wird. Frontmatter-Metadaten (die Felder `title` und `description` im obigen Beispiel) können ändern, wie jede Seite angezeigt wird.
Alle verfügbaren Optionen findest du in der [Frontmatter-Referenz](/de/reference/frontmatter/).

## Tipps für bestehende Websites

Wenn du ein bestehendes Astro-Projekt hast, kannst du mit Starlight schnell eine Dokumentation zu deiner Website hinzufügen.

### Starlight mit einem anderen Pfad verwenden

Um alle Starlight-Seiten mit einem anderen Pfad aufrufen zu können, lege den gesamten Inhalt in einem Unterverzeichnis von `src/content/docs/` ab.

Wenn zum Beispiel die URL alle Starlight-Seiten mit `/guides/` beginnen sollen, füge deine Inhalte in das Verzeichnis `src/content/docs/guides/` ein:

import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src/
  - content/
    - docs/
      - **guides/**
        - guide.md
        - index.md
  - pages/
- astro.config.mjs

</FileTree>

Für die Zukunft planen wir, diesen Anwendungsfall besser zu unterstützen, um die Notwendigkeit eines zusätzlichen verschachtelten Verzeichnisses in `src/content/docs/` zu vermeiden.

### Starlight mit SSR verwenden

Um SSR zu aktivieren, folge der Anleitung [„Serverseitiges Rendern (SSR)“](https://docs.astro.build/de/guides/on-demand-rendering/) in der Astro-Dokumentation, um einen Server-Adapter zu deinem Starlight-Projekt hinzuzufügen.

Die von Starlight erzeugten Dokumentations­seiten werden standardmäßig vorgerendert, unabhängig vom Ausgabemodus deines Projekts. Wenn du nicht möchtest, dass deine Starlight-Seiten vorgerendert werden, setze die [Konfigurations­option `prerender`](/de/reference/configuration/#prerender) auf `false`.


================================================
FILE: docs/src/content/docs/de/reference/configuration.mdx
================================================
---
title: Konfigurationsreferenz
description: Ein Überblick über alle von Starlight unterstützten Konfigurations­optionen.
sidebar:
  label: Konfiguration
---

## Konfiguriere die `starlight` Integration

Starlight ist eine Integration, die auf dem [Astro](https://astro.build) Web-Framework aufbaut. Du kannst dein Projekt innerhalb der Astro-Konfigurationsdatei `astro.config.mjs` anpassen:

```js
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'My delightful docs site',
		}),
	],
});
```

Du kannst die folgenden Optionen an die `starlight` Integration übergeben.

### `title` (erforderlich)

**Typ:** `string | Record<string, string>`

Lege den Titel für deine Website fest. Wird in den Metadaten und im Titel der Browser-Tabs verwendet.

Der Wert kann eine Zeichenkette sein, oder für mehrsprachige Websites ein Objekt mit Werten für jedes Gebietsschema.
Wenn die Objektform verwendet wird, müssen die Schlüssel BCP-47-Tags sein (z. B. `en`, `ar` oder `zh-CN`):

```ts
starlight({
	title: {
		en: 'My delightful docs site',
		de: 'Meine bezaubernde Dokumentationswebsite',
	},
});
```

### `description`

**Typ:** `string`

Lege die Beschreibung für deine Website fest. Wird in den Metadaten verwendet, die mit Suchmaschinen im `<meta name="description">`-Tag geteilt werden, für Seiten wo `description` nicht im Frontmatter festgelegt ist.

### `logo`

**Typ:** [`LogoConfig`](#logoconfig)

Legt ein Logobild fest, das in der Navigationsleiste neben oder anstelle des Seitentitels angezeigt wird. Du kannst entweder eine einzige `src`-Eigenschaft oder separate Bildquellen für `light` und `dark` festlegen.

```js
starlight({
	logo: {
		src: './src/assets/my-logo.svg',
	},
});
```

#### `LogoConfig`

```ts
type LogoConfig = { alt?: string; replacesTitle?: boolean } & (
	| { src: string }
	| { light: string; dark: string }
);
```

### `tableOfContents`

**Typ:** `false | { minHeadingLevel?: number; maxHeadingLevel?: number }`  
**Standard:** `{ minHeadingLevel: 2, maxHeadingLevel: 3 }`

Konfiguriere das Inhaltsverzeichnis, das rechts auf jeder Seite angezeigt wird. Standardmäßig werden `<h2>` und `<h3>` Überschriften in dieses Inhaltsverzeichnis aufgenommen.

### `editLink`

**Typ:** `{ baseUrl: string }`

Aktiviere „Diese Seite bearbeiten“-Links, indem du die Basis-URL für diese festlegst. Der endgültige Link wird `editLink.baseUrl` + der aktuelle Seitenpfad sein. Zum Beispiel, um das Bearbeiten von Seiten im `withastro/starlight` Repo auf GitHub zu ermöglichen:

```js
starlight({
	editLink: {
		baseUrl: 'https://github.com/withastro/starlight/edit/main/',
	},
});
```

Mit dieser Konfiguration würde eine `/einfuehrung` einen Bearbeitungslink haben, der auf `https://github.com/withastro/starlight/edit/main/src/content/docs/einfuehrung.md` zeigt.

### `sidebar`

**Typ:** [`SidebarItem[]`](#sidebaritem)

Konfiguriere die Navigationselemente der Seitenleiste deiner Website.

Eine Seitenleiste ist eine Array von Links und Linkgruppen.
Mit Ausnahme von Einträgen, die `slug` verwenden, muss jeder Eintrag ein `label` und eine der folgenden Eigenschaften haben:

- `link` - ein einzelner Link zu einer bestimmten URL, z. B. `'/home'` oder `'https://example.com'`.

- `slug` - ein Verweis auf eine interne Seite, z. B. `'guides/getting-started'`.

- `items` - ein Array, das weitere Links und Untergruppen enthält.

- `autogenerate` - ein Objekt, das ein Verzeichnis deiner Dokumentation angibt, aus dem automatisch eine Gruppe von Links erzeugt werden soll.

Interne Links können auch als Zeichenkette anstelle eines Objekts mit der Eigenschaft `slug` angegeben werden.

```js
starlight({
	sidebar: [
		// Ein einzelner Link mit der Bezeichnung "Startseite".
		{ label: 'Startseite', link: '/' },
		// Eine Gruppe mit der Bezeichnung „Hier beginnen“, die vier Links enthält.
		{
			label: 'Hier anfangen',
			items: [
				// Verwendung von `slug` für interne Links.
				{ slug: 'intro' },
				{ slug: 'installation' },
				// Oder du verwendst die Abkürzung für interne Links.
				'tutorial',
				'next-steps',
			],
		},
		// Eine Gruppe, die auf alle Seiten im Referenzverzeichnis verweist.
		{
			label: 'Referenzen',
			autogenerate: { directory: 'referenz' },
		},
	],
});
```

#### Sortierung

Die automatisch erstellten Seitenleisten-Gruppen werden alphabetisch nach dem Dateinamen sortiert.
Zum Beispiel würde eine Seite, die aus der Datei `astro.md` erzeugt wurde, über der Seite für `starlight.md` erscheinen.

#### Zusammenklappbare Gruppen

Gruppen von Links sind standardmäßig aufgeklappt. Du kannst dieses Verhalten ändern, indem du die Eigenschaft `collapsed` einer Gruppe auf `true` setzt.

Autogenerierte Untergruppen respektieren standardmäßig die Eigenschaft `collapsed` ihrer übergeordneten Gruppe. Dies kannst du mit der Eigenschaft `autogenerate.collapsed` außer Kraft setzen.

```js {5,13}
sidebar: [
  // Eine zusammengefasste Gruppe von Links
  {
    label: 'Zusammengeklappte Links',
    collapsed: true,
    items: ['intro', 'next-steps'],
  },
  // Eine aufgeklappte Gruppe, die automatisch generierte Untergruppen enthält, welche standardmäßig eingeklappt sind.
  {
    label: 'Referenzen',
    autogenerate: {
      directory: 'reference',
      collapsed: true,
    },
  },
],
```

#### Labels übersetzen

Wenn deine Website mehrsprachig ist, wird das `label` jedes Elements als in der Standard-Sprache verfasst betrachtet. Du kannst die Eigenschaft `translations` verwenden, um die Labels für andere unterstützte Sprachen festzulegen:

```js {5,9,14}
sidebar: [
  // Ein Beispiel für eine Seitenleiste mit ins Französische übersetzten Beschriftungen
  {
    label: 'Hier anfangen',
    translations: { fr: 'Commencez ici' },
    items: [
      {
        label: 'Erste Schritte',
        translations: { fr: 'Bien démarrer' },
        link: '/getting-started',
      },
      {
        label: 'Projektstruktur',
        translations: { fr: 'Structure du projet' },
        link: '/structure',
      },
    ],
  },
],
```

#### `SidebarItem`

```ts
type SidebarItem =
	| string
	| ({
			translations?: Record<string, string>;
			badge?: string | BadgeConfig;
	  } & (
			| {
					// Link
					link: string;
					label: string;
					attrs?: Record<string, string | number | boolean | undefined>;
			  }
			| {
					// Interner Link
					slug: string;
					label?: string;
					attrs?: Record<string, string | number | boolean | undefined>;
			  }
			| {
					// Gruppe von Links
					label: string;
					items: SidebarItem[];
					collapsed?: boolean;
			  }
			| {
					// Automatisch generierte Linkgruppe
					label: string;
					autogenerate: {
						directory: string;
						collapsed?: boolean;
						attrs?: Record<string, string | number | boolean | undefined>;
					};
					collapsed?: boolean;
			  }
	  ));
```

#### `BadgeConfig`

```ts
interface BadgeConfig {
	text: string;
	variant?: 'note' | 'tip' | 'caution' | 'danger' | 'success' | 'default';
	class?: string;
}
```

### `locales`

**Typ:** <code>\{ \[dir: string\]: [LocaleConfig](#localeconfig) \}</code>

[Konfiguriere die Internationalisierung (i18n)](/de/guides/i18n/) für deine Website, indem du festlegst, welche `locales` unterstützt werden.

Jeder Eintrag sollte das Verzeichnis, in dem die Dateien der jeweiligen Sprache gespeichert sind, als Schlüssel verwenden.

```js
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'My Docs',
			// Englisch als Standardsprache festlegen.
			defaultLocale: 'en',
			locales: {
				// Englische Seiten in `src/content/docs/en/`
				en: {
					label: 'English',
				},
				// Chinesische Seiten in `src/content/docs/zh-cn/`
				'zh-cn': {
					label: '简体中文',
					lang: 'zh-CN',
				},
				// Arabische Seiten in `src/content/docs/ar/`
				ar: {
					label: 'العربية',
					dir: 'rtl',
				},
			},
		}),
	],
});
```

#### `LocaleConfig`

```ts
interface LocaleConfig {
	label: string;
	lang?: string;
	dir?: 'ltr' | 'rtl';
}
```

Du kannst die folgenden Optionen für jedes Locale-Schema festlegen:

##### `label` (erforderlich)

**Typ:** `string`

Die Bezeichnung für diese Sprache, die den Benutzern angezeigt werden soll, z. B. im Sprachumschalter. Meistens wird dies der Name der Sprache sein, wie ihn ein Benutzer dieser Sprache erwarten würde, z. B. `"English"`, `"العربية"`, oder `"简体中文"`.

##### `lang`

**Typ:** `string`

Das BCP-47-Tag für diese Sprache, z. B. `"en"`, `"ar"` oder `"zh-CN"`. Wenn nicht gesetzt, wird standardmäßig der Verzeichnisname der Sprache verwendet. Sprach-Tags mit regionalen Unter-Tags (z. B. `"pt-BR"` oder `"en-US"`) verwenden integrierte UI-Übersetzungen für deine Basissprache, wenn keine regional­spezifischen Übersetzungen gefunden werden.

##### `dir`

**Typ:** `'ltr' | 'rtl'`

Die Schreibrichtung dieser Sprache; `"ltr"` für links-nach-rechts (die Voreinstellung) oder `"rtl"` für rechts-nach-links.

#### Root-Locale

Du kannst die Standardsprache ohne ein `/lang/`-Verzeichnis anbieten, indem du ein `root`-Locale setzst:

```js {3-6}
starlight({
	locales: {
		root: {
			label: 'Englisch',
			lang: 'en',
		},
		fr: {
			label: 'Français',
		},
	},
});
```

So kannst du zum Beispiel `/getting-started/` als englische Seite und `/fr/getting-started/` als entsprechende französische Seite verwenden.

### `defaultLocale`

**Typ:** `string`

Legt die Sprache fest, die als Standard für diese Website gilt.
Der Wert sollte mit einem der Schlüssel deines [`locales`](#locales)-Objekts übereinstimmen.
(Wenn deine Standardsprache deiner [Root-Locale](#root-locale) ist, kannst du dies überspringen).

Das standard Locale wird verwendet, um Ersatzinhalte bereitzustellen, wenn Übersetzungen fehlen.

### `social`

**Typ:** <code>{`Array<{ label: string; icon: `}[StarlightIcon](/de/reference/icons/){`; href: string }>`}</code>

Optionale Angaben zu den Social-Media-Konten für diese Website.
Jeder Eintrag wird als Symbol-Link in der Kopfzeile der Seite angezeigt.

```js
starlight({
	social: [
		{ icon: 'codeberg', label: 'Codeberg', href: 'https://codeberg.org/knut' },
		{ icon: 'discord', label: 'Discord', href: 'https://astro.build/chat' },
		{ icon: 'github', label: 'GitHub', href: 'https://github.com/withastro' },
		{ icon: 'gitlab', label: 'GitLab', href: 'https://gitlab.com/delucis' },
		{ icon: 'mastodon', label: 'Mastodon', href: 'https://m.webtoo.ls/@astro' },
	],
}),
```

### `customCss`

**Typ:** `string[]`

Stellen CSS-Dateien zur Verfügung, um das Aussehen deines Starlight-Projekts anzupassen.

Unterstützt lokale CSS-Dateien relativ zum Stammverzeichnis deines Projekts, z. B. `'./src/custom.css'`, und CSS, die du als npm-Modul installiert hast, z. B. `'@fontsource/roboto'`.

```js
starlight({
	customCss: ['./src/custom-styles.css', '@fontsource/roboto'],
});
```

### `markdown`

**Typ:** `{ headingLinks?: boolean; processedDirs?: string[] }`  
**Standard:** `{ headingLinks: true, processedDirs: [] }`

Konfiguriere die Markdown-Verarbeitung von Starlight.

#### `headingLinks`

**Typ:** `boolean`  
**Standard:** `true`

Steuert, ob Überschriften mit einem anklickbaren Ankerlink dargestellt werden oder nicht.

```js
starlight({
	markdown: {
		// Deaktiviere die anklickbaren Überschrift-Ankerlinks von Starlight.
		headingLinks: false,
	},
}),
```

#### `processedDirs`

**Typ:** `string[]`  
**Standard:** `[]`

Gib zusätzliche Ordner an, in denen Dateien von Starlights Markdown-Pipeline bearbeitet werden sollen.
Standardmäßig werden nur Markdown- und MDX-Inhalte verarbeitet, die mit Starlights [`docsLoader()`](/de/reference/configuration/#docsloader) geladen wurden.
Unterstützt lokale Verzeichnisse, die relativ zum Stammverzeichnis deines Projekts liegen, z. B. `./src/data/comments/`.

Starlight unterstützt [anklickbare Überschriften-Ankerlinks](#headinglinks), die [Markdown-Direktiven-Syntax für Asides](/de/guides/authoring-content/#nebenbemerkungen) und die RTL-Unterstützung für Code-Blöcke.
Diese Option kann nützlich sein, wenn du Inhalte aus einer benutzerdefinierten Inhaltssammlung in einer [benutzerdefinierten Seite](/de/guides/pages/#benutzerdefinierte-seiten) mit der Komponente `<StarlightPage>` rendern und erwartest, dass die Markdown-Verarbeitung von Starlight auch auf diese Inhalte angewendet wird.

```js
starlight({
	markdown: {
		// Verarbeite Markdown-Dateien aus der Inhaltssammlung `reviews`
		// im Verzeichnis `src/data/reviews/`.
		processedDirs: ['./src/data/reviews/'],
	},
}),
```

### `expressiveCode`

**Typ:** `StarlightExpressiveCodeOptions | boolean`  
**Standard:** `true`

Starlight verwendet [Expressive Code](https://expressive-code.com), um Codeblöcke zu rendern und Unterstützung für das Hervorheben von Teilen von Codebeispielen, das Hinzufügen von Dateinamen zu Codeblöcken und mehr hinzuzufügen.
Im [Handbuch „Codeblöcke“](/de/guides/authoring-content/#codeblöcke) erfährst du, wie du die Expressive Code-Syntax in deinen Markdown- und MDX-Inhalten verwendest.

Du kannst alle standardmäßigen [Expressive Code-Konfigurations­optionen](https://expressive-code.com/reference/configuration/) sowie einige Starlight-spezifische Eigenschaften verwenden, indem du sie in der Option `expressiveCode` von Starlight festlegst.
Lege beispielsweise die Option `styleOverrides` von Expressive Code fest, um das Standard-CSS zu überschreiben. Dadurch sind Anpassungen möglich, beispielsweise das Hinzufügen abgerundeter Ecken zu deinen Codeblöcken:

```js ins={2-4}
starlight({
	expressiveCode: {
		styleOverrides: { borderRadius: '0.5rem' },
	},
});
```

Wenn du Expressive Code deaktivieren möchtest, setze in deiner Starlight-Konfiguration `expressiveCode: false`:

```js ins={2}
starlight({
	expressiveCode: false,
});
```

Zusätzlich zu den standardmäßigen Expressive Code-Optionen kannst du in deiner `expressiveCode`-Konfiguration auch die folgenden Starlight-spezifischen Eigenschaften festlegen, um das Designverhalten für deine Codeblöcke weiter anzupassen:

#### `themes`

**Typ:** `Array<string | ThemeObject | ExpressiveCodeTheme>`  
**Standard:** `['starlight-dark', 'starlight-light']`

Lege die Designs fest, die zum Stylen von Codeblöcken verwendet werden.
Weitere Informationen zu den unterstützten Designformaten findest du in der [Expressive Code-Dokumentation zu Designs](https://expressive-code.com/guides/themes/).

Starlight verwendet standardmäßig die dunkle und helle Variante von Sarah Drasners [Night Owl-Thema](https://github.com/sdras/night-owl-vscode-theme).

Wenn du mindestens ein dunkles und ein helles Design angibst, wird Starlight das aktive Codeblock-Design automatisch mit dem aktuellen Website-Design synchron halten.
Konfiguriere dieses Verhalten mit der Option [`useStarlightDarkModeSwitch`](#usestarlightdarkmodeswitch).

#### `useStarlightDarkModeSwitch`

**Typ:** `boolean`  
**Standard:** `true`

Falls `true`, wechseln Codeblöcke automatisch zwischen hellen und dunklen Designs, wenn sich das Website-Design ändert.
Falls `false`, musst du manuell CSS hinzufügen, um das Wechseln zwischen mehreren Designs zu handhaben.

:::note
Beim Festlegen von `themes` musst du mindestens ein dunkles und ein helles Design angeben, damit der Wechsel zum Starlight-Dunkelmodus funktioniert.
:::

#### `useStarlightUiThemeColors`

**Typ:** `boolean`  
**Standard:** `true` wenn `themes` nicht gesetzt ist, andernfalls `false`

Falls `true`, werden Starlights CSS-Variablen für die Farben von Codeblock-UI-Elementen (Hintergründe, Schaltflächen, Schatten usw.) verwendet, die dem [Website-Farbdesign](/de/guides/css-and-tailwind/#themes) entsprechen.
Falls `false`, werden für diese Elemente die vom aktiven Syntaxhervorhebungs­design bereitgestellten Farben verwendet.

:::note
Wenn du benutzerdefinierte Themes verwendest und dies auf `true` setzt, musst du mindestens ein dunkles und ein helles Theme bereitstellen, um den richtigen Farbkontrast zu gewährleisten.
:::

### `pagefind`

**Typ:** <code>boolean | <a href="#pagefindoptions">PagefindOptions</a></code>  
**Standard:** `true`

Konfiguriere den Standard-Site-Suchanbieter von Starlight [Pagefind](https://pagefind.app/).

Setze diese Option auf `false`, um die Indizierung deiner Website mit Pagefind zu deaktivieren.
Dadurch wird auch die Standard-Suchoberfläche ausgeblendet, falls sie verwendet wird.

Pagefind kann nicht aktiviert werden, wenn die Option [`prerender`](#prerender) auf `false` gesetzt ist.

Setze `pagefind` auf ein Objekt, um den Pagefind-Suchclient zu konfigurieren:

- Siehe [„Anpassen des Pagefind-Rankings (EN)“](https://pagefind.app/docs/ranking/) in der Pagefind-Dokumentation für weitere Details über die Verwendung der Option `pagefind.ranking`, um zu kontrollieren, wie die Rangfolge der Suchergebnisse berechnet wird
- Siehe [„Mehrere Websites durchsuchen (EN)“](https://pagefind.app/docs/multisite/) in der Pagefind-Dokumentation für weitere Informationen über die Verwendung der Option `pagefind.mergeIndex` zur Steuerung der Suche über mehrere Websites

#### `PagefindOptions`

```ts
interface PagefindOptions {
	ranking?: {
		pageLength?: number;
		termFrequency?: number;
		termSaturation?: number;
		termSimilarity?: number;
	};
	indexWeight?: number;
	mergeIndex?: Array<{
		bundlePath: string;
		indexWeight?: number;
		basePath?: string;
		baseUrl?: string;
		mergeFilter?: Record<string, string | string[]>;
		language?: string;
		ranking?: {
			pageLength?: number;
			termFrequency?: number;
			termSaturation?: number;
			termSimilarity?: number;
		};
	}>;
}
```

### `prerender`

**Typ:** `boolean`  
**Standard:** `true`

Lege fest, ob Starlight-Seiten vorgerendert zu statischem HTML oder bei Bedarf von einem [SSR-Adapter](https://docs.astro.build/de/guides/on-demand-rendering/) gerendert werden sollen.

Starlight-Seiten werden standardmäßig vorgerendert.
Wenn du einen SSR-Adapter verwendest und Starlight-Seiten bei Bedarf rendern möchtest, setze `prerender: false`.

### `head`

**Typ:** [`HeadConfig[]`](#headconfig)

Füge zusätzliche Tags in den `<head>` deines Starlight-Projekts ein.
Kann nützlich sein, um Analytics und andere Skripte und Ressourcen von Drittanbietern hinzuzufügen.

```js
starlight({
	head: [
		// Beispiel: Fathom Analytics Skript-Tag hinzufügen.
		{
			tag: 'script',
			attrs: {
				src: 'https://cdn.usefathom.com/script.js',
				'data-site': 'MY-FATHOM-ID',
				defer: true,
			},
		},
	],
});
```

Einträge in `head` werden direkt in HTML-Elemente umgewandelt und durchlaufen nicht Astros [script](https://docs.astro.build/de/guides/client-side-scripts/#script-bundling) oder [style](https://docs.astro.build/de/guides/styling/#styles-stile-in-astro) Verarbeitung.
Wenn du lokale Elemente wie Skripte, Stile oder Bilder importieren musst, [überschreibe die Komponente Head](/de/guides/overriding-components/#eine-integrierte-komponente-wiederverwenden).

#### `HeadConfig`

```ts
interface HeadConfig {
	tag: string;
	attrs?: Record<string, string | boolean | undefined>;
	content?: string;
}
```

### `lastUpdated`

**Typ:** `boolean`  
**Standard:** `false`

Legt fest, ob in der Fußzeile angezeigt werden soll, wann die Seite zuletzt aktualisiert wurde.

Standardmäßig verwendet diese Funktion die Git-Historie deines Repositorys und kann auf einigen Bereitstellungs­plattformen, die [shallow clones](https://git-scm.com/docs/git-clone/de#git-clone---depthltTiefegt) durchführen, nicht genau sein. Eine Seite kann diese Einstellung oder das Git-basierte Datum mit dem [`lastUpdated` Frontmatter-Feld](/de/reference/frontmatter/#lastupdated) überschreiben.

### `pagination`

**Typ:** `boolean`  
**Standard:** `true`

Legt fest, ob die Fußzeile Links zur vorherigen und nächsten Seite enthalten soll.

Eine Seite kann diese Einstellung oder den Linktext und/oder die URL mit Hilfe der Frontmatter-Felder [`prev`](/de/reference/frontmatter/#prev) und [`next`](/de/reference/frontmatter/#next) überschreiben.

### `favicon`

**Typ:** `string`  
**Standard:** `'/favicon.svg'`

Legt den Pfad des Standard-Favicons für deine Website fest. Dieses sollte sich im Verzeichnis `public/` befinden und eine gültige Symbol-Datei (`.ico`, `.gif`, `.jpg`, `.png` oder `.svg`) sein.

```js
starlight({
  favicon: '/images/favicon.svg',
}),
```

Wenn du zusätzliche Varianten oder Fallback-Favicons festlegen musst, kannst du diese mit der Option [`head`](#head) Tags hinzufügen:

```js
starlight({
	favicon: '/images/favicon.svg',
	head: [
		// ICO-Favicon als Fallback für Safari hinzufügen
		{
			tag: 'link',
			attrs: {
				rel: 'icon',
				href: '/images/favicon.ico',
				sizes: '32x32',
			},
		},
	],
});
```

### `titleDelimiter`

**Typ:** `string`  
**Standard:** `'|'`

Legt das Trennzeichen zwischen Seitentitel und dem Titel der Website im `<title>`-Tag der Website fest, welches in den Browser-Tabs angezeigt wird.

Standardmäßig hat jede Seite einen `<title>` von `Seiten-Titel | Websitename`.
Zum Beispiel heißt diese Seite „Konfigurations­referenz“ und diese Website heißt „Starlight“, also ist der `<titel>` für diese Seite „Konfigurations­referenz | Starlight“.

### `disable404Route`

**Typ:** `Boolean`  
**Standard:** `false`

Deaktiviert die Einspeisung von Starlights Standard [404-Seite](https://docs.astro.build/de/basics/astro-pages/#benutzerdefinierte-404-fehlerseite). Um eine eigene `src/pages/404.astro`-Route in deinem Projekt zu verwenden, setze diese Option auf `true`.

### `routeMiddleware`

**Typ:** `string | string[]`

Gib Pfade zu Route-Middleware an, welche die Verarbeitung deiner Daten durch Starlight verändern kann.
Diese Dateipfade dürfen nicht mit [Astros Middleware](https://docs.astro.build/de/guides/middleware/) kollidieren.

In der [Routendaten-Anleitung](/de/guides/route-data/#anpassen-der-routendaten) findest du weitere Informationen zur Erstellung von Route-Middleware.

### `components`

**Typ:** `Record<string, string>`

Gib die Pfade zu den Komponenten an, um die Standard­implementierungen von Starlight zu ersetzen.

```js
starlight({
	components: {
		SocialLinks: './src/components/MySocialLinks.astro',
	},
});
```

Siehe die [Referenz der Ersetzung von Komponenten](/de/reference/overrides/) für Details zu allen Komponenten, die du überschreiben kannst.

### `plugins`

**Typ:** [`StarlightPlugin[]`](/de/reference/plugins/#api-schnellreferenz)

Erweitere Starlight mit eigenen Plugins.
Plugins nehmen Änderungen an deinem Projekt vor, um die Funktionen von Starlight zu verändern oder zu erweitern.

Besuche das [Plugins Schaufenster](/de/resources/plugins/#plugins) um eine Liste der verfügbaren Plugins zu sehen.

```js
starlight({
	plugins: [starlightPlugin()],
});
```

Siehe die [Referenz für Plugins](/de/reference/plugins/) für Details zur Erstellung eigener Plugins.

### `credits`

**Typ:** `boolean`  
**Standard:** `false`

Aktiviere die Anzeige eines „Erstellt mit Starlight“-Links in der Fußzeile deiner Website.

```js
starlight({
	credits: true,
});
```

## Inhaltssammlungen konfigurieren

Starlight nutzt Astro [Inhaltssammlungen](https://docs.astro.build/de/guides/content-collections/), um deine Inhalte zu laden.
Die Inhaltslader und Schemata von Starlight helfen dir dabei, die Sammlungen nach Bedarf zu konfigurieren.

```js
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';

export const collections = {
	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
	// Optional: Die i18n-Sammlung wird verwendet,
	// um die Benutzeroberfläche auf mehrsprachigen Websites zu übersetzen
	i18n: defineCollection({ loader: i18nLoader(), schema: i18nSchema() }),
};
```

### Inhaltslader

Starlight exportiert die folgenden [Astro-Lader](https://docs.astro.build/de/reference/content-loader-reference/) aus dem Modul `@astrojs/starlight/loaders`, um die Konfiguration von Inhaltssammlungen zu vereinfachen.

#### `docsLoader()`

Der `docsLoader()` lädt lokale Markdown-, MDX- und Markdoc-Dateien aus dem Verzeichnis `src/content/docs/`.
Dateinamen, die mit einem Unterstrich (`_`) beginnen, werden ignoriert.

##### Import

```js
import { docsLoader } from '@astrojs/starlight/loaders';
```

##### Optionen

###### `generateId()`

**Typ:** `({ entry: string; base: URL; data: Record<string, unknown> }) => string`

Standardmäßig werden mit `docsLoader()` erstellte Seiten so verarbeitet, dass Sonderzeichen entfernt und Dateinamen in Kleinbuchstaben umgewandelt werden.
Wenn du diese Standardeinstellung überschreiben möchtest, gib deine eigene `generateId()`-Funktion an.

Dies kann beispielsweise nützlich sein, um Sonderzeichen zu erhalten, die sonst entfernt würden.
Standardmäßig würde `Beispiel.Datei.md` unter `/beispieldatei` bereitgestellt werden.
Wenn du die Datei unter `/Beispiel.Datei` bereitstellen möchtest, kannst du dies tun, indem du eine benutzerdefinierte `generateId()`-Funktion definierst:

```js
docsLoader({
	// Entferne die Erweiterung `.md` oder `.mdx`,
	// aber verarbeite ansonsten die Dateinamen nicht.
	generateId: ({ entry }) => entry.split('.').slice(0, -1).join('.'),
}),
```

Weitere Infos findest du unter [`generateId()` in der Astro-Dokumentation](https://docs.astro.build/de/reference/content-loader-reference/#generateid).

#### `i18nLoader()`

`i18nLoader()` lädt lokale JSON- und YAML-Dateien aus dem Verzeichnis `src/content/i18n/`.
Dateinamen, die mit einem Unterstrich (`_`) beginnen, werden ignoriert.

##### Import

```js
import { i18nLoader } from '@astrojs/starlight/loaders';
```

##### Optionen

Derzeit gibt es keine Optionen zum Konfigurieren von `i18nLoader()`.

### Schemata

Starlight stellt die folgenden [Inhaltssammlungs­schemata](https://docs.astro.build/de/guides/content-collections/#defining-the-collection-schema) aus dem Modul `@astrojs/starlight/schema` zur Verfügung.
Diese Schemata müssen für die Sammlungen `docs` und `i18n` verwendet werden, von denen Starlight abhängt.

#### `docsSchema()`

`docsSchema()` analysiert die Frontmatter für alle deine Inhalte in der Sammlung `docs`.

##### Import

```js
import { docsSchema } from '@astrojs/starlight/schema';
```

##### Optionen

###### `extend`

**Typ:** Zod-Schema oder Funktion, die ein Zod-Schema zurückgibt
**Standard:** `z.object({})`

Erweitere das Frontmatter-Schema von Starlight um zusätzliche Felder.
Weitere Infos zur Verwendung der Option `extend` findest du unter [„Frontmatter-Schema anpassen“](/de/reference/frontmatter/#frontmatter-schema-anpassen).

#### `i18nSchema()`

`i18nSchema()` analysiert alle Dateien, die Daten enthalten, in der `i18n`-Sammlung.

##### Import

```js
import { i18nSchema } from '@astrojs/starlight/schema';
```

##### Optionen

###### `extend`

**Typ:** Zod-Objekt
**Standard:** `z.object({})`

Erweitere das i18n-Schema von Starlight um zusätzliche Felder.
Weitere Infos zur Verwendung der Option `extend` findest du unter [„Übersetzungsschema erweitern“](/de/guides/i18n/#übersetzungsschema-erweitern).


================================================
FILE: docs/src/content/docs/de/reference/frontmatter.md
================================================
---
title: Frontmatter Referenz
description: Ein Überblick über die von Starlight unterstützten Standard-Frontmatter-Felder.
sidebar:
  label: Frontmatter
---

Du kannst einzelne Markdown- und MDX-Seiten in Starlight anpassen, indem du Werte in deren Frontmatter setzt. Zum Beispiel könnte eine normale Seite die Felder `title` und `description` setzen:

```md {3-4}
---
# src/content/docs/example.md
title: Über dieses Projekt
description: Erfahre mehr über das Projekt, an dem ich gerade arbeite.
---

Willkommen auf der Info-Seite!
```

## Frontmatter-Felder

### `title` (erforderlich)

**Typ:** `string`

Du musst für jede Seite einen Titel angeben. Dieser wird oben auf der Seite, in Browser-Tabs und in den Seiten-Metadaten angezeigt.

### `description`

**Typ:** `string`

Die Seitenbeschreibung wird für die Metadaten der Seite verwendet und wird von Suchmaschinen und in der Vorschau von sozialen Medien angezeigt.

### `slug`

**Typ**: `string`

Setzt den Slug der Seite außer Kraft. Siehe [„Benutzerdefinierte IDs definieren“](https://docs.astro.build/de/guides/content-collections/#defining-custom-ids) in der Astro-Dokumentation für weitere Details.

### `editUrl`

**Typ:** `string | boolean`

Überschreibt die [globale `editLink`-Konfiguration](/de/reference/configuration/#editlink). Setze die Konfiguration auf `false`, um den Link `Seite bearbeiten` für eine bestimmte Seite zu deaktivieren oder gibt eine alternative URL an, unter welcher der Inhalt dieser Seite bearbeitet werden kann.

### `head`

**Typ:** [`HeadConfig[]`](/de/reference/configuration/#headconfig)

Du kannst zusätzliche Tags zum `<head>` deiner Seite hinzufügen, indem du das Feld `head` Frontmatter verwendest. Dies bedeutet, dass du benutzerdefinierte Stile, Metadaten oder andere Tags zu einer einzelnen Seite hinzufügen kannst. Ähnlich wie bei der [globalen `head` Option](/de/reference/configuration/#head).

```md
---
# src/content/docs/example.md
title: Über uns
head:
  # Benutze einen eigenen <title> Tag
  - tag: title
    content: Benutzerdefinierter "Über uns"-Titel
---
```

### `tableOfContents`

**Typ:** `false | { minHeadingLevel?: number; maxHeadingLevel?: number; }`

Überschreibt die [globale `tableOfContents`-Konfiguration](/de/reference/configuration/#tableofcontents).
Passe die einzuschließenden Überschriftsebenen an oder setze sie auf `false`, um das Inhaltsverzeichnis auf dieser Seite auszublenden.

```md
---
# src/content/docs/example.md
title: Seite mit nur H2s im Inhaltsverzeichnis
tableOfContents:
  minHeadingLevel: 2
  maxHeadingLevel: 2
---
```

```md
---
# src/content/docs/example.md
title: Seite ohne Inhaltsverzeichnis
tableOfContents: false
---
```

### `template`

**Typ:** `'doc' | 'splash'`  
**Standard:** `'doc'`

Legt die Layoutvorlage für diese Seite fest.
Seiten verwenden standardmäßig das `'doc'`-Layout.
Setze den Typen auf `'splash'`, um ein breiteres Layout ohne Seitenleisten zu verwenden, welches spezifisch für Startseiten entwickelt wurde.

### `hero`

**Typ:** [`HeroConfig`](#heroconfig)

Fügt eine Hero-Komponente oben auf der Seite ein. Kann sehr gut mit `template: splash` kombiniert werden.

Zum Beispiel zeigt diese Konfiguration einige übliche Optionen, einschließlich des Ladens eines Bildes aus deinem Repository.

```md
---
# src/content/docs/example.md
title: Meine Website
template: splash
hero:
  title: 'Mein Projekt: Schnell ins All'
  tagline: Bringe deine Wertgegenstände im Handumdrehen auf den Mond und wieder zurück.
  image:
    alt: Ein glitzerndes, leuchtend farbiges Logo
    file: ~/assets/logo.png
  actions:
    - text: Erzähl mir mehr
      link: /getting-started/
      icon: right-arrow
    - text: Schau mal auf GitHub vorbei
      link: https://github.com/astronaut/mein-projekt
      icon: external
      variant: minimal
      attrs:
        rel: me
---
```

Du kannst verschiedene Versionen der Hero-Komponente im hellen und dunklen Modus anzeigen.

```md
---
# src/content/docs/example.md
hero:
  image:
    alt: Ein glitzerndes, farbenfrohes Logo
    dark: ~/assets/logo-dark.png
    light: ~/assets/logo-light.png
---
```

#### `HeroConfig`

```ts
interface HeroConfig {
  title?: string;
  tagline?: string;
  image?:
    | {
        // Relativer Pfad zu einem Bild in deinem Repository.
        file: string;
        // Alt-Text, um das Bild für unterstützende Technologien zugänglich zu machen
        alt?: string;
      }
    | {
        // Relativer Pfad zu einem Bild in deinem Repository, das für den dunklen Modus verwendet werden soll.
        dark: string;
        // Relativer Pfad zu einem Bild in deinem Repository, das für den hellen Modus verwendet werden soll.
        light: string;
        // Alt-Text, um das Bild für unterstützende Technologien zugänglich zu machen
        alt?: string;
      }
    | {
        // HTML, welches im Bild-Slot verwendet werden soll.
        // Dies kann ein benutzerdefinierter `<img>`-Tag oder ein Inline-`<svg>` sein.
        html: string;
      };
  actions?: Array<{
    text: string;
    link: string;
    variant?: 'primary' | 'secondary' | 'minimal';
    icon?: string;
    attrs?: Record<string, string | number | boolean>;
  }>;
}
```

### `banner`

**Typ:** `{ content: string }`

Zeigt ein Ankündigungsbanner oben auf dieser Seite an.

Der Wert `content` kann HTML für Links oder andere Inhalte enthalten.
Auf dieser Seite wird beispielsweise ein Banner mit einem Link zu `example.com` angezeigt.

```md
---
# src/content/docs/example.md
title: Seite mit Banner
banner:
  content: |
    Wir haben gerade etwas Cooles angefangen!
    <a href="https://example.com">Jetzt besuchen</a>
---
```

### `lastUpdated`

**Typ:** `Date | boolean`

Überschreibt die [globale Option `lastUpdated`](/de/reference/configuration/#lastupdated). Wenn ein Datum angegeben wird, muss es ein gültiger [YAML-Zeitstempel](https://yaml.org/type/timestamp.html) sein und überschreibt somit das im Git-Verlauf für diese Seite gespeicherte Datum.

```md
---
# src/content/docs/example.md
title: Seite mit einem benutzerdefinierten Datum der letzten Aktualisierung
lastUpdated: 2022-08-09
---
```

### `prev`

**Typ:** `boolean | string | { link?: string; label?: string }`

Überschreibt die [globale Option `pagination`](/de/reference/configuration/#pagination). Wenn eine Zeichenkette angegeben wird, wird der generierte Linktext ersetzt und wenn ein Objekt angegeben wird, werden sowohl der Link als auch der Text überschrieben.

```md
---
# src/content/docs/example.md
# Versteckt den Link zur vorherigen Seite
prev: false
---
```

```md
---
# src/content/docs/example.md
# Überschreibe den Linktext der vorherigen Seite
prev: Fortsetzung des Tutorials
---
```

```md
---
# src/content/docs/example.md
# Überschreibe sowohl den Link zur vorherigen Seite als auch den Text
prev:
  link: /unverwandte-seite/
  label: Schau dir diese andere Seite an
---
```

### `next`

**Typ:** `boolean | string | { link?: string; label?: string }`

Dasselbe wie [`prev`](#prev), aber für den Link zur nächsten Seite.

```md
---
# src/content/docs/example.md
# Versteckt den Link zur nächsten Seite
next: false
---
```

### `pagefind`

**Typ:** `boolean`  
**Standard:** `true`

Legt fest, ob diese Seite in den [Pagefind](https://pagefind.app/)-Suchindex aufgenommen werden soll. Setze das Feld auf `false`, um eine Seite von den Suchergebnissen auszuschließen:

```md
---
# src/content/docs/example.md
# Diese Seite aus dem Suchindex ausblenden
pagefind: false
---
```

### `draft`

**Typ:** `boolean`  
**Standard:** `false`

Legt fest, ob diese Seite als Entwurf betrachtet werden soll und nicht in [Produktions-Builds](https://docs.astro.build/de/reference/cli-reference/#astro-build). Setze die Eigenschaft auf `true`, um eine Seite als Entwurf zu markieren und sie nur während der Entwicklung sichtbar zu machen.

```md
---
# src/content/docs/example.md
# Diese Seite von den Produktions-Builds ausschließen
draft: true
---
```

Da Entwurfsseiten nicht in die Build-Ausgabe aufgenommen werden, kannst du keine Entwurfsseiten direkt mit [Slugs](/de/guides/sidebar/#interne-links) zu deiner Seitenleisten­konfiguration hinzufügen.
Entwurfsseiten in Verzeichnissen, die für [autogenerierte Seitenleisten-Gruppen](/de/guides/sidebar/#automatisch-generierte-gruppen) verwendet werden, werden bei Produktions-Builds automatisch ausgeschlossen.

### `sidebar`

**Typ:** [`SidebarConfig`](#sidebarconfig)

Steuert, wie diese Seite in der [Seitenleiste](/de/reference/configuration/#sidebar) angezeigt wird, wenn eine automatisch generierte Linkgruppe verwendet wird.

#### `SidebarConfig`

```ts
interface SidebarConfig {
  label?: string;
  order?: number;
  hidden?: boolean;
  badge?: string | BadgeConfig;
  attrs?: Record<string, string | number | boolean | undefined>;
}
```

#### `label`

**Typ:** `string`  
**Standard:** der Seitentitel ([`title`](#title-erforderlich))

Legt die Bezeichnung für diese Seite in der Seitenleiste fest, wenn sie in einer automatisch generierten Linkgruppe angezeigt wird.

```md
---
# src/content/docs/example.md
title: Über dieses Projekt
sidebar:
  label: Infos
---
```

#### `order`

**Typ:** `number`

Steuere die Reihenfolge dieser Seite beim Sortieren einer automatisch erstellten Gruppe von Links.
Niedrigere Nummern werden in der Linkgruppe weiter oben angezeigt.

```md
---
# src/content/docs/example.md
title: Erste Seite
sidebar:
  order: 1
---
```

#### `hidden`

**Typ:** `boolean`  
**Standard:** `false`

Verhindert, dass diese Seite in eine automatisch generierte Seitenleistengruppe aufgenommen wird.

```md
---
# src/content/docs/example.md
title: Versteckte Seite
sidebar:
  hidden: true
---
```

#### `badge`

**Typ:** <code>string | <a href="/de/reference/configuration/#badgeconfig">BadgeConfig</a></code>

Füge der Seite in der Seitenleiste ein Abzeichen hinzu, wenn es in einer automatisch generierten Gruppe von Links angezeigt wird.
Bei Verwendung einer Zeichenkette wird das Abzeichen mit einer Standard-Akzentfarbe angezeigt.
Optional kann ein [`BadgeConfig` Objekt](/de/reference/configuration/#badgeconfig) mit den Feldern `text`, `variant` and `class` übergeben werden, um das Abzeichen anzupassen.

```md
---
# src/content/docs/example.md
title: Seite mit einem Badge
sidebar:
  # Verwendet die Standardvariante, die der Akzentfarbe deiner Website entspricht
  badge: Neu
---
```

```md
---
# src/content/docs/example.md
title: Seite mit einem Abzeichen
sidebar:
  badge:
    text: Experimentell
    variant: caution
---
```

#### `attrs`

**Typ:** `Record<string, string | number | boolean | undefined>`

HTML-Attribute, die dem Seitenlink in der Seitenleiste hinzugefügt werden, wenn er in einer automatisch generierten Gruppe von Links angezeigt wird.
Wenn [`autogenerate.attrs`](/de/guides/sidebar/#benutzerdefinierte-html-attribute-für-automatisch-generierte-links) für die automatisch generierte Gruppe, zu welcher diese Seite gehört, festgelegt ist, werden Frontmatter-Attribute mit den Gruppenattributen zusammengeführt.

```md
---
# src/content/docs/example.md
title: Seite im neuen Tab öffnen
sidebar:
  # Dies öffnet den Link in einem neuen Tab
  attrs:
    target: _blank
---
```

## Frontmatter-Schema anpassen

Das Frontmatter-Schema für die Starlight-Inhaltssammlung `docs` wird in `src/content.config.ts` mit dem `docsSchema()`-Helper konfiguriert:

```ts {4,7}
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
  docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
};
```

Mehr über Schemata für Inhaltssammlungen erfährst du in [„Definieren eines Sammelschemas“](https://docs.astro.build/de/guides/content-collections/#defining-the-collection-schema) in der Astro-Dokumentation.

`docsSchema()` nimmt die folgenden Optionen an:

### `extend`

**Typ:** Zod-Schema oder Funktion, die ein Zod-Schema zurückgibt  
**Standard:** `z.object({})`

Erweitere das Schema von Starlight um zusätzliche Felder, indem du `extend` in den `docsSchema()` Optionen setzt.
Der Wert sollte ein [Zod-Schema](https://docs.astro.build/de/guides/content-collections/#datentypen-mit-zod-definieren) sein.

Im folgenden Beispiel geben wir einen strengeren Typ für `description` an, um es zur Pflicht zu machen und fügen ein neues optionales Feld `category` hinzu:

```ts {10-15}
// src/content.config.ts
import { defineCollection, z } from 'astro:content';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
  docs: defineCollection({
    loader: docsLoader(),
    schema: docsSchema({
      extend: z.object({
        // Mache ein eingebautes Feld erforderlich statt optional.
        description: z.string(),
        // Füge dem Schema ein neues Feld hinzu.
        category: z.enum(['tutorial', 'guide', 'reference']).optional(),
      }),
    }),
  }),
};
```

Um die Vorteile der [Astro `image()`-Hilfe](https://docs.astro.build/de/guides/images/#bilder-in-inhaltssammlungen) zu nutzen, verwende eine Funktion, die deine Schemaerweiterung zurückgibt:

```ts {10-15}
// src/content.config.ts
import { defineCollection, z } from 'astro:content';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
  docs: defineCollection({
    loader: docsLoader(),
    schema: docsSchema({
      extend: ({ image }) => {
        return z.object({
          // Füge ein Feld hinzu, das auf ein lokales Bild aufgelöst werden muss.
          cover: image(),
        });
      },
    }),
  }),
};
```


================================================
FILE: docs/src/content/docs/de/reference/icons.mdx
================================================
---
title: Symbole Referenz
description: Eine Übersicht über alle in Starlight verfügbaren Symbole.
sidebar:
  label: Symbole
---

Starlight bietet eine Reihe von eingebauten Symbolen, die du mit Hilfe der Komponente `<Icon>` in deinem Inhalt anzeigen kannst.

## Symbole verwenden

Symbole können mit der Komponente [`<Icon>`](/de/components/icons/) angezeigt werden.
Sie werden auch häufig in anderen Komponenten verwendet, wie [Karten](/de/components/cards/) oder Umgebungen wie [Hero-Komponenten](/de/reference/frontmatter/#hero).

## `StarlightIcon`-Typ

Verwende den TypeScript-Typ `StarlightIcon`, um die Namen von [Starlights eingebauten Symbolen](#alle-symbole) zu referenzieren.

```ts {2} /icon: (StarlightIcon)/
// src/icon.ts
import type { StarlightIcon } from '@astrojs/starlight/types';

function getIconLabel(icon: StarlightIcon) {
	// …
}
```

## Alle Symbole

Nachstehend findest du eine Liste aller verfügbaren Symbole mit den zugehörigen Namen. Klicke auf ein Symbol, um den Namen in deine Zwischenablage zu kopieren.

import IconsList from '~/components/icons-list.astro';

<IconsList labels={{ copied: 'Kopiert!' }} />


================================================
FILE: docs/src/content/docs/de/reference/overrides.md
================================================
---
title: Ersetzung von Komponenten Referenz
description: Ein Überblick über die Komponenten und Komponenten­eigenschaften, die von Starlight Ersetzungen unterstützt werden.
tableOfContents:
  maxHeadingLevel: 4
sidebar:
  label: Ersetzung von Komponenten
---

Du kannst Starlights eingebaute Komponenten überschreiben, indem du Pfade zu Ersatzkomponenten in Starlights [`components`](/de/reference/configuration/#components)-Konfigurations­option angibst.
Diese Seite listet alle Komponenten auf, die überschrieben werden können, und verweist auf ihre Standard­implementierungen auf GitHub.

Erfahre mehr in der [Anleitung zum Überschreiben von Komponenten](/de/guides/overriding-components/).

---

## Komponenten

### Head

Diese Komponenten werden innerhalb des `<head>`-Elements jeder Seite gerendert.
Sie sollten nur [innerhalb von `<head>` erlaubte Elemente](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head#see_also) enthalten.

#### `Head`

**Standardkomponente:** [`Head.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Head.astro)

Diese Komponente wird innerhalb des `<head>` einer jeden Seite gerendert.

Überschreibe diese Komponente nur, wenn es unbedingt notwendig ist.
Bevorzuge die [Konfigurationsoption `head`](/de/reference/configuration/#head), das [Frontmatter-Feld `head`](/de/reference/frontmatter/#head) oder eine [Routendaten-Middleware](/de/guides/route-data/#anpassen-der-routendaten), um die von der Standardkomponente dargestellten Routendaten nach Möglichkeit anzupassen.

#### `ThemeProvider`

**Standardkomponente:** [`ThemeProvider.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/ThemeProvider.astro)

Diese Komponente wird innerhalb von `<head>` gerendert und richtet die Unterstützung für dunkle/helle Themen ein.
Die Standard-Implementierung enthält ein Inline-Skript und ein `<template>`, welches vom Skript in [`<ThemeSelect />`](#themeselect) verwendet wird.

---

### Barrierefreiheit

#### `SkipLink`

**Standardkomponente:** [`SkipLink.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/SkipLink.astro)

Diese Komponente wird als erstes Element innerhalb von `<body>` dargestellt und verweist aus Gründen der Barrierefreiheit auf den Hauptinhalt der Seite.
Die Standard­implementierung ist ausgeblendet, bis ein Benutzer sie durch Tabulatorbewegungen mit der Tastatur aktiviert.

---

### Layout

Diese Komponenten sind für das Layout der Starlight-Komponenten und die Verwaltung von Ansichten über verschiedene Haltepunkte hinweg verantwortlich.
Das Überschreiben dieser Komponenten ist mit erheblicher Komplexität verbunden.
Wenn möglich, bevorzuge das Überschreiben einer Komponente auf einer niedrigeren Ebene.

#### `PageFrame`

**Standardkomponente:** [`PageFrame.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/PageFrame.astro)  
**Benannte Slots:** `header`, `sidebar`

Diese Layout-Komponente beinhaltet den größten Teil des Seiteninhalts.
Die Standard­implementierung konfiguriert das Kopfzeilen-Seitennavigation-Haupt-Layout und beinhaltet `header` und `sidebar` benannte Slots zusammen mit einem Standard-Slot für den Hauptinhalt.
Sie rendert auch [`<MobileMenuToggle />`](#mobilemenutoggle), um das Umschalten der Seitenleisten­navigation auf kleinen (mobilen) Viewports zu unterstützen.

#### `MobileMenuToggle`

**Standardkomponente:** [`MobileMenuToggle.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MobileMenuToggle.astro)

Diese Komponente wird innerhalb von [`<PageFrame>`](#pageframe) gerendert und ist für das Umschalten der Seitenleisten­navigation auf kleinen (mobilen) Viewports verantwortlich.

#### `TwoColumnContent`

**Standardkomponente:** [`TwoColumnContent.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/TwoColumnContent.astro)  
**Benannter Slot:** `right-sidebar`

Dies ist die Layout-Komponente, welche die Hauptinhaltsspalte und die rechte Seitenleiste (Inhaltsverzeichnis) beinhaltet.
Die Standard­implementierung behandelt den Wechsel zwischen einem einspaltigen Layout mit kleinem Sichtfeld und einem zweispaltigen Layout mit größerem Sichtfeld.

---

### Kopfzeile

Diese Komponenten stellen die obere Navigationsleiste von Starlight dar.

#### `Header`

**Standardkomponente:** [`Header.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Header.astro)

Dies ist eine Kopfzielen-Komponente, welche oben auf jeder Seite angezeigt wird.
Die Standard­implementierung zeigt [`<SiteTitle />`](#sitetitle), [`<Search />`](#search), [`<SocialIcons />`](#socialicons), [`<ThemeSelect />`](#themeselect), und [`<LanguageSelect />`](#languageselect).

#### `SiteTitle`

**Standardkomponente:** [`SiteTitle.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/SiteTitle.astro)

Die Komponente wird die am Anfang des Website-Headers gerendert, um den Titel der Website darzustellen.
Die Standard­implementierung enthält die Logik für die Darstellung von Logos, die in der Starlight-Konfiguration definiert sind.

#### `Search`

**Standardkomponente:** [`Search.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Search.astro)

Diese Komponente wird verwendet, um Starlights Suchoberfläche darzustellen.
Die Standard­implementierung enthält die Schaltfläche in der Kopfzeile und den Code für die Anzeige eines Suchmodals, wenn darauf geklickt wird, und das Laden von [Pagefinds UI](https://pagefind.app/).

Wenn [`pagefind`](/de/reference/configuration/#pagefind) deaktiviert ist, wird die Standard-Suchkomponente nicht angezeigt.
Wenn du jedoch `Search` überschreibst, wird deine benutzerdefinierte Komponente immer angezeigt, auch wenn die Konfigurations­option `pagefind` auf `false` gesetzt ist.
So kannst du eine Benutzeroberfläche für alternative Suchanbieter hinzufügen, wenn du Pagefind deaktivierst.

#### `SocialIcons`

**Standardkomponente:** [`SocialIcons.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/SocialIcons.astro)

Diese Komponente wird in der Kopfzeile der Website gerendert und enthält Symbol-Links zu sozialen Netzwerken.
Die Standard­implementierung verwendet die Option [`social`](/de/reference/configuration/#social) in der Starlight-Konfiguration, um Symbole und Links darzustellen.

#### `ThemeSelect`

**Standardkomponente:** [`ThemeSelect.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/ThemeSelect.astro)

Diese Komponente wird in der Kopfzeile der Website gerendert und ermöglicht es den Benutzern, ihr bevorzugtes Farbschema auszuwählen.

#### `LanguageSelect`

**Standardkomponente:** [`LanguageSelect.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/LanguageSelect.astro)

Die Komponente wird in der Kopfzeile der Website angezeigt und ermöglicht es den Nutzern, die Sprache auszuwählen.

---

### Globale Seitenleiste

Die globale Seitenleiste von Starlight enthält die Hauptnavigation der Website.
Bei schmalen Ansichtsfenstern ist diese hinter einem Dropdown-Menü versteckt.

#### `Sidebar`

**Standardkomponente:** [`Sidebar.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Sidebar.astro)

Die Komponente wird die vor dem Seiteninhalt gerendert und enthält eine globale Navigation.
Die Standard­implementierung wird als Seitenleiste in ausreichend breiten Ansichtsfenstern und innerhalb eines Dropdown-Menüs in kleinen (mobilen) Ansichtsfenstern angezeigt.
Sie rendert auch [`<MobileMenuFooter />`](#mobilemenufooter), um zusätzliche Elemente innerhalb des mobilen Menüs anzuzeigen.

#### `MobileMenuFooter`

**Standardkomponente:** [`MobileMenuFooter.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MobileMenuFooter.astro)

Diese Komponente wird die am unteren Ende des mobilen Dropdown-Menüs gerendert.
Die Standard­implementierung rendert [`<ThemeSelect />`](#themeselect) und [`<LanguageSelect />`](#languageselect).

---

### Seitenleiste des Inhalts

Die Seitenleiste von Starlight ist für die Anzeige eines Inhalts­verzeichnisses verantwortlich, welches die Untertitel der aktuellen Seite anzeigt.
Bei schmalen Ansichtsfenstern wird diese Leiste zu einem Dropdown-Menü.

#### `PageSidebar`

**Standardkomponente:** [`PageSidebar.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/PageSidebar.astro)

Diese Komponente wird die vor dem Inhalt der Hauptseite gerendert, um ein Inhaltsverzeichnis anzuzeigen.
Die Standard­implementierung rendert [`<TableOfContents />`](#tableofcontents) und [`<MobileTableOfContents />`](#mobiletableofcontents).

#### `TableOfContents`

**Standardkomponente:** [`TableOfContents.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/TableOfContents.astro)

Eine Komponente zur Darstellung des Inhalts­verzeichnisses der aktuellen Seite in breiteren Ansichtsfenstern.

#### `MobileTableOfContents`

**Standardkomponente:** [`MobileTableOfContents.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MobileTableOfContents.astro)

Diese Komponete zeigt das Inhaltsverzeichnis der aktuellen Seite auf kleinen (mobilen) Bildschirmen an.

---

### Inhalt

Folgende Komponenten werden in der Hauptspalte des Seiteninhalts wiedergegeben.

#### `Banner`

**Standardkomponente:** [`Banner.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Banner.astro)

Diese Bannerkomponente wird oben auf jeder Seite angezeigt.
Die Standard-Implementierung verwendet den [`banner`](/de/reference/frontmatter/#banner)-Frontmatter-Wert der Seite, um zu entscheiden, ob sie gerendert wird oder nicht.

#### `ContentPanel`

**Standardkomponente:** [`ContentPanel.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/ContentPanel.astro)

Diese Layout-Komponente beinhaltet Abschnitte der Hauptinhaltsspalte.

#### `PageTitle`

**Standardkomponente:** [`PageTitle.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/PageTitle.astro)

Eine Komponente, welche das `<h1>`-Element für die aktuelle Seite enthält.

Implementierungen sollten sicherstellen, dass sie `id="_top"` auf dem `<h1>` Element wie in der Standard­implementierung setzen.

#### `DraftContentNotice`

**Standardkomponente:** [`DraftContentNotice.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/DraftContentNotice.astro)

Hinweis, der den Nutzern während der Entwicklung angezeigt wird, wenn die aktuelle Seite als Entwurf markiert ist.

#### `FallbackContentNotice`

**Standardkomponente:** [`FallbackContentNotice.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/FallbackContentNotice.astro)

Ein Hinweis, welcher den Benutzern auf der Seite angezeigt wird, für die keine Übersetzung in der aktuellen Sprache verfügbar ist.
Wird nur auf mehrsprachigen Websites verwendet.

#### `Hero`

**Standardkomponente:** [`Hero.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Hero.astro)

Diese Komponente wird am oberen Rand der Seite angezeigt, wenn [`hero`](/de/reference/frontmatter/#hero) in frontmatter eingestellt ist.
Die Standard­implementierung zeigt einen großen Titel, eine Tagline und Call-to-Action-Links neben einem optionalen Bild.

#### `MarkdownContent`

**Standardkomponente:** [`MarkdownContent.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MarkdownContent.astro)

Die Kompoente wird um den Hauptinhalt jeder Seite gerendert.
Die Standard­implementierung richtet grundlegende Stile ein, die auf Markdown-Inhalte angewendet werden.

Die Markdown-Inhaltsstile werden auch in der Datei `@astrojs/starlight/style/markdown.css` veröffentlicht und auf die CSS-Klasse `.sl-markdown-content` bezogen.

---

### Fußzeile

Diese Komponenten werden am unteren Ende der Hauptspalte des Seiteninhalts dargestellt.

#### `Footer`

**Standardkomponente:** [`Footer.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Footer.astro)

Diese Fußzeile-Komponente wird am unteren Rand jeder Seite angezeigt.
Die Standard­implementierung zeigt [`<LastUpdated />`](#lastupdated), [`<Pagination />`](#pagination), und [`<EditLink />`](#editlink).

#### `LastUpdated`

**Standardkomponente:** [`LastUpdated.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/LastUpdated.astro)

Eine Komponente, die in der Fußzeile der Seite gerendert wird, um das zuletzt aktualisierte Datum anzuzeigen.

#### `EditLink`

**Standardkomponente:** [`EditLink.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/EditLink.astro)

Die Komponente wird in der Fußzeile der Seite gerendert, um einen Link anzuzeigen, über den die Seite bearbeitet werden kann.

#### `Pagination`

**Standardkomponente:** [`Pagination.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Pagination.astro)

Diese Komponente wird in der Fußzeile der Seite gerendert, um Navigationspfeile zwischen vorherigen/nächsten Seiten anzuzeigen.


================================================
FILE: docs/src/content/docs/de/reference/plugins.md
================================================
---
title: Plugins Referenz
description: Ein Überblick über die Starlight-Plugin-API.
tableOfContents:
  maxHeadingLevel: 4
sidebar:
  label: Plugins
---

Starlight-Plugins können die Konfiguration, die Benutzeroberfläche und das Verhalten von Starlight anpassen und sind gleichzeitig einfach weiterzugeben und wiederzuverwenden.
Diese Referenzseite dokumentiert die API, auf die Plugins Zugriff haben.

Erfahre mehr über die Verwendung eines Starlight-Plugins in der [Konfigurations­referenz](/de/reference/configuration/#plugins) oder besuche das [Plugins Schaufenster](/de/resources/plugins/#plugins), um eine Liste der verfügbaren Plugins zu sehen.

## API-Schnellreferenz

Ein Starlight-Plugin hat die folgende Form.
Siehe unten für Details zu den verschiedenen Eigenschaften und Hook-Parametern.

<!-- prettier-ignore-start -->
```ts
interface StarlightPlugin {
  name: string;
  hooks: {
    'i18n:setup'?: (options: {
      injectTranslations: (
        translations: Record<string, Record<string, string>>
      ) => void;
    }) => void | Promise<void>;
    'config:setup': (options: {
      config: StarlightUserConfig;
      updateConfig: (newConfig: StarlightUserConfig) => void;
      addIntegration: (integration: AstroIntegration) => void;
      addRouteMiddleware: (config: { entrypoint: string; order?: 'pre' | 'post' | 'default' }) => void;
      astroConfig: AstroConfig;
      command: 'dev' | 'build' | 'preview';
      isRestart: boolean;
      logger: AstroIntegrationLogger;
      useTranslations: (lang: string) => I18nT;
      absolutePathToLang: (path: string) => string;
    }) => void | Promise<void>;
  };
}
```
<!-- prettier-ignore-end -->

## `name`

**Typ:** `string`

Ein Plugin muss einen eindeutigen Namen angeben, der es beschreibt. Der Name wird verwendet, wenn [Logging-Nachrichten](#logger) sich auf dieses Plugin bezieht und kann von anderen Plugins verwendet werden, um das Vorhandensein dieses Plugins zu erkennen.

## `hooks`

Hooks sind Funktionen, die Starlight aufruft, um Plugin-Code zu bestimmten Zeiten auszuführen.

Um den Typ der Argumente eines Hooks zu erhalten, verwende den Utility-Typ `HookParameters` und gib den Namen des Hooks an.
Im folgenden Beispiel wird der Parameter `options` so eingegeben, dass er mit den Argumenten übereinstimmt, die an den Hook `config:setup` übergeben werden:

```ts
import type { HookParameters } from '@astrojs/starlight/types';

function configSetup(options: HookParameters['config:setup']) {
  options.useTranslations('de');
}
```

### `i18n:setup`

Die Funktion zum Einrichten der Plugin-Internationalisierung wird beim Initialisieren von Starlight aufgerufen.
Der `i18n:setup`-Hook kann verwendet werden, um Übersetzungsstrings zu injizieren, damit ein Plugin verschiedene Locales unterstützen kann.
Diese Übersetzungen werden über [`useTranslations()`](#usetranslations) im `config:setup`-Hook und in UI-Komponenten über [`Astro.locals.t()`](/de/guides/i18n/#ui-übersetzungen-verwenden) verfügbar sein.

Der `i18n:setup`-Hook wird mit den folgenden Optionen aufgerufen:

#### `injectTranslations`

**Typ:** `(translations: Record<string, Record<string, string>>) => void`

Eine Callback-Funktion zum Hinzufügen oder Aktualisieren von Übersetzungsstrings, die in Starlights [Lokalisierungs-APIs](/de/guides/i18n/#ui-übersetzungen-verwenden) verwendet werden.

Im folgenden Beispiel injiziert ein Plugin Übersetzungen für einen benutzerdefinierten UI-String mit dem Namen `myPlugin.doThing` für die Sprachumgebungen `en` und `fr`:

```ts {6-13} /(injectTranslations)[^(]/
// plugin.ts
export default {
  name: 'plugin-use-translations',
  hooks: {
    'i18n:setup'({ injectTranslations }) {
      injectTranslations({
        en: {
          'myPlugin.doThing': 'Do the thing',
        },
        fr: {
          'myPlugin.doThing': 'Faire le truc',
        },
      });
    },
  },
};
```

Um die injizierten Übersetzungen in der Benutzeroberfläche deines Plugins zu verwenden, befolge die [„UI-Übersetzungen verwenden“-Anleitung](/de/guides/i18n/#ui-übersetzungen-verwenden).
Wenn du UI-Strings im Zusammenhang mit dem [`config:setup`](#configsetup)-Hook deines Plugins verwenden musst, kannst du den [`useTranslations()`](#usetranslations)-Callback verwenden.

Die Typen für die injizierten Übersetzungsstrings eines Plugins werden im Projekt des Benutzers automatisch generiert, sind aber bei der Arbeit in der Codebasis deines Plugins noch nicht verfügbar.
Um das Objekt `locals.t` im Kontext deines Plugins zu typisieren, deklariere die folgenden globalen Namespaces in einer TypeScript-Deklarationsdatei:

```ts
// env.d.ts
declare namespace App {
  type StarlightLocals = import('@astrojs/starlight').StarlightLocals;
  // Definiere das Objekt `locals.t` im Kontext eines Plugins.
  interface Locals extends StarlightLocals {}
}

declare namespace StarlightApp {
  // Definiere die zusätzlichen Plugin-Übersetzungen in der `I18n`-Schnittstelle.
  interface I18n {
    'myPlugin.doThing': string;
  }
}
```

Du kannst die Typen für die Schnittstelle `StarlightApp.I18n` auch aus einer Quelldatei ableiten, wenn du ein Objekt hast, das deine Übersetzungen enthält.

Nehmen wir zum Beispiel die folgende Quelldatei:

```ts title="ui-strings.ts"
export const UIStrings = {
  en: { 'myPlugin.doThing': 'Do the thing' },
  fr: { 'myPlugin.doThing': 'Faire le truc' },
};
```

Die folgende Deklaration würde die Typen aus den englischen Schlüsseln in der Quelldatei ableiten:

```ts title="env.d.ts"
declare namespace StarlightApp {
  type UIStrings = typeof import('./ui-strings').UIStrings.en;
  interface I18n extends UIStrings {}
}
```

### `config:setup`

Plugin-Konfiguration-Setup-Funktion, die aufgerufen wird, wenn Starlight initialisiert wird (während des [`astro:config:setup`](https://docs.astro.build/de/reference/integrations-reference/#astroconfigsetup) Integrations-Hooks).
Der `config:setup`-Hook kann verwendet werden, um die Starlight-Konfiguration zu aktualisieren oder Astro-Integrationen hinzuzufügen.

Dieser Hook wird mit den folgenden Optionen aufgerufen:

#### `config`

**Typ:** `StarlightUserConfig`

Eine schreibgeschützte Kopie der vom Benutzer bereitgestellten [Starlight-Konfiguration](/de/reference/configuration/).
Diese Konfiguration kann durch andere Plugins, die vor dem aktuellen Plugin konfiguriert wurden, aktualisiert worden sein.

#### `updateConfig`

**Typ:** `(newConfig: StarlightUserConfig) => void`

Eine Callback-Funktion zur Aktualisierung der vom Benutzer bereitgestellten [Starlight-Konfiguration](/de/reference/configuration/).
Gib die Konfigurations­schlüssel der root-Ebene an, die du überschreiben möchtest.
Um verschachtelte Konfigurationswerte zu aktualisieren, musst du das gesamte verschachtelte Objekt bereitstellen.

Um eine vorhandene Konfigurations­option zu erweitern, ohne sie außer Kraft zu setzen, wird der vorhandene Wert in den neuen Wert übertragen.
Im folgenden Beispiel wird ein neues [`social`](/de/reference/configuration/#social) Medienkonto zur bestehenden Konfiguration hinzugefügt, indem `config.social` in das neue `social`-Array übertragen wird:

```ts {6-15}
// plugin.ts
export default {
  name: 'add-twitter-plugin',
  hooks: {
    'config:setup'({ config, updateConfig }) {
      updateConfig({
        social: [
          ...config.social,
          {
            icon: 'twitter',
            label: 'Twitter',
            href: 'https://twitter.com/astrodotbuild',
          },
        ],
      });
    },
  },
};
```

#### `addIntegration`

**Typ:** `(integration: AstroIntegration) => void`

Eine Callback-Funktion zum Hinzufügen einer [Astro-Integration](https://docs.astro.build/de/reference/integrations-reference/), die vom Plugin benötigt wird.

Im folgenden Beispiel prüft das Plugin zunächst, ob [Astros React-Integration](https://docs.astro.build/de/guides/integrations-guide/react/) konfiguriert ist, und fügt sie, falls nicht, mit `addIntegration()` hinzu:

```ts {14} "addIntegration,"
// plugin.ts
import react from '@astrojs/react';

export default {
  name: 'plugin-using-react',
  hooks: {
    'config:setup'({ addIntegration, astroConfig }) {
      const isReactLoaded = astroConfig.integrations.find(
        ({ name }) => name === '@astrojs/react'
      );

      // Füge die React-Integration nur hinzu, wenn sie nicht bereits geladen ist.
      if (!isReactLoaded) {
        addIntegration(react());
      }
    },
  },
};
```

#### `addRouteMiddleware`

**Typ:** `(config: { entrypoint: string; order?: 'pre' | 'post' | 'default'}) => void`

Eine Callback-Funktion, um der Website einen [Routen-Middleware-Handler](/de/guides/route-data/) hinzuzufügen.

Die Eigenschaft `entrypoint` muss ein Modulbezeichner für die Middleware-Datei deines Plugins sein, die einen `onRequest`-Handler exportiert.

Im folgenden Beispiel fügt ein Plugin, das unter dem Namen `@example/starlight-plugin` veröffentlicht wurde, eine Route-Middleware über einen npm-Modul-Spezifizierer hinzu:

```js {6-9}
// plugin.ts
export default {
  name: '@example/starlight-plugin',
  hooks: {
    'config:setup'({ addRouteMiddleware }) {
      addRouteMiddleware({
        entrypoint: '@example/starlight-plugin/route-middleware',
      });
    },
  },
};
```

##### Kontrolle der Ausführungs­reihenfolge

Standardmäßig wird die Plugin-Middleware in der Reihenfolge ausgeführt, in der die Plugins hinzugefügt werden.

Verwende die optionale Eigenschaft `order`, wenn du mehr Kontrolle darüber brauchst, wann deine Middleware läuft.
Setze `order: "pre"`, um vor der Middleware eines Benutzers zu laufen.
Setze `order: "post"`, um nach allen anderen Middlewares zu laufen.

Wenn zwei Plugins Middleware mit demselben `order`-Wert hinzufügen, wird das zuerst hinzugefügte Plugin zuerst ausgeführt.

#### `astroConfig`

**Typ:** `AstroConfig`

Eine schreibgeschützte Kopie der vom Benutzer bereitgestellten [Astro-Konfiguration](https://docs.astro.build/de/reference/configuration-reference/).

#### `command`

**Typ:** `'dev' | 'build' | 'preview'`

Der Befehl, mit dem Starlight gestartet wird:

- `dev` - Projekt wird mit `astro dev` ausgeführt
- `build` - Projekt wird mit `astro build` ausgeführt
- `preview` - Projekt wird mit `astro preview` ausgeführt

#### `isRestart`

**Typ:** `boolean`

`false`, wenn der Dev-Server startet, `true`, wenn ein Reload ausgelöst wird.
Häufige Gründe für einen Neustart sind, dass ein Benutzer seine `astro.config.mjs` bearbeitet, während der Dev-Server läuft.

#### `logger`

**Typ:** `AstroIntegrationLogger`

Eine Instanz des [Astro-Integrationsloggers](https://docs.astro.build/de/reference/integrations-reference/#astrointegrationlogger), die du zum Schreiben von Protokollen verwenden kannst.
Allen protokollierten Meldungen wird der Name des Plugins vorangestellt.

```ts {6}
// plugin.ts
export default {
  name: 'long-process-plugin',
  hooks: {
    'config:setup'({ logger }) {
      logger.info('Beginn eines langen Prozesses…');
      // Ein langer Prozess…
    },
  },
};
```

Im obigen Beispiel wird eine Meldung protokolliert, die die angegebene Info-Meldung enthält:

```shell
[long-process-plugin] Beginn eines langen Prozesses…
```

#### `useTranslations`

**Typ:** `(lang: string) => I18nT`

Rufe `useTranslations()` mit einem BCP-47-Sprach-Tag auf, um eine Utility-Funktion zu generieren, die Zugriff auf UI-Strings für diese Sprache bietet.
`useTranslations()` gibt ein Äquivalent der API `Astro.locals.t()` zurück, die in Astro-Komponenten verfügbar ist.
Weitere Informationen zu den verfügbaren APIs findest du im Leitfaden [„UI-Übersetzungen verwenden“](/de/guides/i18n/#ui-übersetzungen-verwenden).

```ts {6}
// plugin.ts
export default {
  name: 'plugin-use-translations',
  hooks: {
    'config:setup'({ useTranslations, logger }) {
      const t = useTranslations('zh-CN');
      logger.info(t('builtWithStarlight.label'));
    },
  },
};
```

Im obigen Beispiel wird eine Meldung protokolliert, die einen integrierten UI-String für die vereinfachte chinesische Sprache enthält:

```shell
[plugin-use-translations] 基于 Starlight 构建
```

#### `absolutePathToLang`

**Typ:** `(path: string) => string`

Rufe `absolutePathToLang()` mit einem absoluten Dateipfad auf, um die Sprache für diese Datei zu erhalten.

Dies kann besonders nützlich sein, wenn du [remark oder rehype Plugins](https://docs.astro.build/de/guides/markdown-content/#markdown-plugins) hinzufügst, um Markdown- oder MDX-Dateien zu verarbeiten.
Das von diesen Plugins verwendete [virtuelle Dateiformat](https://github.com/vfile/vfile) enthält den [absoluten Pfad](https://github.com/vfile/vfile#filepath) der zu verarbeitenden Datei, der mit `absolutePathToLang()` verwendet werden kann, um die Sprache der Datei zu bestimmen.
Die zurückgegebene Sprache kann mit dem Helfer [`useTranslations()`](#usetranslations) verwendet werden, um UI-Strings für diese Sprache zu erhalten.

Nehmen wir zum Beispiel die folgende Starlight-Konfiguration:

```js
starlight({
  title: 'Meine Dokumentation',
  defaultLocale: 'en',
  locales: {
    // Englische Dokumentationen in `src/content/docs/en/`
    en: { label: 'English' },
    // Französische Dokumentationen in `src/content/docs/fr/`
    fr: { label: 'Français', lang: 'fr' },
  },
});
```

Ein Plugin kann die Sprache einer Datei anhand ihres absoluten Pfads bestimmen:

```ts {6-8} /fr/
// plugin.ts
export default {
  name: 'plugin-use-translations',
  hooks: {
    'config:setup'({ absolutePathToLang, useTranslations, logger }) {
      const lang = absolutePathToLang(
        '/absolute/path/to/project/src/content/docs/fr/index.mdx'
      );
      const t = useTranslations(lang);
      logger.info(t('aside.tip'));
    },
  },
};
```

Im obigen Beispiel wird eine Meldung protokolliert, die einen integrierten UI-String für die französische Sprache enthält:

```shell
[plugin-use-translations] Astuce
```


================================================
FILE: docs/src/content/docs/de/reference/route-data.mdx
================================================
---
title: Routendaten Referenz
description: Die vollständige Referenz­dokumentation für Starlights Routendatenobjekt.
sidebar:
  label: Routendaten
---

Das Routendatenobjekt von Starlight enthält Informationen über die aktuelle Seite.
Erfahre mehr darüber, wie das Datenmodell von Starlight funktioniert, in der [„Routendaten“-Anleitung](/de/guides/route-data/).

In Astro-Komponenten greifst du auf die Routendaten von `Astro.locals.starlightRoute` zu:

```astro {4}
---
// src/components/Custom.astro

const { hasSidebar } = Astro.locals.starlightRoute;
---
```

In der [Routen-Middleware](/de/guides/route-data/#anpassen-der-routendaten) greifst du auf die Routendaten aus dem Kontextobjekt zu, das an deine Middleware-Funktion übergeben wird:

```ts {5}
// src/routeData.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

export const onRequest = defineRouteMiddleware((context) => {
	const { hasSidebar } = context.locals.starlightRoute;
});
```

## `starlightRoute`

Das Objekt `starlightRoute` hat die folgenden Eigenschaften:

### `dir`

**Typ:** `'ltr' | 'rtl'`

Schreibrichtung der Seite.

### `lang`

**Typ:** `string`

BCP-47-Sprachkennzeichen für das Gebietsschema dieser Seite, z. B. `de`, `zh-CN` oder `pt-BR`.

### `locale`

**Typ:** `string | undefined`

Der Basispfad, unter dem eine Sprache angeboten wird. `undefined` für Root-Locale-Slugs.

### `siteTitle`

**Typ:** `string`

Der Seitentitel für das Gebietsschema dieser Seite.

### `siteTitleHref`

**Typ:** `string`

Der Wert für das Attribut `href` des Seitentitels, der auf die Homepage zurückverweist, z. B. `/`.
Bei mehrsprachigen Websites wird hier das aktuelle Gebietsschema angegeben, z. B. `/en/` oder `/zh-cn/`.

### `slug`

**Typ:** `string`

Der aus dem Dateinamen des Inhalts generierte Slug für diese Seite.

Diese Eigenschaft ist veraltet und wird in einer zukünftigen Version von Starlight entfernt werden.
Stelle auf die neue Content Layer API um, indem du [Starlights `docsLoader`](/de/manual-setup/#konfigurieren-von-inhaltssammlungen) benutzt und verwende stattdessen die Eigenschaft [`id`](#id).

### `id`

**Typ:** `string`

Der Slug für diese Seite oder die eindeutige ID für diese Seite, die auf dem Dateinamen des Inhalts basiert, wenn du das Flag [`legacy.collections`](https://docs.astro.build/de/reference/legacy-flags/#collections) benutzt.

### `isFallback`

**Typ:** `boolean | undefined`

`true`, wenn diese Seite in der aktuellen Sprache unübersetzt ist und Fallback-Inhalte aus dem Standardgebiets­schema verwendet.
Wird nur in mehrsprachigen Websites verwendet.

### `entryMeta`

**Typ:** `{ dir: 'ltr' | 'rtl'; lang: string }`

Gebietsschema-Metadaten für den Seiteninhalt. Du kannst von den Werten der Top-Level-Locale unterscheiden, wenn eine Seite Fallback-Inhalte verwendet.

### `entry`

Der Astro-Inhaltssammlungs­eintrag für die aktuelle Seite.
Beinhaltet Frontmatter-Werte für die aktuelle Seite in `entry.data`.

```ts
entry: {
	data: {
		title: string;
		description: string | undefined;
		// usw.
	}
}
```

Erfahre mehr über die Form dieses Objekts in der [Astros Eintragstyp-Sammlung](https://docs.astro.build/de/reference/modules/astro-content/#collectionentry) Referenz.

### `sidebar`

**Typ:** `SidebarEntry[]`

Seitennavigations­einträge für diese Seite.

### `hasSidebar`

**Typ:** `boolean`

Ob die Seitenleiste auf dieser Seite angezeigt werden soll oder nicht.

### `pagination`

**Typ:** `{ prev?: Link; next?: Link }`

Links zur vorherigen und nächsten Seite in der Seitenleiste, falls aktiviert.

### `toc`

**Typ:** `{ minHeadingLevel: number; maxHeadingLevel: number; items: TocItem[] } | undefined`

Inhaltsverzeichnis für diese Seite, falls aktiviert.

### `headings`

**Typ:** `{ depth: number; slug: string; text: string }[]`

Array aller Markdown-Überschriften, die aus der aktuellen Seite extrahiert wurden.
Verwende stattdessen [`toc`](#toc), wenn du einen Inhaltsverzeichnis-Komponenten erstellen willst, welches die Konfigurations­optionen von Starlight berücksichtigt.

### `lastUpdated`

**Typ:** `Date | undefined`

JavaScript `Date` Objekt, welches angibt, wann diese Seite zuletzt aktualisiert wurde, falls aktiviert.

### `editUrl`

**Typ:** `URL | undefined`

`URL`-Objekt für die Adresse, unter der diese Seite bearbeitet werden kann, falls aktiviert.

### `head`

**Typ:** [`HeadConfig[]`](/de/reference/configuration/#headconfig)

Array mit allen Tags, die in den `<head>` der aktuellen Seite aufgenommen werden sollen.
Enthält wichtige Tags wie `<title>` und `<meta charset="utf-8">`.

## Hilfsmittel

### `defineRouteMiddleware()`

Verwende das Hilfsmethode `defineRouteMiddleware()`, um dein Route-Middleware-Modul zu definieren:

```ts "defineRouteMiddleware"
// src/routeData.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

export const onRequest = defineRouteMiddleware((context) => {
	// ...
});
```

### `StarlightRouteData`-Typ

Wenn du Code schreibst, der mit den Routendaten von Starlight arbeiten muss, kannst du den Typ `StarlightRouteData` importieren, damit er der Form von `Astro.locals.starlightRoute` entspricht.

Im folgenden Beispiel aktualisiert die Funktion `usePageTitleInTOC()` die Routedaten so, dass der Titel der aktuellen Seite als Beschriftung für den ersten Eintrag im Inhaltsverzeichnis verwendet wird und die Standard­beschriftung „Übersicht“ ersetzt.
Mit dem Typ `StarlightRouteData` kannst du prüfen, ob die Änderungen der Routendaten gültig sind.

```ts "StarlightRouteData"
// src/route-utils.ts
import type { StarlightRouteData } from '@astrojs/starlight/route-data';

export function usePageTitleInTOC(starlightRoute: StarlightRouteData) {
	const overviewLink = starlightRoute.toc?.items[0];
	if (overviewLink) {
		overviewLink.text = starlightRoute.entry.data.title;
	}
}
```

Diese Funktion kann dann von einer Route Middleware aufgerufen werden:

```ts {3,6}
// src/route-middleware.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';
import { usePageTitleInTOC } from './route-utils';

export const onRequest = defineRouteMiddleware((context) => {
	usePageTitleInTOC(context.locals.starlightRoute);
});
```


================================================
FILE: docs/src/content/docs/de/resources/community-content.mdx
================================================
---
title: Community-Inhalte
description: Entdecke von der Community erstellte Anleitungen, Artikel und Videos, die dir helfen, Starlight zu erlernen und zu bauen!
---

:::tip[Füge dein eigenes hinzu!]
Hast du Inhalte über Starlight produziert?
Eröffne eine PR und füge einen Link zu dieser Seite hinzu!
:::

import { CardGrid, LinkCard } from '@astrojs/starlight/components';

## Artikel und Rezensionen

Hier findest du eine Sammlung von Beiträgen und Artikeln, in denen du mehr über Starlight und die Erfahrungen anderer Menschen erfährst:

<CardGrid>
	<LinkCard
		href="https://devm.io/open-source/starlight-astro"
		title="Statische Website-Erstellung mit Starlight"
		description="“Bei der Entwicklung von Komponenten ist keine Idee zu groß oder zu klein“ - ein Interview mit Chris Swithinbank, Starlight Leiter"
	/>
	<LinkCard
		href="https://frontendatscale.com/blog/hybrid-frontend-architecture/"
		title="Hybride Frontend-Architektur mit Astro und Starlight"
		description="Maxi Ferreira und Ben Holmes bauen eine Dokumentationswebsite mit Starlight, TinaCMS und einem interaktiven API Playground mit Authentifizierung."
	/>
	<LinkCard
		href="https://www.olets.dev/posts/comparing-docs-site-builders-vuepress-vs-starlight/"
		title="Vergleich von Dokumentations­websites-Frameworks: VuePress vs. Starlight"
		description="Wie schneiden diese beiden Frameworks ab?"
	/>
	<LinkCard
		href="https://astro.build/case-studies/wp-engine/"
		title="Fallstudie: Senkung der Entwicklungskosten"
		description="Wie WP Engine mit Astro's Starlight die Entwicklungskosten um über 50% senken konnte."
	/>
	<LinkCard
		href="https://maciekpalmowski.dev/blog/building-a-documentation-site-using-astro-starlight/"
		title="Aufbau einer Dokumentationswebsite mit Astro Starlight"
		description="Maciek Palmowski beschreibt, wie Patchstack seine Dokumentation zu Starlight migriert hat"
	/>
	<LinkCard
		href="https://blog.cloudflare.com/open-source-all-the-way-down-upgrading-our-developer-documentation/"
		title="Open Source von Anfang bis Ende"
		description="Wie Cloudflare Starlight benutzt hat, um seine Entwickler­dokumentation zu verbessern."
	/>
	<LinkCard
		href="https://starlight-changelog.netlify.app/"
		title="Starlight Changelog"
		description="Sieh dir alle Veröffentlichungen des @astrojs/starlight-Pakets auf einer einzigen schönen Website an."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/contributing-to-starlight"
		title="Zu Starlight beitragen"
		description="Meine Erfahrungen und Tipps, wie man bei Open-Source-Projekten wie Starlight mitmachen kann."
	/>
</CardGrid>

## Beispiele und Leitfäden

Beispiele sind in der Regel kurze, konzentrierte Anleitungen, die den Leser durch ein funktionierendes Beispiel für eine bestimmte Aufgabe führen. Beispiele sind eine gute Möglichkeit, deinem Starlight-Projekt neue Funktionen oder Verhaltensweisen hinzuzufügen, indem du Schritt-für-Schritt-Anweisungen befolgst! Andere Anleitungen erklären Konzepte, die sich auf einen bestimmten Inhaltsbereich beziehen, z. B. die Verwendung von Bildern oder das Arbeiten mit MDX.

Erkunde die von der Community erstellten Inhalte, die von Starlight-Benutzern gepflegt werden:

<CardGrid>
	<LinkCard
		href="https://www.webpro.nl/scraps/versioned-docs-with-starlight-and-vercel"
		title="Versionierte Dokumentation mit Starlight & Vercel"
		description="Ein Leitfaden für die Implementierung separater Versionen der Dokumentation für jede Hauptversion eines Projekts."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-heading-links"
		title="Links zu Starlight Überschriften hinzufügen"
		description="Eine Anleitung zur Verwendung eines Rehype-Plugins, um Links zu bestimmten Abschnitten deiner Dokumentation zu teilen."
	/>
	<LinkCard
		href="https://blog.otterlord.dev/posts/starlight-sponsors/"
		title="Füge Sponsoren zu deiner Starlight-Website hinzu"
		description="Eine Anleitung zur Implementierung einer benutzerdefinierten Sponsorenkomponente in deiner Dokumentations-Seitenleiste."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-og-images"
		title="Open Graph Bilder zu Starlight hinzufügen"
		description="Ein Leitfaden zur Erstellung von sozialen Bildern und den entsprechenden Meta-Tags für deine Website."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-third-party-icon-sets"
		title="Symbol-Sets von Drittanbietern in Starlight verwenden"
		description="Eine Anleitung zur Verwendung von unplugin-icons, um die Auswahl an verfügbaren Symbolen für Starlight zu erweitern."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-custom-html-head"
		title="Bearbeite den HTML-Kopf von Starlight-Websites"
		description="Lerne, wie du gängige Kopfinhalte wie Webanalysen, Schriftarten und Skripte hinzufügen kannst."
	/>
	<LinkCard
		href="https://dev.to/mrrobot/publishing-documentation-with-astro-starlight-691"
		title="Dokumentation mit Astro Starlight veröffentlichen"
		description="Erste Schritte mit der Starlight-Dokumentation."
	/>
	<LinkCard
		href="https://events-3bg.pages.dev/jotter/starlight/"
		title="Aktiviere Ansichtsübergänge"
		description="Füge Unterstützung für Ansichtsübergänge, clientseitiges Routing und SPA-ähnliche Navigation zu deiner Starlight-Dokumentationsseite hinzu."
	/>
	<LinkCard
		href="https://jamcomments.com/posts/structured-data-with-starlight"
		title="Hinzufügen von strukturierten Daten zu Starlight-Websites"
		description="Lerne, wie du dynamische JSON-LD strukturierte Daten für deine Dokumentations­websites erstellst."
	/>
	<LinkCard
		href="https://starlight-examples.netlify.app/"
		title="Starlight Beispiele"
		description="Eine Sammlung von StackBlitz-Einbettungen, die zeigen, wie man in Starlight-Dokumentations­websites praktische Dinge tun kann."
	/>
	<LinkCard
		href="https://hideoo.dev/notebooks/starlight-plugins-by-example"
		title="Starlight-Plugins anhand von Beispielen"
		description="Eine Sammlung von Notizen und Beispielen zu Starlight-Plugins und gängigen Mustern, die zum Erstellen dieser Plugins verwendet werden."
	/>
	<LinkCard
		href="https://blog.trueberryless.org/blog/starlight-progress-indicator/"
		title="Lesefortschrittsanzeige hinzufügen"
		description="Erfahre, wie du eine horizontale Lesefortschrittsanzeige zu deiner Starlight-Website hinzufügen kannst."
	/>
	<LinkCard
		href="https://blog.trueberryless.org/blog/starlight-sidebar-whitespace/"
		title="Verwende eigene Stile für deine Starlight-Seitenleiste"
		description="Mit ein bisschen CSS kannst du Schriftarten, Farben und mehr in der Starlight-Seitenleiste anpassen."
	/>
	<LinkCard
		href="https://blog.trueberryless.org/blog/starlight-dropdown-and-list-together/"
		title="Starlight-Themen Dropdown auf Mobilgeräten, Liste auf Desktop-Computern"
		description="Kombiniere zwei Plugins, um das Beste aus beiden auf Desktop- und Mobilgeräten zu erhalten."
	/>
	<LinkCard
		href="https://blog.trueberryless.org/blog/starlight-autogenerate-whole-sidebar/"
		title="Verarbeitung von Starlight-Seitenleisten mit Middleware"
		description="Benutze Route-Middleware, um die Reihenfolge der Seitenleisten und Gruppenbeschriftungen zu steuern, inspiriert von den Konventionen von Nuxt Content."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-custom-social-links"
		title="Füge soziale Links mit benutzerdefinierten Symbolen zu Starlight hinzu"
		description="Hier erfährst du, wie du eigene Symbole für Social-Media-Links im Header der Starlight-Website verwenden kannst."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-paste-images-with-visual-studio-code"
		title="Bilder mit Visual Studio Code in Starlight-Seiten einfügen"
		description="Verbessere deinen Starlight-Dokumentations-Workflow, indem du Bilder mit Visual Studio Code in deine Dokumentationsseiten einfügst."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-add-diagrams-using-d2"
		title="Füge Diagramme mit D2 zu deiner Starlight-Dokumentation hinzu"
		description="Lerne, wie du mit D2 Diagramme zu deiner Starlight-Dokumentation hinzufügen kannst."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-og-images-cloudinary-astro-sdk"
		title="Erstelle Open-Graph-Bilder für Starlight mit dem Cloudinary Astro SDK."
		description="Lerne, wie du mit dem Cloudinary Astro SDK Open-Graph-Bilder für deine Starlight-Dokumentationswebsite machst."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-list-recent-github-releases"
		title="Zeig die neuesten GitHub-Veröffentlichungen in Starlight mit der Astro Content Layer API an."
		description="Lerne, wie du die Astro Content Layer API nutzen kannst, um die neuesten GitHub-Veröffentlichungen in einem Starlight-Projekt aufzulisten."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-sitewide-banner"
		title="Füge ein siteweites Banner zu Starlight hinzu"
		description="Lerne, wie du mit der integrierten Bannerfunktion von Starlight ein siteweites Banner erstellen kannst."
	/>
	<LinkCard
		href="https://lirantal.com/blog/customizing-astro-starlight-sidebar-gated-content-auth"
		title="Anpassen der Astro Starlight-Seitenleiste für geschützte Inhalte mit Authentifizierung"
		description="Schütze dein Kursmaterial, indem du Clerk und SSR nutzt, um die Kapitel in der Starlight-Seitenleiste je nach Benutzeranmeldung dynamisch auszublenden oder anzuzeigen."
	/>
</CardGrid>

## Video-Inhalte

Entdecke Videos und Kanäle mit Starlight-Inhalten, darunter Live-Streams und Bildungsinhalte.

import YouTubeGrid from '~/components/youtube-grid.astro';

### Official-Videos

<YouTubeGrid
	videos={[
		{
			href: 'https://www.youtube.com/watch?v=5u0Ds7wzUeI',
			title: 'Starlight von Astro',
			description: 'Sieh dir das offizielle Starlight-Startvideo an',
		},
		{
			href: 'https://www.youtube.com/watch?v=j8K-ESJF814',
			title: 'Ein Jahr Starlight!',
			description:
				'Sarah redet über Astros von der Community erstelltes Dokumentationstheme',
		},
	]}
/>

### Community Videos und Streams

<YouTubeGrid
	videos={[
		{
			href: 'https://www.youtube.com/shorts/zjOWezSzd18',
			title: '🌟 SUB 1 MINUTE RUN',
			description:
				'Sieh dir an, wie Ben eine neue Starlight-Website in weniger als einer Minute startet!',
		},
		{
			href: 'https://www.youtube.com/watch?v=sF6UcV3moZg',
			title: 'Dokumentation mit Starlight und Astro erstellen',
			description:
				'Schau dir an, wie Chris und Alex mit CodingCat.dev in den Code von Starlight eintauchen',
		},
		{
			href: 'https://www.youtube.com/watch?v=sWkkHbwDeQc',
			title: 'Astro Starlight',
			description: 'Einführung in Starlight in weniger als einer Minute.',
		},
		{
			href: 'https://www.youtube.com/watch?v=-Ki-1E5gNCk',
			title:
				'Astro Starlight Dokumentations­vorlage (Erstelle eigene Applikations-Dokumentation!)',
			description:
				'Eine neue Starlight-Website ist in etwa 5 Minuten einsatzbereit',
		},
		{
			href: 'https://www.youtube.com/watch?v=12o7WxjAxjM',
			title:
				'Starlight-Dokumentation in ein Next.js-Projekt mit Proxys einbinden',
			description:
				'Starlight als Unterverzeichnis-Projekt innerhalb einer Next.js-Website einrichten',
		},
		{
			href: 'https://www.youtube.com/watch?v=5pq80drDrNs',
			title:
				'Mit diesem tollen Tool habe ich Shadcns Dokumentation in 30 Minuten neu erstellt',
			description:
				'In diesem Video erkläre ich dir, was Starlight so cool macht und warum du es vielleicht bei deinem nächsten Projekt ausprobieren solltest.',
		},
		{
			href: 'https://www.youtube.com/watch?v=Q1E4Gkt63ko',
			title: 'Astro Starlight und Emoji-Blast mit Chris Swithinbank',
			description:
				'Chris, der Schöpfer von Astros Starlight-Framework, zeigt mir, wie ich es für eine neue Emoji-Website einrichte. 🌟 🎇',
		},
	]}
/>


================================================
FILE: docs/src/content/docs/de/resources/plugins.mdx
================================================
---
title: Plugins und Integrationen
description: Entdecke Community-Tools wie Plugins und Integrationen, die Starlight erweitern!
sidebar:
  order: 1
---

:::tip[Füge dein eigenes hinzu!]
Hast du ein Plugin oder ein Tool für Starlight entwickelt?
Eröffne einen PR und füge einen Link zu dieser Seite hinzu!
:::

## Plugins

[Plugins](/de/reference/plugins/) können die Konfiguration, die Benutzeroberfläche und das Verhalten von Starlight anpassen und sind gleichzeitig einfach weiterzugeben und wiederzuverwenden.
Erweitere deine Website mit offiziellen Plugins, die vom Starlight-Team unterstützt werden, und mit Community-Plugins, die von Starlight-Nutzern gepflegt werden.

### Offizielle Plugins

<CardGrid>
	<LinkCard
		href="/de/guides/site-search/#algolia-docsearch"
		title="Algolia DocSearch"
		description="Ersetze Pagefind, den Standard-Suchanbieter, durch Algolia DocSearch."
	/>
</CardGrid>

### Community-Plugins

<CardGrid>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-links-validator"
		title="starlight-links-validator"
		description="Überprüfe deine Starlight-Website auf defekte Links."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-typedoc"
		title="starlight-typedoc"
		description="Erstelle Starlight-Websites aus TypeScript mit TypeDoc."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-blog"
		title="starlight-blog"
		description="Füge einen Blog zu deiner Dokumentationswebsite hinzu."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-openapi"
		title="starlight-openapi"
		description="Erstelle Dokumentations­websites aus OpenAPI/Swagger-Spezifikationen."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-obsidian"
		title="starlight-obsidian"
		description="Veröffentliche Obsidian-Tresore auf deiner Starlight-Website."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-image-zoom"
		title="starlight-image-zoom"
		description="Füge deinen Dokumentations­bildern Zoomfunktionen hinzu."
	/>
	<LinkCard
		href="https://github.com/lorenzolewis/starlight-utils"
		title="starlight-utils"
		description="Erweitere Starlight mit einer Sammlung von allgemeinen Dienstprogrammen."
	/>
	<LinkCard
		href="https://github.com/trueberryless/starlight-view-modes"
		title="starlight-view-modes"
		description="Füge deiner Dokumentations-Website verschiedene Ansichtsmodi hinzu."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-versions"
		title="starlight-versions"
		description="Versioniere deine Starlight-Dokumentations­website."
	/>
	<LinkCard
		href="https://inox-tools.fryuni.dev/star-warp"
		title="star-warp"
		description="Warp-Drive durch die Suchergebnisse in deiner Dokumentation."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-heading-badges"
		title="starlight-heading-badges"
		description="Füge Abzeichen zu deinen Markdown- und MDX-Überschriften hinzu."
	/>
	<LinkCard
		href="https://github.com/Fevol/starlight-site-graph"
		title="starlight-site-graph"
		description="Füge einen interaktiven Graphen in die Seitenleiste deiner Website ein."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-sidebar-topics"
		title="starlight-sidebar-topics"
		description="Unterteile deine Dokumentation in verschiedene Abschnitte, die jeweils eine eigene Seitenleiste haben."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-cooler-credit"
		title="starlight-cooler-credit"
		description="Füge einen netten Verweis auf Starlight oder Astro am Ende des Inhalts­verzeichnisses ein."
	/>
	<LinkCard
		href="https://github.com/dragomano/starlight-giscus"
		title="starlight-giscus"
		description="Füge Giscus-Kommentare zu deiner Dokumentations-Website hinzu."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-videos"
		title="starlight-videos"
		description="Verbessere deine Dokumentation mit Videoanleitungen und Kursen."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-kbd"
		title="starlight-kbd"
		description="Dokumentiere Tastaturkürzel mit Leichtigkeit."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-auto-sidebar"
		title="starlight-auto-sidebar"
		description="Modifiziere deine automatisch generierten Seitenleistengruppen."
	/>
	<LinkCard
		href="https://github.com/delucis/starlight-llms-txt"
		title="starlight-llms-txt"
		description="Füge llms.txt zu deiner Dokumentationsseite hinzu, welche auf llmstxt.org basiert."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-toc-overview-customizer"
		title="starlight-toc-overview-customizer"
		description="Modifiziere Starlights Inhaltsverzeichnis mit anpassbarem Übersichtstitel."
	/>
	<LinkCard
		href="https://delucis.github.io/starlight-markdown-blocks/"
		title="starlight-markdown-blocks"
		description="Erweiter Starlights Markdown-Nebenbemerkungs-Syntax um eigene Blocktypen."
	/>
	<LinkCard
		href="https://github.com/WindMillCode/starlight-fullview-mode"
		title="starlight-fullview-mode"
		description="Klappe die Seitenleisten ein und erweitere den Inhalt für ein Vollbildschirm-Erlebnis."
	/>
	<LinkCard
		href="https://github.com/frostybee/starlight-scroll-to-top"
		title="starlight-scroll-to-top"
		description="Füge deiner Dokumentations-Website eine Schaltfläche „Nach oben scrollen“ hinzu."
	/>
	<LinkCard
		href="https://github.com/frostybee/starlight-codeblock-fullscreen"
		title="starlight-codeblock-fullscreen"
		description="Füge eine Funktion zum Umschalten zwischen Vollbildmodus und Normalansicht zu den Expressive Code-Blöcken in deiner Dokumentation hinzu."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-auto-drafts"
		title="starlight-auto-drafts"
		description="Passe das Standardverhalten von Entwurfsseiten an und entferne automatisch Links zur Seitenleiste zu Entwurfsseiten im Produktionsmodus."
	/>
	<LinkCard
		href="https://github.com/corsfix/starlight-contextual-menu"
		title="starlight-contextual-menu"
		description="Füge ein Kontextmenü zu deiner Starlight-Dokumentation hinzu."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-changelogs"
		title="starlight-changelogs"
		description="Zeige Änderungsprotokolle neben deiner Projektdokumentation an."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-github-alerts"
		title="starlight-github-alerts"
		description="GitHub-Warnungen als Starlight-Nebenbemerkungen anzeigen."
	/>
	<LinkCard
		href="https://github.com/dlcastillop/starlight-page-actions"
		title="starlight-page-actions"
		description="Fügt deiner Dokumentation Seitenaktionsschaltflächen hinzu."
	/>
	<LinkCard
		href="https://github.com/typesense/starlight-docsearch-typesense"
		title="starlight-docsearch-typesense"
		description="Eine von Typesense unterstützte Alternative zum offiziellen Algolia DocSearch-Plugin."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-sidebar-swipe/"
		title="starlight-sidebar-swipe"
		description="Mach die linke Seitenleiste auf Handys wischbar wie Discord Mobile."
	/>
	<LinkCard
		href="https://github.com/Rettend/starlight-plugin-icons"
		title="starlight-plugin-icons"
		description="Füge Symbole zu Astro Starlight hinzu: Seitenleiste, Codeblöcke, Dateibaum."
	/>
	<LinkCard
		href="https://github.com/dlcastillop/starlight-ui-tweaks"
		title="starlight-ui-tweaks"
		description="Erweitert die Kernkomponenten der Benutzeroberfläche mit benutzerdefinierten Navigationslinks, Anzeigen, Marketing-Fußzeilen und einer übersichtlicheren Themenumschaltung."
	/>
	<LinkCard
		href="https://frostybee.github.io/starlight-tags/"
		title="starlight-tags"
		description="Füge Tags zu deinen Starlight-Dokumentationsseiten hinzu, um Inhalte zu organisieren und leichter zu finden."
	/>
	<LinkCard
		href="https://github.com/dionysuzx/starlight-copy-button"
		title="starlight-copy-button"
		description="Kopiere das gesamte Markdown der Dokumentationsseite mit einem schicken Button im Seitentitel."
	/>
	<LinkCard
		href="https://frostybee.github.io/starlight-telescope/"
		title="starlight-telescope"
		description="Navigiere schnell zu jeglichen Dokumentationsseiten mithilfe von Fuzzy-Search und Tastaturkombinationen."
	/>
	<LinkCard
		href="https://frostybee.github.io/starlight-announcement/"
		title="starlight-announcement"
		description="Füge verbesserte Ankündigungsbanner mit Varianten, Schließmöglichkeit, Zeitplanung und Seiteneinschränkung zu deiner Dokumentation hinzu."
	/>
</CardGrid>

## Community-Tools und Integrationen

import { CardGrid, LinkCard } from '@astrojs/starlight/components';

Diese Community-Tools und Integrationen können verwendet werden, um deiner Starlight-Website Funktionen hinzuzufügen.

<CardGrid>
	<LinkCard
		href="https://www.feelback.dev/blog/new-astro-starlight-integration/"
		title="FeelBack"
		description="Füge ein Nutzer-Feedback-System zu deinen Dokumentationswebsites hinzu."
	/>
	<LinkCard
		href="https://github.com/val-town/notion-to-astro"
		title="notion-to-astro"
		description="Konvertiere Notion-Exporte in Astro Starlight-Dokumentation."
	/>
	<LinkCard
		href="https://github.com/mattjennings/astro-live-code"
		title="astro-live-code"
		description="Rendere deine MDX-Codeblöcke als interaktive Komponenten."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-i18n"
		title="starlight-i18n"
		description="Visual Studio Code-Erweiterung, die bei der Übersetzung von Starlight-Seiten hilft."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-package-managers"
		title="starlight-package-managers"
		description="Zeige schnell npm-bezogene Befehle für mehrere Paketmanager an."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-showcases"
		title="starlight-showcases"
		description="Ein Set von Starlight-Komponenten zum Erstellen von Schaufensterseiten."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/generator-starlight-plugin"
		title="@hideoo/starlight-plugin"
		description="Ein Generator, um schnell Starlight-Plugins zu erstellen."
	/>
	<LinkCard
		href="https://github.com/Linkerin/starlight-to-pdf"
		title="starlight-to-pdf"
		description="Ein Kommandozeilen­werkzeug zur Konvertierung von Starlight-Websites in PDF-Dateien."
	/>
	<LinkCard
		href="https://github.com/joesaby/astro-plantuml"
		title="astro-plantuml"
		description="PlantUML-Inhalte in Markdown-Codeblöcken wiedergeben."
	/>
	<LinkCard
		href="https://github.com/joesaby/astro-mermaid"
		title="astro-mermaid"
		description="Rendere Mermaid-Inhalte in Markdown-Code-Blöcken auf der Client-Seite."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/astro-d2"
		title="astro-d2"
		description="D2 Markdown-Code-Blöcke in Diagramme umwandeln."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-links"
		title="starlight-links"
		description="Visual Studio Code-Erweiterung, die IntelliSense für Starlight Markdown- und MDX-Inhaltslinks bietet."
	/>
	<LinkCard
		href="https://docs.contentisland.net/templates/starlight/"
		title="contentisland-cli"
		description="Verbinde und synchronisiere dein Starlight-Projekt mit Content Island Headless CMS, um deine Dokumentation zu bearbeiten und zu verwalten."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-sidebar-topics-dropdown"
		title="starlight-sidebar-topics-dropdown"
		description="Teile deine Dokumentationswebsite in mehrere Abschnitte auf und wechsle zwischen ihnen mit einem Dropdown-Menü in der Seitenleiste."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-save-file-component"
		title="starlight-save-file-component"
		description="Zeig schnell einen Link zu einem Download-Asset auf deiner Starlight-Website an."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-contributor-list"
		title="starlight-contributor-list"
		description="Zeig eine Liste aller Leute an, die zu deinem Projekt beigetragen haben."
	/>
</CardGrid>


================================================
FILE: docs/src/content/docs/de/resources/showcase.mdx
================================================
---
title: Starlight Schaufenster
description: Entdecke Websites, die mit Starlight erstellt wurden!
sidebar:
  label: Website-Schaufenster
---

:::tip[Füge deine eigene hinzu!]
Hast du eine Starlight-Website gebaut?
[Eröffne einen PR](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md#showcase) und füge einen Link zu dieser Seite hinzu!
:::

## Websites

import ShowcaseSites from '~/components/showcase-sites.astro';

Starlight wird bereits in der Produktion eingesetzt. Dies sind einige der Websites im Internet:

<ShowcaseSites />

Siehe alle [öffentlichen Projekt-Repos mit Starlight auf GitHub](https://github.com/withastro/starlight/network/dependents).


================================================
FILE: docs/src/content/docs/de/resources/themes.mdx
================================================
---
title: Themes
description: Gestalte deine Dokumentation mit einem Community-Theme für Starlight
tableOfContents: false
sidebar:
  order: 2
head:
  - tag: style
    content: |
      body { --sl-content-width: 66.75rem; }
---

import ThemeGrid from '~/components/theme-grid.astro';

Ein Theme ist ein Starlight-Plugin, welches das Erscheinungsbild einer Website mit [benutzerdefiniertem CSS](/de/guides/css-and-tailwind/), [Komponenten­ersetzung](/de/guides/overriding-components/) oder anderen neuen Funktionen verändert.

## Community-Themes

Installiere ein von der Community erstelltes Theme, um das Aussehen deiner Website schnell anzupassen.

Schau dir unten eine Vorschau aller Designs an oder probier sie interaktiv auf der [Starlight Themes-Demo-Website](https://starlight-themes.netlify.app/) aus.

<ThemeGrid
	labels={{
		/** Barrierefreie Beschriftung für den Themenschalter. */
		legend: 'Vorschau',
		/** Barrierefreies Label für die dunkle Farbschema-Variante. */
		dark: 'Dunkel',
		/** Barrierefreies Label für die helle Farbschema-Variante. */
		light: 'Hell',
	}}
	themes={[
		{
			title: 'Starlight Rapide',
			description:
				'Starlight-Theme inspiriert vom Visual Studio Code Vitesse-Theme.',
			href: 'https://starlight-theme-rapide.vercel.app/',
			previews: { light: 'rapide-light.png', dark: 'rapide-dark.png' },
		},
		{
			title: 'Starlight Obsidian',
			description:
				'Starlight-Theme inspiriert vom Obsidian Publish-Websites-Theme.',
			href: 'https://fevol.github.io/starlight-theme-obsidian/',
			previews: { light: 'obsidian-light.png', dark: 'obsidian-dark.png' },
		},
		{
			title: 'Catppuccin für Starlight',
			description: 'Beruhigendes Pastelltheme für Starlight.',
			href: 'https://starlight.catppuccin.com/',
			previews: { light: 'catppuccin-light.png', dark: 'catppuccin-dark.png' },
		},
		{
			title: 'Ion',
			description: 'Ein elegantes, modernes Theme für Starlight.',
			href: 'https://louisescher.github.io/starlight-ion-theme/',
			previews: { light: 'ion-light.png', dark: 'ion-dark.png' },
		},
		{
			title: 'Starlight Black',
			description: 'Starlight-Theme inspiriert von der Shadcn-Dokumentation.',
			href: 'https://starlight-theme-black.vercel.app/',
			previews: { light: 'black-light.png', dark: 'black-dark.png' },
		},
		{
			title: 'Starlight Flexoki',
			description:
				'Ein warmes und freundliches Theme basierend auf der Flexoki-Farbpalette.',
			href: 'https://delucis.github.io/starlight-theme-flexoki/',
			previews: { light: 'flexoki-light.png', dark: 'flexoki-dark.png' },
		},
		{
			title: 'Starlight Nova',
			description: 'Ein modernes und wunderschönes Theme für Starlight.',
			href: 'https://starlight-theme-nova.pages.dev/',
			previews: { light: 'nova-light.png', dark: 'nova-dark.png' },
		},
		{
			title: 'Starlight Next.js Theme',
			description: 'Starlight-Theme inspiriert von der Next.js-Dokumentation.',
			href: 'https://starlight-theme-next.trueberryless.org/',
			previews: { light: 'nextjs-light.png', dark: 'nextjs-dark.png' },
		},
		{
			title: 'Starlight Galaxy',
			description:
				'Ein Astro Starlight-Theme, das perfekt für die Veröffentlichung von Dokumentationen und Bildungsinhalten ist.',
			href: 'https://frostybee.github.io/starlight-theme-galaxy/',
			previews: { light: 'galaxy-light.png', dark: 'galaxy-dark.png' },
		},
		{
			title: 'Starlight Page',
			description:
				'Ein intuitives, modernes Starlight-Theme mit flüssigen Einblend-Animationen.',
			href: 'https://pelagornis-page.netlify.app/',
			previews: { light: 'page-light.png', dark: 'page-dark.png' },
		},
		{
			title: 'Starlight Gruvbox',
			description: 'Retro-Groove-Theme für Starlight',
			href: 'https://starlight-theme-gruvbox.otterlord.dev/',
			previews: { light: 'gruvbox-light.png', dark: 'gruvbox-dark.png' },
		},
		{
			title: 'Starlight Six',
			description:
				'Das schlichte und moderne Astro.js Starlight-Theme von Six Technology',
			href: 'https://six-tech.github.io/Six.StarlightTheme/',
			previews: { light: 'six-light.png', dark: 'six-dark.png' },
		},
		{
			title: 'Starlight Vintage',
			description:
				'Ein Starlight Theme, welches stark vom zeitlosen Design der alten Astro-Dokumentation inspiriert ist.',
			href: 'https://starlight-theme-vintage.netlify.app/',
			previews: { light: 'vintage-light.png', dark: 'vintage-dark.png' },
		},
	]}
/>

:::tip[Füge dein eigenes Theme hinzu!]
Hast du ein Starlight-Theme gebaut?
[Eröffne einen PR](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md#themes) welcher dein Theme zu dieser Seite hinzufügt.
:::


================================================
FILE: docs/src/content/docs/environmental-impact.md
================================================
---
title: Eco-friendly docs
description: Learn how Starlight can help you build greener documentation sites and reduce your carbon footprint.
---

Estimates for the climate impact of the web industry range from between [2%][sf] and [4% of global carbon emissions][bbc], roughly equivalent to the emissions of the airline industry.
There are many complex factors in calculating the ecological impact of a website, but this guide includes a few tips for reducing the environmental footprint of your docs site.

The good news is, choosing Starlight is a great start.
According to the Website Carbon Calculator, this site is [cleaner than 98% of web pages tested][sl-carbon], producing 0.01g of CO₂ per page visit.

## Page weight

The more data a web page transfers, the more energy resources it requires.
In April 2023, the median web page required a user to download more than 2,000 KB according to [data from the HTTP Archive][http].

Starlight builds pages that are as lightweight as possible.
For example, on a first visit, a user will download less than 50 KB of compressed data — just 2.5% of the HTTP archive median.
With a good caching strategy, subsequent navigations can download as little as 10 KB.

### Images

While Starlight provides a good baseline, images you add to your docs pages can quickly increase your page weight.
Starlight uses Astro’s [optimized asset support][assets] to optimize local images in your Markdown and MDX files.

### UI components

Components built with UI frameworks like React or Vue can easily add large amounts of JavaScript to a page.
Because Starlight is built on Astro, components like this load **zero client-side JavaScript by default** thanks to [Astro Islands][islands].

### Caching

Caching is used to control how long a browser stores and reuses data it already downloaded.
A good caching strategy makes sure that a user gets new content as soon as possible when it changes, but also avoids pointlessly downloading the same content over and over when it hasn’t changed.

The most common way to configure caching is with the [`Cache-Control` HTTP header][cache].
When using Starlight, you can set a long cache time for everything in the `/_astro/` directory.
This directory contains CSS, JavaScript, and other bundled assets that can be safely cached forever, reducing unnecessary downloads:

```
Cache-Control: public, max-age=604800, immutable
```

How to configure caching depends on your web host. For example, Vercel applies this caching strategy for you with no config required, while you can set [custom headers for Netlify][ntl-headers] by adding a `public/_headers` file to your project:

```
/_astro/*
  Cache-Control: public
  Cache-Control: max-age=604800
  Cache-Control: immutable
```

[cache]: https://csswizardry.com/2019/03/cache-control-for-civilians/
[ntl-headers]: https://docs.netlify.com/routing/headers/

## Power consumption

How a web page is built can impact the power it takes to run on a user’s device.
By using minimal JavaScript, Starlight reduces the amount of processing power a user’s phone, tablet, or computer needs to load and render pages.

Be mindful when adding features like analytics tracking scripts or JavaScript-heavy content like video embeds as these can increase the page power usage.
If you need analytics, consider choosing a lightweight option like [Cabin][cabin], [Fathom][fathom], or [Plausible][plausible].
Embeds like YouTube and Vimeo videos can be improved by waiting to [load the video on user interaction][lazy-video].
Packages like [`astro-embed`][embed] can help for common services.

:::tip[Did you know?]
Parsing and compiling JavaScript is one of the most expensive tasks browsers have to do.
Compared to rendering a JPEG image of the same size, [JavaScript can take more than 30 times longer to process][cost-of-js].
:::

[cabin]: https://withcabin.com/
[fathom]: https://usefathom.com/
[plausible]: https://plausible.io/
[lazy-video]: https://web.dev/iframe-lazy-loading/
[embed]: https://www.npmjs.com/package/astro-embed
[cost-of-js]: https://medium.com/dev-channel/the-cost-of-javascript-84009f51e99e

## Hosting

Where a web page is hosted can have a big impact on how environmentally friendly your documentation site is.
Data centers and server farms can have a large ecological impact, including high electricity consumption and intensive use of water.

Choosing a host that uses renewable energy will mean lower carbon emissions for your site. The [Green Web Directory][gwb] is one tool that can help you find hosting companies.

[gwb]: https://www.thegreenwebfoundation.org/directory/

## Comparisons

Curious how other docs frameworks compare?
These tests with the [Website Carbon Calculator][wcc] compare similar pages built with different tools.

| Framework                   | CO₂ per page visit | Rating |
| --------------------------- | ------------------ | :----: |
| [Starlight][sl-carbon]      | 0.01g              |   A+   |
| [Sphinx][sx-carbon]         | 0.01g              |   A+   |
| [Read the Docs][rtd-carbon] | 0.03g              |   A+   |
| [VitePress][vp-carbon]      | 0.04g              |   A    |
| [docsify][dy-carbon]        | 0.05g              |   A    |
| [mdBook][md-carbon]         | 0.05g              |   A    |
| [Nextra][nx-carbon]         | 0.05g              |   A    |
| [MkDocs][mk-carbon]         | 0.07g              |   A    |
| [Fumadocs][fs-carbon]       | 0.07g              |   A    |
| [Docusaurus][ds-carbon]     | 0.10g              |   B    |
| [Docus][dc-carbon]          | 0.11g              |   B    |
| [GitBook][gb-carbon]        | 0.42g              |   F    |
| [Mintlify][mt-carbon]       | 0.48g              |   F    |

<small>Data collected on 7 August 2025. Click a link to see up-to-date figures.</small>

[sl-carbon]: https://www.websitecarbon.com/website/starlight-astro-build-getting-started/
[vp-carbon]: https://www.websitecarbon.com/website/vitepress-dev-guide-what-is-vitepress/
[dc-carbon]: https://www.websitecarbon.com/website/docus-dev-en-getting-started-project-structure/
[sx-carbon]: https://www.websitecarbon.com/website/sphinx-doc-org-en-master-usage-quickstart-html/
[mk-carbon]: https://www.websitecarbon.com/website/mkdocs-org-getting-started/
[md-carbon]: https://www.websitecarbon.com/website/rust-lang-github-io-mdbook/
[nx-carbon]: https://www.websitecarbon.com/website/nextra-site-docs-docs-theme-start/
[fs-carbon]: https://www.websitecarbon.com/website/fumadocs-dev-docs-ui/
[dy-carbon]: https://www.websitecarbon.com/website/docsify-js-org/
[ds-carbon]: https://www.websitecarbon.com/website/docusaurus-io-docs/
[rtd-carbon]: https://www.websitecarbon.com/website/docs-readthedocs-io-en-stable-index-html/
[gb-carbon]: https://www.websitecarbon.com/website/gitbook-com-docs/
[mt-carbon]: https://www.websitecarbon.com/website/mintlify-com-docs-quickstart/

## More resources

### Tools

- [Website Carbon Calculator][wcc]
- [GreenFrame](https://greenframe.io/)
- [Ecograder](https://ecograder.com/)
- [WebPageTest Carbon Control](https://www.webpagetest.org/carbon-control/)
- [Ecoping](https://ecoping.earth/)

### Articles and talks

- [“Building a greener web”](https://youtu.be/EfPoOt7T5lg), talk by Michelle Barker
- [“Sustainable Web Development Strategies Within An Organization”](https://www.smashingmagazine.com/2022/10/sustainable-web-development-strategies-organization/), article by Michelle Barker
- [“A sustainable web for everyone”](https://2021.stateofthebrowser.com/speakers/tom-greenwood/), talk by Tom Greenwood
- [“How Web Content Can Affect Power Usage”](https://webkit.org/blog/8970/how-web-content-can-affect-power-usage/), article by Benjamin Poulain and Simon Fraser

[sf]: https://www.sciencefocus.com/science/what-is-the-carbon-footprint-of-the-internet/
[bbc]: https://www.bbc.com/future/article/20200305-why-your-internet-habits-are-not-as-clean-as-you-think
[http]: https://httparchive.org/reports/state-of-the-web
[assets]: https://docs.astro.build/en/guides/images/
[islands]: https://docs.astro.build/en/concepts/islands/
[wcc]: https://www.websitecarbon.com/


================================================
FILE: docs/src/content/docs/es/404.md
================================================
---
title: No encontrada
template: splash
editUrl: false
lastUpdated: false
hero:
  title: '404'
  tagline: <strong>Houston, tenemos un problema.</strong> No pudimos encontrar esa página.<br>Verifica la URL o intenta usar la barra de búsqueda.
  actions:
    - text: Ir a la Home
      icon: right-arrow
      link: /es/
      variant: primary
---


================================================
FILE: docs/src/content/docs/es/components/asides.mdx
================================================
---
title: Apartados
description: Aprende a usar apartados en Starlight para mostrar información secundaria junto al contenido principal de una página.
---

import { Aside } from '@astrojs/starlight/components';

Para mostrar información secundaria junto al contenido principal de una página, usa el componente `<Aside>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<Aside slot="preview">
    Incluye información no esencial y complementaria en un `<Aside>`.
</Aside>

</Preview>

## Importación

```tsx
import { Aside } from '@astrojs/starlight/components';
```

## Uso

Muestra un apartado (también conocido como “admoniciones” o “llamadas”) usando el componente `<Aside>`.

Un `<Aside>` también puede tener un atributo opcional [`type`](#type), que controla el color, el icono y el título predeterminado del apartado.

<Preview>

````mdx
import { Aside } from '@astrojs/starlight/components';

<Aside>Contenido en un apartado.</Aside>

<Aside type="caution">Contenido de precaución.</Aside>

<Aside type="tip">

Otro tipo de contenido también es compatible en los apartados.

```js
// Por ejemplo, un fragmento de código.
```

</Aside>

<Aside type="danger">No des tu contraseña a nadie.</Aside>
````

<Fragment slot="markdoc">

````markdoc
{% aside %}
Contenido en un apartado.
{% /aside %}

{% aside type="caution" %}
Contenido de precaución.
{% /aside %}

{% aside type="tip" %}
Otro tipo de contenido también es compatible en los apartados.

```js
// Por ejemplo, un fragmento de código.
```
{% /aside %}

{% aside type="danger" %}
No des tu contraseña a nadie.
{% /aside %}
````

</Fragment>

<Fragment slot="preview">

    <Aside>Contenido en un apartado.</Aside>

    <Aside type="caution">Contenido de precaución.</Aside>

    <Aside type="tip">

    Otro tipo de contenido también es compatible en los apartados.

    ```js
    // Por ejemplo, un fragmento de código.
    ```

    </Aside>

    <Aside type="danger">No des tu contraseña a nadie.</Aside>

</Fragment>

</Preview>

Starlight también proporciona una sintaxis personalizada para renderizar apartados en Markdown y MDX como una alternativa al componente `<Aside>`.
Ver la guía [“Redacción de contenido en Markdown”](/es/guides/authoring-content/#apartados) para obtener detalles de la sintaxis personalizada.

### Usa títulos personalizados

Sobreescribe los títulos predeterminados de los apartados usando el atributo [`title`](#title).

<Preview>

```mdx 'title="Watch out!"'
import { Aside } from '@astrojs/starlight/components';

<Aside type="caution" title="¡Cuidado!">
	Una advertencia *con* un título personalizado.
</Aside>
```

<Fragment slot="markdoc">

```markdoc 'title="Watch out!"'
{% aside type="caution" title="¡Cuidado!" %}
Una advertencia *con* un título personalizado.
{% /aside %}
```

</Fragment>

<Aside slot="preview" type="caution" title="¡Cuidado!">
	Una advertencia *con* un título personalizado.
</Aside>

</Preview>

## Props de `<Aside>`

**Implementación:** [`Aside.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Aside.astro)

El componente `<Aside>` acepta las siguientes propiedades:

### `type`

**tipo:** `'note' | 'tip' | 'caution' | 'danger'`  
**por defecto:** `'note'`

El tipo de apartado a mostrar:

- apartados `note` (el predeterminado) son azules y muestran un icono de información.
- apartados `tip` son morados y muestran un icono de cohete.
- apartados `caution` son amarillos y muestran un icono de advertencia.
- apartados `danger` son rojos y muestran un icono de advertencia octogonal.

### `title`

**tipo:** `string`

El título del apartado a mostrar.
Si `title` no está establecido, se usará el título predeterminado para el `type` actual del apartado.


================================================
FILE: docs/src/content/docs/es/components/badges.mdx
================================================
---
title: Insignias
description: Aprende a usar insignias en Starlight para mostrar información adicional.
---

import { Badge } from '@astrojs/starlight/components';

Para mostrar pequeñas piezas de información, como un estado o categoría, usa el componente `<Badge>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<Badge slot="preview" text="Nuevo" />

</Preview>

## Importación

```tsx
import { Badge } from '@astrojs/starlight/components';
```

## Uso

Muestra una insignia usando el componente `<Badge>` y pasa el contenido que deseas mostrar al atributo [`text`](#text) del componente `<Badge>`.

Por defecto, la insignia usará el color de acento del tema de tu sitio.
Para usar un color de insignia integrado, establece el atributo [`variant`](#variant) en uno de los valores admitidos.

<Preview>

```mdx
import { Badge } from '@astrojs/starlight/components';

<Badge text="Nota" variant="note" />
<Badge text="Éxito" variant="success" />
<Badge text="Consejo" variant="tip" />
<Badge text="Precaución" variant="caution" />
<Badge text="Peligro" variant="danger" />
```

<Fragment slot="markdoc">

```markdoc
{% badge text="Nota" variant="note" /%}
{% badge text="Éxito" variant="success" /%}
{% badge text="Consejo" variant="tip" /%}
{% badge text="Precaución" variant="caution" /%}
{% badge text="Peligro" variant="danger" /%}
```

</Fragment>

<Fragment slot="preview">
	<Badge text="Nota" variant="note" />
	<Badge text="Éxito" variant="success" />
	<Badge text="Consejo" variant="tip" />
	<Badge text="Precaución" variant="caution" />
	<Badge text="Peligro" variant="danger" />
</Fragment>

</Preview>

### Usa diferentes tamaños

Usa el atributo [`size`](#size) para controlar el tamaño del texto de la insignia.

<Preview>

```mdx /size="\w+"/
import { Badge } from '@astrojs/starlight/components';

<Badge text="Nuevo" size="small" />
<Badge text="Nuevo y mejorado" size="medium" />
<Badge text="Nuevo, mejorado y grande" size="large" />
```

<Fragment slot="markdoc">

```markdoc /size="\w+"/
{% badge text="Nuevo" size="small" /%}
{% badge text="Nuevo y mejorado" size="medium" /%}
{% badge text="Nuevo, mejorado y grande" size="large" /%}
```

</Fragment>

<Fragment slot="preview">
	<Badge text="Nuevo" size="small" />
	<Badge text="Nuevo y mejorado" size="medium" />
	<Badge text="Nuevo, mejorado y grande" size="large" />
</Fragment>

</Preview>

### Personaliza las insignias

Personaliza las insignias usando cualquier otro atributo `<span>` como `class` o `style` con CSS personalizado.

<Preview>

```mdx "style={{ fontStyle: 'italic' }}"
import { Badge } from '@astrojs/starlight/components';

<Badge text="Personalizado" variant="success" style={{ fontStyle: 'italic' }} />
```

<Fragment slot="markdoc">

```markdoc 'style="font-style: italic;"'
{% badge text="Personalizado" variant="success" style="font-style: italic;" /%}
```

</Fragment>

<Badge
	slot="preview"
	text="Personalizado"
	variant="success"
	style={{ fontStyle: 'italic' }}
/>

</Preview>

## Props de `<Badge>`

**Implementación:** [`Badge.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Badge.astro)

El componente `<Badge>` acepta las siguientes propiedades y también cualquier [otro atributo `<span>`](https://developer.mozilla.org/es/docs/Web/HTML/Atributos_globales):

### `text`

**requerido**  
**tipo:** `string`

El contenido de texto que se mostrará en la insignia.

### `variant`

**tipo:** `'note' | 'danger' | 'success' | 'caution' | 'tip' | 'default'`  
**por defecto:** `'default'`

El color de la insignia a usar: `note` (azul), `tip` (morado), `danger` (rojo), `caution` (naranja), `success` (verde) o `default` (color de acento del tema).

### `size`

**tipo:** `'small' | 'medium' | 'large'`

Define el tamaño de la insignia a mostrar.


================================================
FILE: docs/src/content/docs/es/components/card-grids.mdx
================================================
---
title: Cuadrículas de tarjetas
description: Aprende a envolver varias tarjetas en una cuadrícula en Starlight.
sidebar:
  order: 4
---

import { Card, CardGrid, LinkCard } from '@astrojs/starlight/components';

Para envolver múltiples componentes [`<Card>`](/es/components/cards/) o [`<LinkCard>`](/es/components/link-cards/) en una cuadrícula, usa el componente `<CardGrid>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<CardGrid slot="preview">
	<Card title="Estrellas" icon="star">
		Sirius, Vega, Betelgeuse
	</Card>
	<Card title="Lunas" icon="moon">
		Io, Europa, Ganymede
	</Card>
</CardGrid>

</Preview>

## Importación

```tsx
import { CardGrid } from '@astrojs/starlight/components';
```

## Uso

### Agrupar tarjetas

Muestra varios componentes [`<Card>`](/es/components/cards/) uno al lado del otro cuando hay suficiente espacio agrupándolos con el componente `<CardGrid>`.

<Preview>

```mdx {3,10}
import { Card, CardGrid } from '@astrojs/starlight/components';

<CardGrid>
	<Card title="Revisa esto" icon="open-book">
		Contenido interesante que deseas destacar.
	</Card>
	<Card title="Otra caracaterística" icon="information">
		Más información que deseas compartir.
	</Card>
</CardGrid>
```

<Fragment slot="markdoc">

```markdoc {1,9}
{% cardgrid %}
{% card title="Revisa esto" icon="open-book" %}
Contenido interesante que deseas destacar.
{% /card %}

{% card title="Otra caracaterística" icon="information" %}
Más información que deseas compartir.
{% /card %}
{% /cardgrid %}
```

</Fragment>

<CardGrid slot="preview">
	<Card title="Revisa esto" icon="open-book">
		Contenido interesante que deseas destacar.
	</Card>
	<Card title="Otra caracaterística" icon="information">
		Más información que deseas compartir.
	</Card>
</CardGrid>

</Preview>

### Agrupar tarjetas de enlace

Muestra varios componentes [`<LinkCard>`](/es/components/link-cards/) uno al lado del otro cuando hay suficiente espacio agrupándolos con el componente `<CardGrid>`.

<Preview>

```mdx {3,9}
import { LinkCard, CardGrid } from '@astrojs/starlight/components';

<CardGrid>
	<LinkCard
		title="Creación de contenido en Markdown"
		href="/es/guides/authoring-content/"
	/>
	<LinkCard title="Componentes" href="/es/components/using-components/" />
</CardGrid>
```

<Fragment slot="markdoc">

```markdoc {1,5}
{% cardgrid %}
{% linkcard title="Creación de contenido en Markdown" href="/es/guides/authoring-content/" /%}

{% linkcard title="Componentes" href="/es/components/using-components/" /%}
{% /cardgrid %}
```

</Fragment>

<CardGrid slot="preview">
	<LinkCard
		title="Creación de contenido en Markdown"
		href="/es/guides/authoring-content/"
	/>
	<LinkCard title="Componentes" href="/es/components/using-components/" />
</CardGrid>

</Preview>

### Tarjetas escalonadas

Cambia la segunda columna de la cuadrícula verticalmente para agregar interés visual agregando el atributo [`stagger`](#stagger) al componente `<CardGrid>`.

Este atributo es útil en tu página de inicio para mostrar las características clave de tu proyecto.

<Preview>

```mdx "stagger"
import { Card, CardGrid } from '@astrojs/starlight/components';

<CardGrid stagger>
	<Card title="Revisa esto" icon="open-book">
		Contenido interesante que deseas destacar.
	</Card>
	<Card title="Otra característica" icon="information">
		Más información que deseas compartir.
	</Card>
</CardGrid>
```

<Fragment slot="markdoc">

```markdoc "stagger=true"
{% cardgrid stagger=true %}
{% card title="Revisa esto" icon="open-book" %}
Contenido interesante que deseas destacar.
{% /card %}

{% card title="Otra característica" icon="information" %}
Más información que deseas compartir.
{% /card %}
{% /cardgrid %}
```

</Fragment>

<CardGrid slot="preview" stagger>
	<Card title="Revisa esto" icon="open-book">
		Contenido interesante que deseas destacar.
	</Card>
	<Card title="Otra característica" icon="information">
		Más información que deseas compartir.
	</Card>
</CardGrid>

</Preview>

## Props de `<CardGrid>`

**Implementación:** [`CardGrid.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/CardGrid.astro)

El componente `<CardGrid>` acepta las siguientes propiedades:

### `stagger`

**tipo:** `boolean`

Define si se deben escalonar las tarjetas en la cuadrícula o no.


================================================
FILE: docs/src/content/docs/es/components/cards.mdx
================================================
---
title: Tarjetas
description: Aprende a usar tarjetas en Starlight para mostrar contenido en una caja.
sidebar:
  order: 2
---

import { Card } from '@astrojs/starlight/components';

Para mostrar contenido en una caja que coincida con los estilos de Starlight, usa el componente `<Card>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<Card slot="preview" title="Lunas" icon="moon">
	Io, Europa, Ganymede
</Card>

</Preview>

## Importación

```tsx
import { Card } from '@astrojs/starlight/components';
```

## Uso

Muestra una tarjeta usando el componente `<Card>` y proporciona un [`title`](#title) para la tarjeta.

<Preview>

```mdx
import { Card } from '@astrojs/starlight/components';

<Card title="Revisa esto">Contenido interesante que deseas destacar.</Card>
```

<Fragment slot="markdoc">

```markdoc
{% card title="Revisa esto" %}
Contenido interesante que deseas destacar.
{% /card %}
```

</Fragment>

<Card slot="preview" title="Revisa esto">
	Contenido interesante que deseas destacar.
</Card>

</Preview>

### Agregar iconos a las tarjetas

Incluye un icono en una tarjeta usando el atributo [`icon`](#icon) establecido en el nombre de [uno de los iconos integrados de Starlight](/es/reference/icons/#todos-los-iconos).

<Preview>

```mdx 'icon="star"'
import { Card } from '@astrojs/starlight/components';

<Card title="Estrellas" icon="star">
	Sirius, Vega, Betelgeuse
</Card>
```

<Fragment slot="markdoc">

```markdoc 'icon="star"'
{% card title="Estrellas" icon="star" %}
Sirius, Vega, Betelgeuse
{% /card %}
```

</Fragment>

<Card slot="preview" title="Estrellas" icon="star">
	Sirius, Vega, Betelgeuse
</Card>

</Preview>

### Agrupar tarjetas

Muestra varias tarjetas una al lado de la otra cuando hay suficiente espacio agrupándolas con el componente [`<CardGrid>`](/es/components/card-grids/).
Consulta la guía [“Agrupar tarjetas”](/es/components/card-grids/#agrupar-tarjetas) para un ejemplo.

## Props de `<Card>`

**Implementación:** [`Card.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Card.astro)

El componente `<Card>` acepta las siguientes propiedades:

### `title`

**requerido**  
**tipo:** `string`

El título de la tarjeta a mostrar.

### `icon`

**tipo:** `string`

Una tarjeta puede incluir un atributo `icon` establecido en el nombre de [uno de los iconos integrados de Starlight](/es/reference/icons/#todos-los-iconos).


================================================
FILE: docs/src/content/docs/es/components/code.mdx
================================================
---
title: Código
description: Aprende a mostrar código con resaltado de sintaxis en Starlight sin bloques de código de Markdown.
---

import { Code } from '@astrojs/starlight/components';

El componente `<Code>` muestra código con resaltado de sintaxis.
Es útil cuando no es posible usar un [bloque de código de Markdown](/es/guides/authoring-content/#bloques-de-código), por ejemplo, para mostrar datos provenientes de fuentes externas como archivos, bases de datos o APIs.

import Preview from '~/components/component-preview.astro';

<Preview>

<Code
	slot="preview"
	code={`## Bienvenido

¡Hola desde **el espacio**!`}
lang="md"
title="example.md"
ins={3}
/>

</Preview>

## Importación

```tsx
import { Code } from '@astrojs/starlight/components';
```

## Uso

Usa el componente `<Code>` para renderizar código con resaltado de sintaxis, por ejemplo, al mostrar código obtenido de fuentes externas.

Ver la [documentación de Expressive Code “Componente de código”](https://expressive-code.com/key-features/code-component/) para obtener detalles completos sobre cómo usar el componente `<Code>` y la lista de props disponibles.

<Preview>

```mdx
import { Code } from '@astrojs/starlight/components';

export const exampleCode = `console.log('¡Esto podría provenir de un archivo o CMS!');`;
export const fileName = 'example.js';
export const highlights = ['archivo', 'CMS'];

<Code code={exampleCode} lang="js" title={fileName} mark={highlights} />
```

<Fragment slot="markdoc">

```markdoc
{% code
   code="console.log('¡Esto podría provenir de un archivo o CMS!');"
   lang="js"
   title="example.js"
   meta="'archivo' 'CMS'" /%}
```

</Fragment>

export const exampleCode = `console.log('¡Esto podría provenir de un archivo o CMS!');`;
export const fileName = 'example.js';
export const highlights = ['archivo', 'CMS'];

<Code
	slot="preview"
	code={exampleCode}
	lang="js"
	title={fileName}
	mark={highlights}
/>

</Preview>

### Mostrar código importado

En los archivos MDX y componentes de Astro, usa [el sufijo de importación `?raw` de Vite](https://es.vite.dev/guide/assets#importar-recursos-como-cadenas-de-texto) para importar cualquier archivo de código como un string.
Puedes pasar este string importado al componente `<Code>` para incluirlo en tu página.

<Preview>

```mdx "?raw"
# src/content/docs/example.mdx

import { Code } from '@astrojs/starlight/components';
import importedCode from '/tsconfig.json?raw';

<Code code={importedCode} lang="json" title="tsconfig.json" />
```

import importedCode from '../../../../../../examples/basics/tsconfig.json?raw';

<Code slot="preview" code={importedCode} lang="json" title="tsconfig.json" />

</Preview>

## Props de `<Code>`

**Implementación:** [`Code.astro`](https://github.com/expressive-code/expressive-code/blob/main/packages/astro-expressive-code/components/Code.astro)

El componente `<Code>` acepta todas las propiedades documentadas en la [documentación de Expressive Code “Componente de código”](https://expressive-code.com/key-features/code-component/#available-props).


================================================
FILE: docs/src/content/docs/es/components/file-tree.mdx
================================================
---
title: Árbol de archivos
description: Aprende a mostrar la estructura de un directorio con iconos de archivo y subdirectorios colapsables en Starlight.
---

import { FileTree } from '@astrojs/starlight/components';

Para mostrar la estructura de un directorio con iconos de archivo y subdirectorios colapsables, usa el componente `<FileTree>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<FileTree slot="preview">

- astro.config.mjs un archivo **importante**
- package.json
- README.md
- src
  - components
    - **Header.astro**
  - …
- pages/

</FileTree>

</Preview>

## Importación

```tsx
import { FileTree } from '@astrojs/starlight/components';
```

## Uso

Muestra un árbol de archivos con iconos de archivo y subdirectorios colapsables usando el componente `<FileTree>`.

Especifica la estructura de tus archivos y directorios con una [lista Markdown no ordenada](https://www.markdownguide.org/basic-syntax/#unordered-lists) dentro de `<FileTree>`.
Crea un subdirectorio usando una lista anidada o agrega una `/` al final de un elemento de la lista para renderizarlo como un directorio sin contenido específico.

<Preview>

```mdx
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- astro.config.mjs
- package.json
- src
  - components
    - Header.astro
    - Title.astro
  - pages/

</FileTree>
```

<Fragment slot="markdoc">

```markdoc
{% filetree %}
- astro.config.mjs
- package.json
- src
  - components
    - Header.astro
    - Title.astro
  - pages/
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- astro.config.mjs
- package.json
- src
  - components
    - Header.astro
    - Title.astro
  - pages/

</FileTree>

</Preview>

### Resaltar entradas

Haz que un archivo o directorio destaque haciendo que su nombre esté en negrita, por ejemplo, `**README.md**`.

<Preview>

```mdx {7}
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src
  - components
    - **Header.astro**
    - Title.astro

</FileTree>
```

<Fragment slot="markdoc">

```markdoc {4}
{% filetree %}
- src
  - components
    - **Header.astro**
    - Title.astro
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- src
  - components
    - **Header.astro**
    - Title.astro

</FileTree>

</Preview>

### Agregar comentarios

Agrega un comentario a un archivo o directorio agregando más texto después del nombre.
El formateo de Markdown en línea como negritas e itálicas es compatible en los comentarios.

<Preview>

```mdx {7}
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src
  - components
    - Header.astro un archivo **importante**
    - Title.astro

</FileTree>
```

<Fragment slot="markdoc">

```markdoc {4}
{% filetree %}
- src
  - components
    - Header.astro un archivo **importante**
    - Title.astro
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- src
  - components
    - Header.astro un archivo **importante**
    - Title.astro

</FileTree>

</Preview>

### Agregar marcadores de posición

Agrega archivos y directorios de marcador de posición usando `...` o `…` como nombre.
Esto puede ser útil para indicar a un lector que se espera que una carpeta contenga más elementos sin especificarlos todos explícitamente.

<Preview>

```mdx {8}
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src
  - components
    - Header.astro
    - …

</FileTree>
```

<Fragment slot="markdoc">

```markdoc {5}
{% filetree %}
- src
  - components
    - Header.astro
    - …
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- src
  - components
    - Header.astro
    - …

</FileTree>

</Preview>

## Props de `<FileTree>`

**Implementación:** [`FileTree.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/FileTree.astro)

El componente `<FileTree>` no acepta ninguna propiedad.


================================================
FILE: docs/src/content/docs/es/components/icons.mdx
================================================
---
title: Iconos
description: Aprende a mostrar iconos en Starlight.
---

import { Icon } from '@astrojs/starlight/components';

Para mostrar los iconos del [conjunto de iconos integrados](/es/reference/icons/#todos-los-iconos) de Starlight, usa el componente `<Icon>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<Icon
	slot="preview"
	name="open-book"
	color="var(--sl-color-text-accent)"
	size="4rem"
/>

</Preview>

## Importación

```tsx
import { Icon } from '@astrojs/starlight/components';
```

## Uso

Muestra un icono usando el componente `<Icon>`.
Un icono requiere un [`name`](#name) establecido en [uno de los iconos integrados de Starlight](/es/reference/icons/#todos-los-iconos) y opcionalmente puede incluir un [`label`](#label) para proporcionar contexto a los lectores de pantalla.

<Preview>

```mdx
import { Icon } from '@astrojs/starlight/components';

<Icon name="star" />
<Icon name="starlight" label="El logo de Starlight" />
```

<Fragment slot="markdoc">

```markdoc
{% icon name="star" /%}
{% icon name="starlight" label="El logo de Starlight" /%}
```

</Fragment>

<Fragment slot="preview">
	<Icon name="star" />
	<Icon name="starlight" label="El logo de Starlight" />
</Fragment>

</Preview>

### Personalizar iconos

Los atributos [`size`](#size) y [`color`](#color) se pueden usar para ajustar la apariencia del icono utilizando unidades CSS y valores de color.
El atributo [`class`](#class) se puede usar para agregar clases CSS personalizadas al icono.

<Preview>

```mdx
import { Icon } from '@astrojs/starlight/components';

<Icon name="star" color="goldenrod" size="2rem" />
<Icon name="rocket" color="var(--sl-color-text-accent)" />
```

<Fragment slot="markdoc">

```markdoc
{% icon name="star" color="goldenrod" size="2rem" /%}
{% icon name="rocket" color="var(--sl-color-text-accent)" /%}
```

</Fragment>

<Fragment slot="preview">
	<Icon name="star" color="goldenrod" size="2rem" />
	<Icon name="rocket" color="var(--sl-color-text-accent)" />
</Fragment>

</Preview>

## Props de `<Icon>`

**Implementación:** [`Icon.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Icon.astro)

El componente `<Icon>` acepta las siguientes propiedades:

### `name`

**requerido**  
**tipo:** `string`

El nombre del icono a mostrar establecido en [uno de los iconos integrados de Starlight](/es/reference/icons/#todos-los-iconos).

### `label`

**tipo:** `string`

Una etiqueta opcional para proporcionar contexto a las tecnologías de asistencia, como los lectores de pantalla.

Cuando no se establece `label`, el icono estará completamente oculto para las tecnologías de asistencia.
En este caso, asegúrate de que el contexto siga siendo comprensible sin el icono.
Por ejemplo, un enlace que contenga solo el icono **debe** incluir el atributo `label` para ser accesible, pero si un enlace contiene texto y el icono es puramente decorativo, omitir el `label` puede tener sentido.

### `size`

**tipo:** `string`

El tamaño de un icono usando unidades CSS.

### `color`

**tipo:** `string`

El color de un icono utilizando un valor de color CSS.

### `class`

**tipo:** `string`

Personaliza las clases CSS para agregar al icono.


================================================
FILE: docs/src/content/docs/es/components/link-buttons.mdx
================================================
---
title: Botones de enlace
description: Aprende a crear botones de enlace en Starlight para enlaces de llamada a la acción visualmente distintos.
---

import { LinkButton } from '@astrojs/starlight/components';

Para mostrar enlaces de llamada a la acción visualmente distintos, usa el componente `<LinkButton>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<LinkButton slot="preview" href="/es/getting-started/">
	Lee la documentación
</LinkButton>

</Preview>

## Importación

```tsx
import { LinkButton } from '@astrojs/starlight/components';
```

## Uso

Usa el componente `<LinkButton>` para mostrar un enlace de llamada a la acción visualmente distinto.
Un botón de enlace es útil para dirigir a los usuarios al contenido más relevante o accionable y se usa a menudo en páginas de destino.

Un `<LinkButton>` requiere un atributo [`href`](#href).
Opcionalmente, personaliza la apariencia del botón de enlace usando el atributo [`variant`](#variant), que se puede establecer en `primary` (el valor predeterminado), `secondary` o `minimal`.

<Preview>

```mdx
import { LinkButton } from '@astrojs/starlight/components';

<LinkButton href="/es/getting-started/">Comienza</LinkButton>
<LinkButton href="/es/reference/configuration/" variant="secondary">
	Referencia de configuración
</LinkButton>
```

<Fragment slot="markdoc">

```markdoc
{% linkbutton href="/es/getting-started/" %}Comienza{% /linkbutton %}

{% linkbutton href="/es/reference/configuration/" variant="secondary" %}
Referencia de configuración
{% /linkbutton %}
```

</Fragment>

<Fragment slot="preview">
	<LinkButton href="/es/getting-started/">Comienza</LinkButton>
	<LinkButton href="/es/reference/configuration/" variant="secondary">
		Referencia de configuración
	</LinkButton>
</Fragment>

</Preview>

### Agregar iconos a los botones de enlace

Incluye un icono en un botón de enlace usando el atributo [`icon`](#icon) establecido en el nombre de [uno de los iconos integrados de Starlight](/es/reference/icons/#todos-los-iconos).

El atributo [`iconPlacement`](#iconplacement) se puede usar para colocar el icono antes del texto estableciéndolo en `start` (el valor predeterminado es `end`).

<Preview>

```mdx {6-7}
import { LinkButton } from '@astrojs/starlight/components';

<LinkButton
	href="https://docs.astro.build"
	variant="secondary"
	icon="external"
	iconPlacement="start"
>
	Relacionado: Astro
</LinkButton>
```

<Fragment slot="markdoc">

```markdoc {4-5}
{% linkbutton
   href="https://docs.astro.build"
	 variant="secondary"
	 icon="external"
	 iconPlacement="start" %}
Relacionado: Astro
{% /linkbutton %}
```

</Fragment>

<LinkButton
	slot="preview"
	href="https://docs.astro.build"
	variant="secondary"
	icon="external"
	iconPlacement="start"
>
	Relacionado: Astro
</LinkButton>

</Preview>

## Props de `<LinkButton>`

**Implementación:** [`LinkButton.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/LinkButton.astro)

El componente `<LinkButton>` acepta las siguientes props y también cualquier [otro atributo `<a>`](https://developer.mozilla.org/es/docs/Web/HTML/Element/a):

### `href`

**requerido**  
**tipo:** `string`

El URL al que apunta el botón de enlace.

### `variant`

**tipo:** `'primary' | 'secondary' | 'minimal'`  
**por defecto:** `'primary'`

La apariencia del botón de enlace.
Establece `primary` para un enlace de llamada a la acción prominente que usa el color de acento del tema, `secondary` para un enlace menos prominente o `minimal` para un enlace con un estilo mínimo.

### `icon`

**tipo:** `string`

Un botón de enlace puede incluir un atributo `icon` establecido en el nombre de [uno de los iconos integrados de Starlight](/es/reference/icons/#todos-los-iconos).

### `iconPlacement`

**tipo:** `'start' | 'end'`  
**por defecto:** `'end'`

Determina la ubicación del icono en relación con el texto del botón de enlace.


================================================
FILE: docs/src/content/docs/es/components/link-cards.mdx
================================================
---
title: Tarjetas de enlace
description: Aprende a mostrar enlaces de forma destacada como tarjetas en Starlight.
sidebar:
  order: 3
---

import { LinkCard } from '@astrojs/starlight/components';

Para mostrar enlaces a diferentes páginas de forma destacada, utiliza el componente `<LinkCard>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<LinkCard
	slot="preview"
	title="Personalización de Starlight"
	description="Aprende a personalizar tu sitio de Starlight con estilos personalizados, fuentes y más."
	href="/es/guides/customization/"
/>

</Preview>

## Importación

```tsx
import { LinkCard } from '@astrojs/starlight/components';
```

## Uso

Mostrar un enlace de forma destacada utilizando el componente `<LinkCard>`.
Cada `<LinkCard>` requiere un atributo [`title`](#title) y un atributo [`href`](#href).

<Preview>

```mdx
import { LinkCard } from '@astrojs/starlight/components';

<LinkCard
	title="Creación de contenido en Markdown"
	href="/es/guides/authoring-content/"
/>
```

<Fragment slot="markdoc">

```markdoc
{% linkcard title="Creación de contenido en Markdown" href="/es/guides/authoring-content/" /%}
```

</Fragment>

<LinkCard
	slot="preview"
	title="Creación de contenido en Markdown"
	href="/es/guides/authoring-content/"
/>

</Preview>

### Agregar una descripción de enlace

Agrega una descripción breve a una tarjeta de enlace utilizando el atributo [`description`](#description).

<Preview>

```mdx {6}
import { LinkCard } from '@astrojs/starlight/components';

<LinkCard
	title="Internacionalización"
	href="/es/guides/i18n/"
	description="Configura Starlight para admitir varios idiomas."
/>
```

<Fragment slot="markdoc">

```markdoc {4}
{% linkcard
   title="Internacionalización"
	 href="/es/guides/i18n/"
	 description="Configura Starlight para admitir varios idiomas." /%}
```

</Fragment>

<LinkCard
	slot="preview"
	title="Internacionalización"
	href="/es/guides/i18n/"
	description="Configura Starlight para admitir varios idiomas."
/>

</Preview>

### Agrupar tarjetas de enlace

Muestra varias tarjetas de enlace una al lado de la otra cuando hay suficiente espacio agrupándolas con el componente [`<CardGrid>`](/es/components/card-grids/).
Ve la guía [“Agrupar tarjetas de enlace”](/es/components/card-grids/#agrupar-tarjetas) para un ejemplo.

## Props de `<LinkCard>`

**Implementación:** [`LinkCard.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/LinkCard.astro)

El componente `<LinkCard>` acepta las siguientes propiedades, así como todos los demás atributos de los elementos [`<a>`](https://developer.mozilla.org/es/docs/Web/HTML/Element/a):

### `title`

**requerido**  
**tipo:** `string`

El título de la tarjeta de enlace a mostrar.

### `href`

**requerido**  
**tipo:** `string`

El URL al que enlazar cuando se interactúa con la tarjeta.

### `description`

**tipo:** `string`

Una descripción opcional para mostrar debajo del título.


================================================
FILE: docs/src/content/docs/es/components/steps.mdx
================================================
---
title: Pasos
description: Aprende como dar estilo a listas numeradas de tareas para crear guías paso a paso en Starlight.
---

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

Para estilar una lista numerada de tareas para crear guías paso a paso, utiliza el componente `<Steps>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<Steps slot="preview">

1. Crea un nuevo proyecto de Starlight:

   <Tabs syncKey="pkg">

   <TabItem label="npm">

   ```sh
   npm create astro@latest -- --template starlight
   ```

   </TabItem>

   <TabItem label="pnpm">

   ```sh
   pnpm create astro --template starlight
   ```

   </TabItem>

   <TabItem label="Yarn">

   ```sh
   yarn create astro --template starlight
   ```

   </TabItem>

   </Tabs>

2. Escribe tu primera página de documentación.

</Steps>

</Preview>

## Importación

```tsx
import { Steps } from '@astrojs/starlight/components';
```

## Uso

Usa el componente `<Steps>` para estilar listas numeradas de tareas.
Esto es útil para guías paso a paso más complejas donde cada paso necesita ser claramente resaltado.

Envuelve `<Steps>` alrededor de una lista ordenada de Markdown estándar.
Toda la sintaxis de Markdown estándar es aplicable dentro de `<Steps>`.

<Preview>

````mdx
import { Steps } from '@astrojs/starlight/components';

<Steps>

1. Importa el componente en tu archivo MDX:

   ```js
   import { Steps } from '@astrojs/starlight/components';
   ```

2. Envuelve `<Steps>` alrededor de tus elementos de lista ordenada.

</Steps>
````

<Fragment slot="markdoc">

````markdoc
{% steps %}

1. Importa el componente en tu archivo MDX:

   ```js
   import { Steps } from '@astrojs/starlight/components';
   ```

2. Envuelve `<Steps>` alrededor de tus elementos de lista ordenada.

{% /steps %}
````

</Fragment>

<Steps slot="preview">

1. Importa el componente en tu archivo MDX:

   ```js
   import { Steps } from '@astrojs/starlight/components';
   ```

2. Envuelve `<Steps>` alrededor de tus elementos de lista ordenada.

</Steps>

</Preview>

## Props de `<Steps>`

**Implementación:** [`Steps.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Steps.astro)

El componente `<Steps>` no acepta ninguna propiedad.


================================================
FILE: docs/src/content/docs/es/components/tabs.mdx
================================================
---
title: Pestañas
description: Aprende a crear interfaces con pestañas en Starlight para agrupar información equivalente.
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

Para crear una interfaz con pestañas usa los componentes `<Tabs>` y `<TabItem>`.
Las pestañas son útiles para agrupar información equivalente donde un usuario solo necesita ver una de varias opciones.

import Preview from '~/components/component-preview.astro';

<Preview>

<Tabs slot="preview">
	<TabItem label="Estrellas">Sirius, Vega, Betelgeuse</TabItem>
	<TabItem label="Lunas">Io, Europa, Ganymede</TabItem>
</Tabs>

</Preview>

## Importación

```tsx
import { Tabs, TabItem } from '@astrojs/starlight/components';
```

## Uso

Muestra una interfaz con pestañas usando los componentes `<Tabs>` y `<TabItem>`.
Cada `<TabItem>` debe tener una [`label`](#label) para mostrar a los usuarios.

<Preview>

```mdx
import { Tabs, TabItem } from '@astrojs/starlight/components';

<Tabs>
	<TabItem label="Estrellas">Sirius, Vega, Betelgeuse</TabItem>
	<TabItem label="Lunas">Io, Europa, Ganymede</TabItem>
</Tabs>
```

<Fragment slot="markdoc">

```markdoc
{% tabs %}
{% tabitem label="Estrellas" %}
Sirius, Vega, Betelgeuse
{% /tabitem %}

{% tabitem label="Lunas" %}
Io, Europa, Ganymede
{% /tabitem %}
{% /tabs %}
```

</Fragment>

<Tabs slot="preview">
	<TabItem label="Estrellas">Sirius, Vega, Betelgeuse</TabItem>
	<TabItem label="Lunas">Io, Europa, Ganymede</TabItem>
</Tabs>

</Preview>

### Sincronizar pestañas

Mantén sincronizados varios grupos de pestañas agregando el atributo [`syncKey`](#synckey).

Todos las `<Tabs>` en una página con el mismo valor de `syncKey` mostrarán la misma etiqueta activa.
Esto permite que el lector elija una vez (por ejemplo, su sistema operativo o administrador de paquetes) y vea su elección persistida a través de las navegaciones de página.

Para sincronizar pestañas relacionadas, agrega una propiedad `syncKey` idéntica a cada componente `<Tabs>` y asegúrate de que todos usen las mismas etiquetas `<TabItem>`:

<Preview>

```mdx 'syncKey="constelaciones"'
import { Tabs, TabItem } from '@astrojs/starlight/components';

_Algunas estrellas:_

<Tabs syncKey="constelaciones">
	<TabItem label="Orion">Bellatrix, Rigel, Betelgeuse</TabItem>
	<TabItem label="Gemini">Pollux, Castor A, Castor B</TabItem>
</Tabs>

_Algunos exoplanetas:_

<Tabs syncKey="constelaciones">
	<TabItem label="Orion">HD 34445 b, Gliese 179 b, Wasp-82 b</TabItem>
	<TabItem label="Gemini">Pollux b, HAT-P-24b, HD 50554 b</TabItem>
</Tabs>
```

<Fragment slot="markdoc">

```markdoc 'syncKey="constelaciones"'
_Algunas estrellas:_

{% tabs syncKey="constelaciones" %}
{% tabitem label="Orion" %}
Bellatrix, Rigel, Betelgeuse
{% /tabitem %}

{% tabitem label="Gemini" %}
Pollux, Castor A, Castor B
{% /tabitem %}
{% /tabs %}

_Algunos exoplanetas:_

{% tabs syncKey="constelaciones" %}
{% tabitem label="Orion" %}
HD 34445 b, Gliese 179 b, Wasp-82 b
{% /tabitem %}

{% tabitem label="Gemini" %}
Pollux b, HAT-P-24b, HD 50554 b
{% /tabitem %}
{% /tabs %}
```

</Fragment>

<Fragment slot="preview">

_Algunas estrellas:_

<Tabs syncKey="constelaciones">
	<TabItem label="Orion">Bellatrix, Rigel, Betelgeuse</TabItem>
	<TabItem label="Gemini">Pollux, Castor A, Castor B</TabItem>
</Tabs>

_Algunos exoplanetas:_

<Tabs syncKey="constelaciones">
	<TabItem label="Orion">HD 34445 b, Gliese 179 b, Wasp-82 b</TabItem>
	<TabItem label="Gemini">Pollux b, HAT-P-24b, HD 50554 b</TabItem>
</Tabs>

</Fragment>

</Preview>

### Agregar iconos a las pestañas

Incluye un icono en un elemento de pestaña usando el atributo [`icon`](#icon) establecido en el nombre de [uno de los iconos integrados de Starlight](/es/reference/icons/#todos-los-iconos) para mostrar un icono junto a la etiqueta.

<Preview>

```mdx /icon="\w+"/
import { Tabs, TabItem } from '@astrojs/starlight/components';

<Tabs>
	<TabItem label="Estrellas" icon="star">
		Sirius, Vega, Betelgeuse
	</TabItem>
	<TabItem label="Lunas" icon="moon">
		Io, Europa, Ganymede
	</TabItem>
</Tabs>
```

<Fragment slot="markdoc">

```markdoc /icon="\w+"/
{% tabs %}
{% tabitem label="Estrellas" icon="star" %}
Sirius, Vega, Betelgeuse
{% /tabitem %}

{% tabitem label="Lunas" icon="moon" %}
Io, Europa, Ganymede
{% /tabitem %}
{% /tabs %}
```

</Fragment>

<Tabs slot="preview">
	<TabItem label="Estrellas" icon="star">
		Sirius, Vega, Betelgeuse
	</TabItem>
	<TabItem label="Lunas" icon="moon">
		Io, Europa, Ganymede
	</TabItem>
</Tabs>

</Preview>

## Props de `<Tabs>`

**Implementación:** [`Tabs.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Tabs.astro)

El componente `<Tabs>` agrupa varios componentes `<TabItem>` y acepta las siguientes propiedades:

### `syncKey`

**tipo:** `string`

Una clave utilizada para mantener sincronizados varios grupos de pestañas en varias páginas.

## Props de `<TabItem>`

**Implementación:** [`TabItem.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/TabItem.astro)

Un conjunto de pestañas está compuesto por elementos de pestaña, cada uno con las siguientes propiedades:

### `label`

**requerido**  
**tipo:** `string`

Un elemento de pestaña debe incluir un atributo `label` establecido en el texto que se mostrará en la pestaña.

### `icon`

**tipo:** `string`

Cada elemento de pestaña puede incluir un atributo `icon` establecido en el nombre de [uno de los iconos integrados de Starlight](/es/reference/icons/#todos-los-iconos) para mostrar un icono junto a la etiqueta.


================================================
FILE: docs/src/content/docs/es/components/using-components.mdx
================================================
---
title: Usando componentes
description: Usando componentes en MDX y Markdoc con Starlight.
sidebar:
  order: 1
---

Los componentes te permiten reutilizar fácilmente un fragmento de UI o estilos de manera consistente.
Los ejemplos pueden incluir una tarjeta de enlace o un incrustado de YouTube.
Starlight admite el uso de componentes en archivos [MDX](https://mdxjs.com/) y [Markdoc](https://markdoc.dev/) y proporciona algunos componentes comunes para que los uses.

[Conoce más sobre la construcción de componentes en la documentación de Astro](https://docs.astro.build/es/core-concepts/astro-components/).

## Usando un componente en MDX

Puedes usar un componente importándolo en tu archivo MDX y luego renderizándolo como una etiqueta JSX.
Estos se ven como etiquetas HTML pero comienzan con una letra mayúscula que coincide con el nombre en tu declaración de `import`:

```mdx
---
# src/content/docs/example.mdx
title: Bienvenido a mi documentación
---

import { Icon } from '@astrojs/starlight/components';
import CustomCard from '../../components/CustomCard.astro';

<Icon name="open-book" />

<CustomCard>
	Los componentes también pueden contener **contenido anidado**.
</CustomCard>
```

Debido a que Starlight está impulsado por Astro, puedes agregar soporte para componentes construidos con cualquier [framework de UI compatible (React, Preact, Svelte, Vue, Solid y Alpine)](https://docs.astro.build/es/core-concepts/framework-components/) en tus archivos MDX.
{/* TODO: Actualizar esta liga cuando los docs en español de Astro incluyan el fragmento de la versión en inglés. */}
Aprende más sobre [usar componentes en MDX](https://docs.astro.build/en/guides/integrations-guide/mdx/#using-components-in-mdx) en la documentación de Astro.

## Usando un componente en Markdoc

Agrega soporte para la creación de contenido en Markdoc siguiendo nuestra [guía de configuración de Markdoc](/es/guides/authoring-content/#markdoc).

Usando el preset de Starlight Markdoc, puedes usar los componentes incorporados de Starlight con la sintaxis de etiqueta de Markdoc `{% %}`.
A diferencia de MDX, los componentes en Markdoc no necesitan ser importados.
El siguiente ejemplo renderiza el [componente de tarjeta](/es/components/cards/) de Starlight en un archivo Markdoc:

```markdoc
---
# src/content/docs/example.mdoc
title: Bienvenido a mi documentación
---

{% card title="Estrellas" icon="star" %}
Sirius, Vega, Betelgeuse
{% /card %}
```

Ver la [documentación de integración de Astro Markdoc](https://docs.astro.build/es/guides/integrations-guide/markdoc/#render-components) para más información sobre cómo usar componentes en archivos Markdoc.

## Componentes incorporados

Starlight proporcona componentes integrados para casos de uso comunes en la documentación.
Estos componentes están disponibles en el paquete `@astrojs/starlight/components` en archivos MDX y en el [preset de Starlight Markdoc](/es/guides/authoring-content/#markdoc) en archivos Markdoc.

Ve la barra lateral para una lista de componentes disponibles y cómo usarlos.

## Compatibilidad con los estilos de Starlight

Starlight aplica estilos predeterminados a tu contenido de Markdown, por ejemplo, agregando márgenes entre elementos.
Si estos estilos entran en conflicto con la apariencia de tu componente, establece la clase `not-content` en tu componente para deshabilitarlos.

```astro 'class="not-content"'
---
// src/components/Example.astro
---

<div class="not-content">
	<p>No se ve afectado por los estilos predeterminados de Starlight.</p>
</div>
```

## Props de componentes

Usa el tipo [`ComponentProps`](https://docs.astro.build/es/guides/typescript/#tipo-componentprops) de `astro/types` para hacer referencia a las `Props` aceptadas por un componente incluso si no están exportadas por el componente en sí.
Esto puede ser util al envolver o extender un componente existente.

El siguiente ejemplo usa `ComponentProps` para obtener el tipo de las props aceptadas por el componente `Icon` incorporado de Starlight:

```astro
---
// src/components/Example.astro
import type { ComponentProps } from 'astro/types';
import { Icon } from '@astrojs/starlight/icon';

type IconProps = ComponentProps<typeof Icon>;
---
```


================================================
FILE: docs/src/content/docs/es/environmental-impact.md
================================================
---
title: Documentación ecológica
description: Aprende cómo Starlight puede ayudarte a construir sitios de documentación más ecológicos y reducir tu huella de carbono.
---

Las estimaciones del impacto climático de la industria web oscilan entre el [2%][sf] y el [4% de las emisiones globales de carbono][bbc], equivalente aproximadamente a las emisiones de la industria de la aviación. Hay muchos factores complejos en el cálculo del impacto ecológico de un sitio web, pero esta guía incluye algunos consejos para reducir la huella ambiental de tu sitio de documentación.

La buena noticia es que elegir Starlight es un excelente comienzo. Según el Website Carbon Calculator, este sitio es [más limpio que el 99% de las páginas web analizadas][sl-carbon], produciendo 0.01g de CO₂ por visita a la página.

## Peso de la página

Cuanto más datos transfiera una página web, más recursos energéticos requerirá. En abril de 2023, la mediana de una página web requería que un usuario descargara más de 2.000 KB, según [los datos del HTTP Archive][http].

Starlight construye páginas que son lo más livianas posible. Por ejemplo, en una primera visita, un usuario descargará menos de 50 KB de datos comprimidos, lo que representa solo el 2.5% de la mediana del archivo HTTP. Con una buena estrategia de almacenamiento en caché, las navegaciones posteriores pueden descargar tan solo 10 KB.

### Imágenes

Si bien Starlight proporciona una buena base, las imágenes que agregas a tus páginas de documentación pueden aumentar rápidamente el peso de la página. Starlight utiliza el [soporte de assets optimizados][assets] de Astro para optimizar las imágenes locales en tus archivos Markdown y MDX.

### Componentes UI

Los componentes construidos con frameworks UI como React o Vue pueden añadir fácilmente grandes cantidades de JavaScript a una página. Sin embargo, debido a que Starlight está construido sobre Astro, los componentes como estos no cargan **ningún JavaScript del lado del cliente de forma predeterminada**, gracias a las [islas de Astro][islands].

### Caché

La caché se utiliza para controlar cuánto tiempo un navegador almacena y reutiliza los datos que ha estado descargando. Una buena estrategia de caché asegura que un usuario obtenga nuevo contenido tan pronto como sea posible cuando está cambiando, pero también evita descargar innecesariamente el mismo contenido una y otra vez cuando no ha estado cambiando.

La forma más común de configurar la caché es mediante la [cabecera HTTP `Cache-Control`][cache]. Al utilizar Starlight, puedes establecer un tiempo de caché prolongado para todo lo que se encuentra en el directorio `/_astro/`. Este directorio contiene CSS, JavaScript y otros activos empaquetados que se pueden almacenar en caché de forma segura para siempre, reduciendo las descargas innecesarias.

```
Cache-Control: public, max-age=604800, immutable
```

Cómo configurar la caché depende de tu proveedor de alojamiento web. Por ejemplo, Vercel aplica automáticamente esta estrategia de caché sin necesidad de configuración, mientras que en Netlify puedes establecer [cabeceras personalizadas][ntl-headers] añadiendo un archivo `public/_headers` a tu proyecto:

```
/_astro/*
  Cache-Control: public
  Cache-Control: max-age=604800
  Cache-Control: immutable
```

[cache]: https://csswizardry.com/2019/03/cache-control-for-civilians/
[ntl-headers]: https://docs.netlify.com/routing/headers/

## Consumo de energía

La forma en que se construye una página web puede afectar la cantidad de energía necesaria para que funcione en el dispositivo de un usuario. Al utilizar un JavaScript mínimo, Starlight reduce la cantidad de potencia de procesamiento que necesita el teléfono, la tableta o la computadora de un usuario para cargar y renderizar las páginas.

Ten en cuenta que al agregar funciones como scripts de seguimiento de análisis o contenido pesado en JavaScript como incrustaciones de video, esto puede aumentar el consumo de energía de la página. Si necesitas analíticas, considera elegir una opción liviana como [Cabin][cabin], [Fathom][fathom] o [Plausible][plausible]. Las incrustaciones de videos de servicios como YouTube y Vimeo se pueden mejorar al [cargar el video cuando haya interacción del usuario][lazy-video]. Paquetes como [astro-embed][embed] pueden ser útiles para servicios comunes.

:::tip[¿Sabías esto?]
El análisis y compilación de JavaScript es una de las tareas más costosas que los navegadores deben realizar. En comparación con el renderizado de una imagen JPEG del mismo tamaño, [el procesamiento de JavaScript puede llevar más de 30 veces más tiempo][cost-of-js].
:::

[cabin]: https://withcabin.com/
[fathom]: https://usefathom.com/
[plausible]: https://plausible.io/
[lazy-video]: https://web.dev/iframe-lazy-loading/
[embed]: https://www.npmjs.com/package/astro-embed
[cost-of-js]: https://medium.com/dev-channel/the-cost-of-javascript-84009f51e99e

## Hospedaje

El lugar donde se hospeda una página web puede tener un gran impacto en la ecología de tu sitio de documentación. Los centros de datos y las granjas de servidores pueden tener un alto consumo de electricidad y un uso intensivo del agua.

Elegir un proveedor de alojamiento que utilice energía renovable significa tener emisiones de carbono más bajas para tu sitio. El [Directorio de la Web Ecológica][gwb] es una herramienta que puede ayudarte a encontrar empresas de alojamiento.

[gwb]: https://www.thegreenwebfoundation.org/directory/

## Comparaciones

¿Curioso por saber cómo se comparan otros frameworks de documentación?
Estas pruebas con el [Calculadora de Carbono de Sitios Web][wcc] comparan páginas similares construidas con diferentes herramientas.

| Framework                   | CO₂ por visita a la página | Calificación |
| --------------------------- | -------------------------- | :----------: |
| [Starlight][sl-carbon]      | 0.01g                      |      A+      |
| [Read the Docs][rtd-carbon] | 0.05g                      |      A+      |
| [Sphinx][sx-carbon]         | 0.06g                      |      A+      |
| [VitePress][vp-carbon]      | 0.07g                      |      A+      |
| [Docus][dc-carbon]          | 0.09g                      |      A+      |
| [docsify][dy-carbon]        | 0.10g                      |      A       |
| [Nextra][nx-carbon]         | 0.11g                      |      A       |
| [MkDocs][mk-carbon]         | 0.19g                      |      B       |
| [Docusaurus][ds-carbon]     | 0.21g                      |      B       |
| [GitBook][gb-carbon]        | 0.43g                      |      C       |
| [Mintlify][mt-carbon]       | 1.22g                      |      F       |

<small>Datos recopilados el 22 de Julio de 2024. Haz clic en un enlace para ver cifras actualizadas.</small>

[sl-carbon]: https://www.websitecarbon.com/website/starlight-astro-build-getting-started/
[vp-carbon]: https://www.websitecarbon.com/website/vitepress-dev-guide-what-is-vitepress/
[dc-carbon]: https://www.websitecarbon.com/website/docus-dev-introduction-getting-started/
[sx-carbon]: https://www.websitecarbon.com/website/sphinx-doc-org-en-master-usage-quickstart-html/
[mk-carbon]: https://www.websitecarbon.com/website/mkdocs-org-getting-started/
[nx-carbon]: https://www.websitecarbon.com/website/nextra-site-docs-docs-theme-start/
[dy-carbon]: https://www.websitecarbon.com/website/docsify-js-org/
[ds-carbon]: https://www.websitecarbon.com/website/docusaurus-io-docs/
[rtd-carbon]: https://www.websitecarbon.com/website/docs-readthedocs-io-en-stable-index-html/
[gb-carbon]: https://www.websitecarbon.com/website/docs-gitbook-com/
[mt-carbon]: https://www.websitecarbon.com/website/mintlify-com-docs-quickstart/

## Más recursos

### Herramientas

- [Calculadora de Carbono de Sitios Web][wcc]
- [GreenFrame](https://greenframe.io/)
- [Ecograder](https://ecograder.com/)
- [Control de Carbono WebPageTest](https://www.webpagetest.org/carbon-control/)
- [Ecoping](https://ecoping.earth/)

### Artículos y charlas

- [“Construyendo una web más ecológica”](https://youtu.be/EfPoOt7T5lg), charla de Michelle Barker
- [“Estrategias de desarrollo web sostenible dentro de una organización”](https://www.smashingmagazine.com/2022/10/sustainable-web-development-strategies-organization/), artículo de Michelle Barker
- [“Una web sostenible para todos”](https://2021.stateofthebrowser.com/speakers/tom-greenwood/), charla de Tom Greenwood
- [“Cómo el contenido web puede afectar el consumo de energía”](https://webkit.org/blog/8970/how-web-content-can-affect-power-usage/), artículo de Benjamin Poulain y Simon Fraser

[sf]: https://www.sciencefocus.com/science/what-is-the-carbon-footprint-of-the-internet/
[bbc]: https://www.bbc.com/future/article/20200305-why-your-internet-habits-are-not-as-clean-as-you-think
[http]: https://httparchive.org/reports/state-of-the-web
[assets]: https://docs.astro.build/en/guides/assets/
[islands]: https://docs.astro.build/en/concepts/islands/
[wcc]: https://www.websitecarbon.com/


================================================
FILE: docs/src/content/docs/es/getting-started.mdx
================================================
---
title: Empezando
description: Aprende cómo empezar a construir tu próximo sitio de documentación con Starlight utilizando Astro.
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

Starlight es un tema de documentación completo construido sobre el framework [Astro](https://astro.build).
Esta guía te ayudará a comenzar con un nuevo proyecto.
Consulta las [instrucciones de configuración manual](/es/manual-setup/) para agregar Starlight a un proyecto de Astro existente.

## Inicio rápido

### Crea un nuevo proyecto

Crea un nuevo proyecto de Astro + Starlight ejecutando el siguiente comando en tu terminal:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight
```

</TabItem>
</Tabs>

Esto creará un nuevo [directorio de proyecto](/es/guides/project-structure/) con todos los archivos y configuraciones necesarios para tu sitio.

:::tip[Míralo en acción]
Prueba Starlight en tu navegador:
[abre la plantilla en StackBlitz](https://stackblitz.com/github/withastro/starlight/tree/main/examples/basics).
:::

### Inicia el servidor de desarrollo

Cuando trabajas localmente, el [servidor de desarrollo de Astro](https://docs.astro.build/es/reference/cli-reference/#astro-dev) te permite previsualizar tu trabajo y actualiza automáticamente tu navegador cuando realizas cambios.

Dentro del directorio de tu proyecto, ejecuta el siguiente comando para iniciar el servidor de desarrollo:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm run dev
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dev
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dev
```

</TabItem>
</Tabs>

Esto imprimirá un mensaje en tu terminal con la URL de la vista previa local.
Abre esta URL para comenzar a navegar por tu sitio.

### Añade contenido

Starlight está listo para que añadas nuevo contenido o ¡traigas tus archivos existentes!.

Agrega nuevas páginas a tu sitio web creando archivos Markdown en el directorio `src/content/docs/`.

Lee más sobre el enrutamiento basado en archivos y el soporte para archivos MDX y Markdoc en la [Guía de Páginas](/es/guides/pages/)

### Siguientes pasos

- **Configura:** Aprende acerca de las opciones comunes en [“Personalizando Starlight”](/es/guides/customization/).
- **Navega:** Configura tu barra lateral siguiendo la guía [“Barra Lateral de Navegación”](/es/guides/sidebar/).
- **Componentes:** Descubre tarjetas incorporadas, pestañas y más en la guía [“Componentes”](/es/components/using-components/).
- **Despliega:** Publica tu trabajo siguiendo la guía [“Despliega tu sitio”](https://docs.astro.build/es/guides/deploy/) en la documentación de Astro.

## Actualizando Starlight

:::tip
Debido a que Starlight es un software beta, habrá actualizaciones y mejoras frecuentes.
¡Asegúrate de actualizar Starlight regularmente!
:::

Starlight es una integración Astro. Puedes actualizarlo y otros paquetes de Astro ejecutando el siguiente comando en tu terminal:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npx @astrojs/upgrade
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dlx @astrojs/upgrade
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dlx @astrojs/upgrade
```

</TabItem>
</Tabs>

Consulta el [registro de cambios de Starlight](https://github.com/withastro/starlight/blob/main/packages/starlight/CHANGELOG.md) para obtener una lista completa de los cambios realizados en cada versión.

## Solución de problemas de Starlight

Utiliza las páginas de referencia de [configuración del proyecto](/es/reference/configuration/) y [configuración del frontmatter de páginas individuales](/es/reference/frontmatter/) para asegurarte de que tu sitio de Starlight esté configurado y funcione correctamente.
Consulta las guías en la barra lateral para obtener ayuda en la adición de contenido y personalización de tu sitio de Starlight.

Si no encuentras la respuesta en la documentación, visita la [documentación completa de Astro](https://docs.astro.build/es/) para obtener la documentación completa de Astro.
Es posible que tu pregunta se responda comprendiendo cómo funciona Astro en general, debajo de este tema Starlight.

También puedes revisar cualquier problema conocido de [Starlight en GitHub](https://github.com/withastro/starlight/issues) y obtener ayuda en el [Discord de Astro](https://astro.build/chat/) de nuestra activa y amigable comunidad. ¡Publica preguntas en nuestro foro `#support` con la etiqueta "starlight" o visita nuestro canal dedicado `#starlight` para discutir el desarrollo actual y más!


================================================
FILE: docs/src/content/docs/es/guides/authoring-content.mdx
================================================
---
title: Creación de contenido en Markdown
description: Una descripción general de la sintaxis Markdown que soporta Starlight.
---

Starlight admite la gama completa de la sintaxis [Markdown](https://daringfireball.net/projects/markdown/) en archivos `.md`, así como el frontmatter en [YAML](https://dev.to/paulasantamaria/introduction-to-yaml-125f) para definir metadatos como el título y la descripción.

Por favor, asegúrate de consultar la documentación de [MDX](https://mdxjs.com/docs/what-is-mdx/#markdown) o [Markdoc](https://markdoc.dev/docs/syntax) si estás utilizando esos formatos de archivo, ya que el soporte y el uso de Markdown pueden variar.

## Frontmatter

Puedes personalizar individualmente las páginas en Starlight estableciendo valores en el frontmatter.
El frontmatter se establece en la parte superior de tus archivos entre separadores `---`:

```md title="src/content/docs/example.md"
---
title: Mi título de página
---

El contenido de la página sigue luego de los `---`.
```

Cada página debe incluir al menos un `title`.
Consulta la [referencia de frontmatter](/es/reference/frontmatter/) para ver todos los campos disponibles y cómo añadir campos personalizados.

## Estilos en línea

El texto puede estar **en negrita**, _en cursiva_, o ~~tachado~~.

```md
El texto puede estar **en negrita**, _en cursiva_, o ~~tachado~~.
```

Puedes [enlazar a otra página](/es/getting-started/).

```md
Puedes [enlazar a otra página](/es/getting-started/).
```

Puedes resaltar `código en línea` con comillas invertidas.

```md
Puedes resaltar `código en línea` con comillas invertidas.
```

## Imágenes

Las imágenes en Starlight utilizan el [soporte de assets optimizados incorporado en Astro](https://docs.astro.build/en/guides/assets/).

Markdown y MDX admiten la sintaxis Markdown para mostrar imágenes, que incluye alt-text para lectores de pantalla y tecnología de asistencia.

![Una ilustración de planetas y estrellas con la palabra “astro”](https://raw.githubusercontent.com/withastro/docs/main/public/default-og-image.png)

```md
![Una ilustración de planetas y estrellas con la palabra “astro”](https://raw.githubusercontent.com/withastro/docs/main/public/default-og-image.png)
```

También se admiten rutas de imágenes relativas para imágenes almacenadas localmente en tu proyecto.

```md
// src/content/docs/page-1.md

![Una nave espacial en el espacio](../../assets/images/rocket.svg)
```

## Encabezados

Puedes estructurar el contenido utilizando encabezados. Los encabezados en Markdown se indican con uno o más `#` al comienzo de la línea.

### Cómo estructurar el contenido de la página en Starlight

Starlight está configurado para utilizar automáticamente el título de tu página como un encabezado de nivel superior y se incluirá un encabezado "Visión general" en la parte superior de la tabla de contenido de cada página. Recomendamos comenzar cada página con contenido de texto de párrafo regular y utilizar encabezados dentro de la página a partir de `<h2>` en adelante:

```md
---
title: Guía de Markdown
description: Cómo utilizar Markdown en Starlight
---

Esta página describe cómo utilizar Markdown en Starlight.

## Estilos en línea

## Encabezados
```

### Enlaces de anclaje automáticos para encabezados.

Al utilizar encabezados en Markdown, se generan automáticamente enlaces de anclaje para que puedas vincular directamente a ciertas secciones de tu página:

```md
---
title: Mi página de contenido
description: Cómo utilizar los enlaces de anclaje integrados de Starlight.
---

## Introducción

Puedo enlazar a [mi conclusión](#conclusión) más abajo en la misma página.

## Conclusión

`https://mi-sitio.com/page1/#introduction` navega directamente a mi Introducción.
```

Los encabezados de nivel 2 (`<h2>`) y nivel 3 (`<h3>`) aparecerán automáticamente en la tabla de contenido de la página.

Aprende más sobre cómo Astro procesa los `id`s de los encabezados en [la documentación de Astro](https://docs.astro.build/es/guides/markdown-content/#ids-de-encabezado)

## Apartados

Los apartados (también conocidos como “apartados” o ”contenido destacado”) son útiles para mostrar información secundaria junto al contenido principal de una página.

Starlight proporciona una sintaxis personalizada de Markdown para renderizar apartados. Los bloques de apartados se indican utilizando un par de triples dos puntos `:::` para envolver tu contenido, y pueden ser de tipo `note`, `tip`, `caution` o `danger`.

Puedes anidar cualquier otro tipo de contenido Markdown dentro de un apartado, pero los apartados son más adecuados para fragmentos de contenido cortos y concisos.

### Nota de apartados

:::note
Starlight es un conjunto de herramientas para crear sitios web de documentación construido con [Astro](https://astro.build/). Puedes comenzar con este comando:

```sh
npm run create astro@latest --template starlight
```

:::

````md
:::note
Starlight es un conjunto de herramientas para sitios de documentación construido con [Astro](https://astro.build/). Puedes comenzar con este comando:

```sh
npm run create astro@latest --template starlight
```

:::
````

### Títulos personalizados para los apartados

Puedes especificar un título personalizado para el apartado utilizando corchetes cuadrados después del tipo del apartado, por ejemplo, `:::tip[¿Sabías esto?]`.

:::tip[¿Sabías esto?]
Astro te ayuda a construir sitios web más rápidos con la[“Arquitectura de Islas”](https://docs.astro.build/es/concepts/islands/).
:::

```md
:::tip[¿Sabías esto?]
Astro te ayuda a construir sitios web más rápidos con la[“Arquitectura de Islas”](https://docs.astro.build/es/concepts/islands/).
:::
```

### Más tipos de apartados

Los apartados de caution y danger son útiles para llamar la atención del usuario sobre detalles que podrían generar problemas. Si te encuentras utilizando estos tipos de apartados con frecuencia, también puede ser una señal de que lo que estás documentando podría beneficiarse de una reestructuración o rediseño.

:::caution
Si no estás seguro de si deseas un sitio de documentación increíble, piénsalo dos veces antes de usar [Starlight](/es/).
:::

:::danger
Tus usuarios pueden ser más productivos y encontrar más fácil de usar tu producto gracias a las útiles características de Starlight.

- Navegación clara
- Tema de color configurable por el usuario
- [Soporte de i18n](/es/guides/i18n/)

:::

```md
:::caution
Si no estás seguro de si deseas un sitio de documentación increíble, piénsalo dos veces antes de usar [Starlight](/es/).
:::

:::danger
Tus usuarios pueden ser más productivos y encontrar más fácil de usar tu producto gracias a las útiles características de Starlight.

- Navegación clara
- Tema de color configurable por el usuario
- [Soporte de i18n](/es/guides/i18n/)

:::
```

## Citas en bloque

> Esto es una cita en bloque, que se utiliza comúnmente para citar a otra persona o documento.
>
> Las citas en bloque se indican con un `>` al inicio de cada línea.

```md
> Esto es una cita en bloque, que se utiliza comúnmente para citar a otra persona o documento.
>
> Las citas en bloque se indican con un `>` al inicio de cada línea.
```

## Bloques de código

Un bloque de código se indica con un bloque de tres comillas invertidas <code>```</code> al inicio y al final. Puedes indicar el lenguaje de programación que se está utilizando después de las comillas invertidas de apertura.

```js
// Código JavaScript con resaltado de sintaxis.
var fun = function lang(l) {
	dateformat.i18n = require('./lang/' + l);
	return true;
};
```

````md
```js
// Código JavaScript con resaltado de sintaxis.
var fun = function lang(l) {
	dateformat.i18n = require('./lang/' + l);
	return true;
};
```
````

### Características de Expressive Code

Starlight usa [Expressive Code](https://github.com/expressive-code/expressive-code/tree/main/packages/astro-expressive-code) para ampliar las posibilidades de formato de los bloques de código.
Los marcadores de texto de Expressive Code y los plugins de marcos de ventana están habilitados de forma predeterminada.
El renderizado de los bloques de código se puede configurar utilizando la opción de configuración [`expressiveCode`](/es/reference/configuration/#expressivecode) de Starlight.

#### Marcadores de texto

Puedes resaltar líneas específicas o partes de tus bloques de código utilizando [los marcadores de texto de Expressive Code](https://github.com/expressive-code/expressive-code/blob/main/packages/%40expressive-code/plugin-text-markers/README.md#usage-in-markdown--mdx-documents) en la línea de apertura de tu bloque de código.
Usa llaves (`{ }`) para resaltar líneas enteras, y comillas para resaltar cadenas de texto.

Hay tres estilos de resaltado: neutral para llamar la atención sobre el código, verde para indicar código insertado y rojo para indicar código eliminado.
Tanto el texto como las líneas enteras pueden marcarse con el marcador predeterminado, o en combinación con `ins=` y `del=` para producir el resaltado deseado.

Expressive Code proporciona varias opciones para personalizar la apariencia visual de tus ejemplos de código.
Muchas de estas opciones se pueden combinar, para obtener ejemplos de código altamente ilustrativos.
Por favor, explora la [documentación de Expressive Code](https://github.com/expressive-code/expressive-code/blob/main/packages/%40expressive-code/plugin-text-markers/README.md) para ver las extensas opciones disponibles.
Algunos de los ejemplos más comunes se muestran a continuación:

- [Marca líneas enteras y rangos de líneas usando el marcador `{ }`](https://github.com/expressive-code/expressive-code/blob/main/packages/%40expressive-code/plugin-text-markers/README.md#marking-entire-lines--line-ranges):

  ```js {2-3}
  function demo() {
    // Esta línea (#2) y la siguiente están resaltadas
    retrun 'Esta es la línea #3 de este fragmento'
  }
  ```

  ````md
  ```js {2-3}
  function demo() {
  	// Esta línea (#2) y la siguiente están resaltadas
  	return 'Esta es la línea #3 de este fragmento';
  }
  ```
  ````

- [Marca selecciones de texto usando el marcador `" "` o expresiones regulares](https://github.com/expressive-code/expressive-code/blob/main/packages/%40expressive-code/plugin-text-markers/README.md#marking-individual-text-inside-lines):

  ```js "Términos individuales" /También.*compatibles/
  // Términos individuales también pueden ser resaltados
  function demo() {
  	return 'También las expresiones regulares son compatibles';
  }
  ```

  ````md
  ```js "Términos individuales" /También.*compatibles/
  // Términos individuales también pueden ser resaltados
  function demo() {
  	return 'También las expresiones regulares son compatibles';
  }
  ```
  ````

- [Marca texto o líneas como insertadas o eliminadas con `ins` o `del`](https://github.com/expressive-code/expressive-code/blob/main/packages/%40expressive-code/plugin-text-markers/README.md#selecting-marker-types-mark-ins-del):

  ```js "return true;" ins="insertados" del="eliminados"
  function demo() {
  	console.log('Estos son tipos de marcadores insertados y eliminados');
  	// La declaración de retorno utiliza el tipo de marcador predeterminado
  	return true;
  }
  ```

  ````md
  ```js "return true;" ins="insertados" del="eliminados"
  function demo() {
  	console.log('Estos son tipos de marcadores insertados y eliminados');
  	// La declaración de retorno utiliza el tipo de marcador predeterminado
  	return true;
  }
  ```
  ````

- [Combina el resaltado de sintaxis con la sintaxis similar a `diff`](https://github.com/expressive-code/expressive-code/blob/main/packages/%40expressive-code/plugin-text-markers/README.md#combining-syntax-highlighting-with-diff-like-syntax):

  ```diff lang="js"
    function thisIsJavaScript() {
      // ¡El bloque completo se resalta como JavaScript,
      // y aún podemos añadir marcadores de diferencias a él!
  -   console.log('Código antiguo a eliminar')
  +   console.log('¡Nuevo y brillante código!')
    }
  ```

  ````md
  ```diff lang="js"
    function thisIsJavaScript() {
      // ¡El bloque completo se resalta como JavaScript,
      // y aún podemos añadir marcadores de diferencias a él!
  -   console.log('Código antiguo a eliminar')
  +   console.log('¡Nuevo y brillante código!')
    }
  ```
  ````

#### Marcos y títulos

Los bloques de código se pueden representar dentro de un marco similar a una ventana.
Un marco que se parece a una ventana de código se utilizará para todos los demás lenguajes de programación (por ejemplo, `bash`o `sh`).
Otros lenguajes se muestran dentro de un marco de estilo de editor de código si incluyen un título.

Un título opcional del bloque de código se puede establecer con un atributo `title="..."` después de las comillas invertidas de apertura del bloque de código y el identificador del lenguaje, o con un comentario del nombre del archivo en las primeras líneas del código.

- [Añade una pestaña con el nombre del archivo con un comentario](https://github.com/expressive-code/expressive-code/blob/main/packages/%40expressive-code/plugin-frames/README.md#adding-titles-open-file-tab-or-terminal-window-title)

  ```js
  // mi-archivo-de-prueba.js
  console.log('¡Hola mundo!');
  ```

  ````md
  ```js
  // mi-archivo-de-prueba.js
  console.log('¡Hola mundo!');
  ```
  ````

- [Agrega un título a la ventana Terminal](https://github.com/expressive-code/expressive-code/blob/main/packages/%40expressive-code/plugin-frames/README.md#adding-titles-open-file-tab-or-terminal-window-title)

  ```bash title="Instalando dependencias…"
  npm install
  ```

  ````md
  ```bash title="Instalando dependencias…"
  npm install
  ```
  ````

- [Desactiva los marcos de ventana con `frame="none"`](https://github.com/expressive-code/expressive-code/blob/main/packages/%40expressive-code/plugin-frames/README.md#overriding-frame-types)

  ```bash frame="none"
  echo "Esto no se renderiza como una terminal a pesar de usar el lenguaje bash"
  ```

  ````md
  ```bash frame="none"
  echo "Esto no se renderiza como una terminal a pesar de usar el lenguaje bash"
  ```
  ````

## Details

Los details (también conocidos como "revelaciones" o "acordeones") son útiles para ocultar contenido que no es inmediatamente relevante.
Los usuarios pueden hacer clic en un breve resumen para expandir y ver el contenido completo.

Usa el elemento HTML estándar [`<details>`](https://developer.mozilla.org/es/docs/Web/HTML/Element/details) y [`<summary>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/summary) en tu contenido Markdown para crear un widget de revelación.

Puedes anidar cualquier otra sintaxis de Markdown dentro de un elemento `<details>`.

<details>
<summary>¿Dónde y cuándo es más visible la constelación de Andrómeda?</summary>

La [constelación de Andrómeda](<https://es.wikipedia.org/wiki/Andr%C3%B3meda_(constelaci%C3%B3n)>) es más visible en el cielo nocturno durante el mes de noviembre en latitudes entre `+90°` y `−40°`.

</details>

```md
<details>
<summary>¿Dónde y cuándo es más visible la constelación de Andrómeda?</summary>

La [constelación de Andrómeda](<https://es.wikipedia.org/wiki/Andr%C3%B3meda_(constelaci%C3%B3n)>) es más visible en el cielo nocturno durante el mes de noviembre en latitudes entre `+90°` y `−40°`.

</details>
```

## Otras características comunes de Markdown

Starlight admite todas las demás sintaxis de autoría de Markdown, como listas y tablas. Puedes consultar la [Guía de referencia de Markdown](https://www.markdownguide.org/cheat-sheet/) para obtener una descripción general rápida de todos los elementos de sintaxis de Markdown.

## Configuración avanzada de Markdown y MDX

Starlight utiliza el motor de renderizado de Markdown y MDX de Astro, construido sobre remark y rehype. Puedes añadir soporte para sintaxis y comportamientos personalizados añadiendo `remarkPlugins` o `rehypePlugins` en tu archivo de configuración de Astro. Consulta la sección ["Plugins de Markdown"](https://docs.astro.build/es/guides/markdown-content/#plugins-de-markdown) en la documentación de Astro para obtener más información.

## Markdoc

Starlight admite la creación de contenido en Markdoc utilizando la integración experimental de [Astro Markdoc](https://docs.astro.build/es/guides/integrations-guide/markdoc/) y el preset de Starlight Markdoc.

### Crea un nuevo proyecto con Markdoc

Empieza un nuevo proyecto en Starlight con Markdoc preconfigurado usando `create astro`:

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight/markdoc
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight/markdoc
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight/markdoc
```

</TabItem>
</Tabs>

### Agrega Markdoc a un proyecto existente

Si ya tienes un sitio Starlight y quieres agregar Markdoc, sigue estos pasos.

<Steps>

1.  Agrega la integración de Markdoc de Astro:

    <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npx astro add markdoc
    ```

    </TabItem>

    <TabItem label="pnpm">

    ```sh
    pnpm astro add markdoc
    ```

    </TabItem>

    <TabItem label="Yarn">

    ```sh
    yarn astro add markdoc
    ```

    </TabItem>

    </Tabs>

2.  Instala el preajuste de Starlight Markdoc:

    <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npm install @astrojs/starlight-markdoc
    ```

    </TabItem>

    <TabItem label="pnpm">

    ```sh
    pnpm add @astrojs/starlight-markdoc
    ```

    </TabItem>

    <TabItem label="Yarn">

    ```sh
    yarn add @astrojs/starlight-markdoc
    ```

    </TabItem>

    </Tabs>

3.  Crea un archivo de configuración de Markdoc en `markdoc.config.mjs` y utiliza el preset de Starlight Markdoc:

    ```js
    import { defineMarkdocConfig } from '@astrojs/markdoc/config';
    import starlightMarkdoc from '@astrojs/starlight-markdoc';

    export default defineMarkdocConfig({
    	extends: [starlightMarkdoc()],
    });
    ```

</Steps>

Para obtener más información sobre la sintaxis y las características de Markdoc, consulta la [documentación de Markdoc](https://markdoc.dev/docs/syntax) o la [guía de integración de Astro Markdoc](https://docs.astro.build/es/guides/integrations-guide/markdoc/).


================================================
FILE: docs/src/content/docs/es/guides/css-and-tailwind.mdx
================================================
---
title: CSS y Estilos
description: Aprende a darle estilo a tu sitio Starlight con CSS personalizado o integrado con Tailwind CSS.
---

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

Puedes darle estilo a tu sitio de Starlight con archivos CSS personalizados o usar el plugin Starlight Tailwind.

## Estilos CSS personalizados

Personaliza los estilos aplicados a tu sitio Starlight proporcionando archivos CSS adicionales para modificar o extender los estilos predeterminados de Starlight.

<Steps>

1. Agrega un archivo CSS a tu directorio `src/`.
   Por ejemplo, podrías establecer un ancho de columna predeterminado más ancho y un tamaño de texto más grande para los títulos de las páginas:

   ```css
   /* src/styles/custom.css */
   :root {
   	--sl-content-width: 50rem;
   	--sl-text-5xl: 3.5rem;
   }
   ```

2. Agrega la ruta de tu archivo CSS al array `customCss` de Starlight en `astro.config.mjs`:

   ```diff lang="js"
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Docs With Custom CSS',
   			customCss: [
   +                // Ruta relativa a tu archivo CSS personalizado
   +				'./src/styles/custom.css',
   			],
   		}),
   	],
   });
   ```

</Steps>

Puedes ver todas las propiedades CSS personalizadas utilizadas por Starlight que puedes establecer para personalizar tu sitio en el archivo [`props.css` en GitHub](https://github.com/withastro/starlight/blob/main/packages/starlight/style/props.css).

## Tailwind CSS

El soporte de CSS de Tailwind en proyectos de Astro es proporcionado por la [integración Astro Tailwind](https://docs.astro.build/en/guides/integrations-guide/tailwind/).
Starlight proporciona un plugin de Tailwind para ayudar a configurar Tailwind para que sea compatible con los estilos de Starlight.

El plugin Starlight Tailwind aplica la siguiente configuración:

- Configura las variantes de Tailwind `dark:` para que funcionen con el modo oscuro de Starlight.
- Usa los [colores y fuentes del tema](#estilando-starlight-con-tailwind) de Tailwind en la UI de Starlight.
- Desactiva la [comprobación preliminar “Preflight”](https://tailwindcss.com/docs/preflight) de Tailwind mientras restauras selectivamente las partes esenciales de la comprobación preliminar requeridas para las clases de utilidad de borde de Tailwind.

### Crea un nuevo proyecto con Tailwind

Empieza un nuevo proyecto en Starlight con Tailwind CSS preconfigurado usando `create astro`:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight/tailwind
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight/tailwind
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight/tailwind
```

</TabItem>
</Tabs>

### Agrega Tailwind a un proyecto existente

Si ya tienes un sitio en Starlight y quieres agregar Tailwind CSS, sigue estos pasos.

<Steps>

1.  Agrega la integración de Tailwind de Astro:

    <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npx astro add tailwind
    ```

    </TabItem>

    <TabItem label="pnpm">

    ```sh
    pnpm astro add tailwind
    ```

    </TabItem>

    <TabItem label="Yarn">

    ```sh
    yarn astro add tailwind
    ```

    </TabItem>

    </Tabs>

2.  Instala el plugin Starlight Tailwind:

    <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npm install @astrojs/starlight-tailwind
    ```

    </TabItem>

    <TabItem label="pnpm">

    ```sh
    pnpm add @astrojs/starlight-tailwind
    ```

    </TabItem>

    <TabItem label="Yarn">

    ```sh
    yarn add @astrojs/starlight-tailwind
    ```

    </TabItem>

    </Tabs>

3.  Crea un archivo CSS para los estilos base de Tailwind, por ejemplo en `src/tailwind.css`:

    ```css
    /* src/tailwind.css */
    @tailwind base;
    @tailwind components;
    @tailwind utilities;
    ```

4.  Actualiza tu archivo de configuración de Astro para usar tus estilos base de Tailwind y desactivar los estilos base predeterminados:

    ```js {11-12,16-17}
    // astro.config.mjs
    import { defineConfig } from 'astro/config';
    import starlight from '@astrojs/starlight';
    import tailwind from '@astrojs/tailwind';

    export default defineConfig({
    	integrations: [
    		starlight({
    			title: 'Documentación con Tailwind',
    			customCss: [
    				// Ruta a tus estilos base de Tailwind:
    				'./src/tailwind.css',
    			],
    		}),
    		tailwind({
    			// Desactiva los estilos base predeterminados:
    			applyBaseStyles: false,
    		}),
    	],
    });
    ```

5.  Agrega el plugin Starlight Tailwind a `tailwind.config.mjs`:

    ```js ins={2,7}
    // tailwind.config.mjs
    import starlightPlugin from '@astrojs/starlight-tailwind';

    /** @type {import('tailwindcss').Config} */
    export default {
    	content: ['./src/**/*.{astro,html,js,jsx,md,mdx,svelte,ts,tsx,vue}'],
    	plugins: [starlightPlugin()],
    };
    ```

</Steps>

### Estilando Starlight con Tailwind

Starlight utilizará los valores de la [configuración de tema Tailwind](https://tailwindcss.com/docs/theme) en su UI.

Si se establece, las siguientes opciones anularán los estilos predeterminados de Starlight:

- `colors.accent` - usada para enlaces y resaltado de elementos actuales
- `colors.gray` - usada para colores de fondo y bordes
- `fontFamily.sans` - usada para el texto de la UI y el contenido
- `fontFamily.mono` - usada para ejemplos de código

```js {12,14,18,20}
// tailwind.config.mjs
import starlightPlugin from '@astrojs/starlight-tailwind';
import colors from 'tailwindcss/colors';

/** @type {import('tailwindcss').Config} */
export default {
	content: ['./src/**/*.{astro,html,js,jsx,md,mdx,svelte,ts,tsx,vue}'],
	theme: {
		extend: {
			colors: {
				// Tu color de acento preferido. Indigo es el más cercano a los valores predeterminados de Starlight.
				accent: colors.indigo,
				// Tu escala de grises preferida. Zinc es el más cercano a los valores predeterminados de Starlight.
				gray: colors.zinc,
			},
			fontFamily: {
				// Tu fuente de texto preferida. Starlight usa una pila de fuentes del sistema de forma predeterminada.
				sans: ['"Atkinson Hyperlegible"'],
				// Tu fuente de código preferida. Starlight usa fuentes monoespaciadas del sistema de forma predeterminada.
				mono: ['"IBM Plex Mono"'],
			},
		},
	},
	plugins: [starlightPlugin()],
};
```

## Temas

El tema de color de Starlight se puede controlar anulando sus propiedades personalizadas predeterminadas.
Estas variables son utilizadas en toda la UI con una gama de tonos grises utilizados para los colores de texto y fondo y un color de acento utilizado para los enlaces y para resaltar los elementos actuales en la navegación.

### Editor de temas de color

Usa los controles deslizantes a continuación para modificar las paletas de colores de acento y gris de Starlight.
Las áreas de vista previa oscura y clara mostrarán los colores resultantes, y toda la página también se actualizará para obtener una vista previa de tus cambios.

Usa la opción Nivel de Contraste para especificar qué estándares de contraste de color de las [pautas de accesibilidad de contenido web](https://developer.mozilla.org/es/docs/Web/Accessibility/Understanding_WCAG/Perceivable/Color_contrast) debe cumplir.

Cuando estés satisfecho con tus cambios, copia el código CSS o Tailwind a continuación y úsalo en tu proyecto.

import ThemeDesigner from '~/components/theme-designer.astro';

<ThemeDesigner
	labels={{
		presets: {
			label: 'Preajustes',
			ocean: 'Océano',
			forest: 'Bosque',
			oxide: 'Óxido',
			nebula: 'Nebulosa',
			default: 'Por defecto',
			random: 'Aleatorio',
		},
		contrast: {
			label: 'Nivel de Contraste',
		},
		editor: {
			accentColor: 'Acento',
			grayColor: 'Gris',
			hue: 'Tono',
			chroma: 'Croma',
			pickColor: 'Elegir color',
		},
		preview: {
			darkMode: 'Modo oscuro',
			lightMode: 'Modo claro',
			bodyText:
				'El texto del cuerpo se muestra en un tono gris con un alto contraste con el fondo.',
			linkText: 'Los enlaces están coloreados.',
			dimText:
				'Algunos textos, como la tabla de contenidos, tienen un contraste más bajo.',
			inlineCode: 'El código en línea tiene un fondo distinto.',
		},
	}}
>
	<Fragment slot="css-docs">
		Agrega el siguiente CSS a tu proyecto en un [archivo CSS
		personalizado](#estilos-css-personalizados) para aplicar este tema a tu
		sitio.
	</Fragment>
	<Fragment slot="tailwind-docs">
		El ejemplo de [archivo de configuración de
		Tailwind](#estilando-starlight-con-tailwind) a continuación incluye paletas
		de colores `accent` y `gray` generadas para usar en el objeto de
		configuración `theme.extend.colors`.
	</Fragment>
</ThemeDesigner>


================================================
FILE: docs/src/content/docs/es/guides/customization.mdx
================================================
---
title: Personalizando Starlight
description: Aprende cómo personalizar tu sitio de Starlight con estilos personalizados, fuentes y mucho más.
---

import { Tabs, TabItem, FileTree, Steps } from '@astrojs/starlight/components';

Starlight proporciona estilos y características predeterminadas sensatas, por lo que puedes comenzar rápidamente sin necesidad de configuración. Cuando desees comenzar a personalizar la apariencia de tu sitio de Starlight, esta guía te proporciona toda la información necesaria.

## Añade tu logo

Agregando un logo personalizado al encabezado del sitio es una forma rápida de agregar tu marca personalizada a un sitio de Starlight.

<Steps>

1. Agrega el archivo de imagen de tu logo al directorio `src/assets/`:

   <FileTree>

   - src/
     - assets/
       - **mi-logo.svg**
     - content/
   - astro.config.mjs

   </FileTree>

2. Agrega la ruta de tu logotipo como opción [`logo.src`](/es/reference/configuration/#logo) de Starlight en el archivo `astro.config.mjs`:

   ```diff lang="js"
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Docs Con Mi Logo',
   			logo: {
   +				src: './src/assets/my-logo.svg',
   			},
   		}),
   	],
   });
   ```

</Steps>

De forma predeterminada, el logo se mostrará junto al título de tu sitio.
Si tu imagen de logo ya incluye el título del sitio, puedes ocultar visualmente el texto del título estableciendo la opción `replacesTitle`.
El texto del título seguirá estando disponible para lectores de pantalla para garantizar la accesibilidad del encabezado.

```js {5}
starlight({
  title: 'Docs Con Mi Logo',
  logo: {
    src: './src/assets/mi-logo.svg',
    replacesTitle: true,
  },
}),
```

### Variantes de logo claro y oscuro

Puedes mostrar diferentes versiones de tu logo en modos claro y oscuro.

<Steps>

1. Agrega un archivo de imagen para cada variante en el directorio `src/assets/`:

   <FileTree>

   - src/
     - assets/
       - **logo-claro.svg**
       - **logo-oscuro.svg**
     - content/
   - astro.config.mjs

   </FileTree>

2. Agrega la ruta de tus variantes de logo como opciones `light` y `dark` en lugar de `src` en el archivo `astro.config.mjs`:

   ```diff lang="js"
   starlight({
     title: 'Docs Con Mi Logo',
     logo: {
   +    light: './src/assets/light-logo.svg',
   +    dark: './src/assets/dark-logo.svg',
     },
   }),
   ```

</Steps>

## Habilitar el mapa del sitio

Starlight tiene soporte incorporado para generar un mapa del sitio. Habilita la generación del mapa del sitio estableciendo tu URL como `site` en `astro.config.mjs`:

```js {4}
// astro.config.mjs

export default defineConfig({
	site: 'https://stargazers.club',
	integrations: [starlight({ title: 'Sitio con mapa del sitio' })],
});
```

Aprende cómo [agregar un enlace del mapa del sitio a `robots.txt`](https://docs.astro.build/es/guides/integrations-guide/sitemap/#enlace-de-sitemap-en-robotstxt) en la documentación de Astro.

## Diseño de página

De forma predeterminada, las páginas de Starlight utilizan un diseño con una barra lateral de navegación global y una tabla de contenidos que muestra los encabezados de la página actual.

Puedes aplicar un diseño de página más amplio sin barras laterales estableciendo [`template: splash`](/es/reference/frontmatter/#template) en el frontmatter de una página. Esto funciona especialmente bien para páginas de inicio y puedes verlo en acción en la [página de inicio de este sitio](/es/).

```md {5}
---
# src/content/docs/index.md

title: Mi página Landing
template: splash
---
```

## Tabla de contenidos

Starlight muestra una tabla de contenidos en cada página para facilitar que los lectores naveguen hasta el encabezado que están buscando. Puedes personalizar — e incluso desactivar — la tabla de contenidos de forma global en la integración de Starlight o de forma individual en el frontmatter de cada página.

De forma predeterminada, los encabezados `<h2>` y `<h3>` se incluyen en la tabla de contenidos. Puedes cambiar qué niveles de encabezados se incluyen en toda la página utilizando las opciones `minHeadingLevel` y `maxHeadingLevel` en tu configuración [global de `tableOfContents`](/es/reference/configuration/#tableofcontents). Puedes anular estas configuraciones predeterminadas en una página individual agregando las propiedades correspondientes de [`tableOfContents` en el frontmatter](/es/reference/frontmatter/#tableofcontents):

<Tabs syncKey="config-type">
  <TabItem label="Frontmatter">

```md {4-6}
---
# src/content/docs/example.md
title: Página con solo encabezados H2 en la tabla de contenidos
tableOfContents:
  minHeadingLevel: 2
  maxHeadingLevel: 2
---
```

  </TabItem>
  <TabItem label="Configuración global">

```js {7}
// astro.config.mjs

defineConfig({
	integrations: [
		starlight({
			title: 'Docs con una configuración personalizada de tabla de contenidos',
			tableOfContents: { minHeadingLevel: 2, maxHeadingLevel: 2 },
		}),
	],
});
```

  </TabItem>
</Tabs>

Desactiva completamente la tabla de contenidos estableciendo la opción `tableOfContents` en `false`:

<Tabs syncKey="config-type">
  <TabItem label="Frontmatter">

```md {4}
---
# src/content/docs/example.md
title: Página sin tabla de contenidos
tableOfContents: false
---
```

  </TabItem>
  <TabItem label="Configuración global">

```js {7}
// astro.config.mjs

defineConfig({
	integrations: [
		starlight({
			title: 'Docs con la tabla de contenidos desactivada globalmente',
			tableOfContents: false,
		}),
	],
});
```

  </TabItem>
</Tabs>

## Enlaces sociales

Starlight cuenta con soporte incorporado para agregar enlaces a tus cuentas de redes sociales en el encabezado del sitio mediante la opción [`social`](/es/reference/configuration/#social) en la integración de Starlight.

Puedes encontrar una lista completa de todos los iconos de enlaces compatibles en la [Referencia de Configuración](/es/reference/configuration/#social).

```js {9-12}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Docs Con Mis Enlaces Sociales',
			social: {
				discord: 'https://astro.build/chat',
				github: 'https://github.com/withastro/starlight',
			},
		}),
	],
});
```

## Enlaces de edición

Starlight puede mostrar un enlace ”Editar página” en el pie de cada página. Esto facilita que los lectores encuentren el archivo que deben editar para mejorar tus documentos. Para proyectos de código abierto en particular, esto puede ayudar a fomentar las contribuciones de tu comunidad.

Para habilitar los enlaces de edición, establece [`editLink.baseUrl`](/es/reference/configuration/#editlink) en la URL utilizada para editar tu repositorio en la configuración de integración de Starlight.
El valor de `editLink.baseUrl` se añadirá al inicio de la ruta de la página actual para formar el enlace de edición completo.

Algunos patrones comunes incluyen:

- GitHub: `https://github.com/USER_NAME/REPO_NAME/edit/BRANCH_NAME/`
- GitLab: `https://gitlab.com/USER_NAME/REPO_NAME/-/edit/BRANCH_NAME/`

Si tu proyecto de Starlight no se encuentra en la raíz de tu repositorio, incluye la ruta al proyecto al final de la URL base.

Este ejemplo muestra el enlace de edición configurado para la documentación de Starlight, que se encuentra en el subdirectorio `docs/` en la rama `main` del repositorio `withastro/starlight` en GitHub:

```js {9-12}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Docs Con Enlaces De Edición',
			editLink: {
				baseUrl: 'https://github.com/withastro/starlight/edit/main/docs/',
			},
		}),
	],
});
```

## Páginas 404 personalizadas

Los sitios de Starlight muestran de forma predeterminada una página de error 404 simple. Puedes personalizarla agregando un archivo `404.md` (o `404.mdx`) a tu directorio `src/content/docs/`.

<FileTree>

- src/
  - content/
    - docs/
      - **404.md**
      - index.md
- astro.config.mjs

</FileTree>

Puedes utilizar todas las técnicas de diseño y personalización de páginas de Starlight en tu página de error 404. Por ejemplo, la página de error 404 predeterminada utiliza la [plantilla `splash`](#diseño-de-página) y el componente [`hero`](/es/reference/frontmatter/#hero) en el frontmatter:

```md {4, 6-8}
---
# src/content/docs/404.md
title: '404'
template: splash
editUrl: false
hero:
  title: '404'
  tagline: Página no encontrada. Verifica la URL o intenta usar la barra de búsqueda.
---
```

### Desactivar la página 404 predeterminada

Si tu proyecto requiere un diseño 404 completamente personalizado, puedes crear una ruta `src/pages/404.astro` y establecer la opción de configuración [`disable404Route`](/es/reference/configuration/#disable404route) para desactivar la ruta predeterminada de Starlight:

```js {9}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Docs With Custom 404',
			disable404Route: true,
		}),
	],
});
```

## Fuentes personalizadas

De forma predeterminada, Starlight utiliza fuentes sans-serif disponibles en el dispositivo local del usuario para todo el texto.
Esto asegura que la documentación se cargue rápidamente en una fuente que sea familiar para cada usuario, sin necesidad de utilizar ancho de banda adicional para descargar archivos de fuentes grandes.

Si necesitas agregar una fuente personalizada a tu sitio de Starlight, puedes configurar las fuentes para utilizarlas en archivos CSS personalizados o mediante cualquier otra [técnica de estilo de Astro](https://docs.astro.build/es/guides/styling/).

### Configurar fuentes

Si ya tienes archivos de fuentes, sigue la [guía de configuración local](#configurar-archivos-de-fuentes-locales).
Para utilizar Google Fonts, sigue la [guía de configuración de Fontsource](#configurar-una-fuente-de-fontsource).

#### Configurar archivos de fuentes locales.

<Steps>

1. Agrega tus archivos de fuente a un directorio `src/fonts/` y crea un archivo `font-face.css` vacío.

   <FileTree>

   - src/
     - content/
     - fonts/
       - **FuentePersonalizada.woff2**
       - **font-face.css**
   - astro.config.mjs

   </FileTree>

2. Agrega una declaración [`@font-face`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face) para cada una de tus fuentes en `src/fonts/font-face.css`.
   Utiliza una ruta relativa al archivo de fuente dentro de la función `url()`.

   ```css
   /* src/fonts/font-face.css */

   @font-face {
   	font-family: 'Fuente Personalizada';
   	/* Utiliza una ruta relativa al archivo de fuente local dentro de la función `url()`. */
   	src: url('./FuentePersonalizada.woff2') format('woff2');
   	font-weight: normal;
   	font-style: normal;
   	font-display: swap;
   }
   ```

3. Agrega la ruta al archivo `font-face.css` al arreglo `customCss` de Starlight en `astro.config.mjs`.

   ```diff lang="js"
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Docs Con Un Tipo De Letra Personalizado',
   			customCss: [
   +				// Ruta relativa a tu archivo CSS @font-face.
   +				'./src/fonts/font-face.css',
   			],
   		}),
   	],
   });
   ```

</Steps>

#### Configurar una fuente de Fontsource

El proyecto [Fontsource](https://fontsource.org/) simplifica el uso de fuentes de Google Fonts y otras fuentes de código abierto.
Proporciona módulos npm que puedes instalar para las fuentes que deseas utilizar e incluye archivos CSS listos para usar que puedes agregar a tu proyecto.

<Steps>

1.  Encuentra la fuente que deseas utilizar en el catálogo de [Fontsource](https://fontsource.org/).
    En este ejemplo, se utilizará [IBM Plex Serif](https://fontsource.org/fonts/ibm-plex-serif).

2.  Instala el paquete para la fuente que has elegido.
    Puedes encontrar el nombre del paquete haciendo clic en “Install” en la página de la fuente de Fontsource.

             <Tabs syncKey="pkg">

        <TabItem label="npm">

        ```sh
        npm install @fontsource/ibm-plex-serif
        ```

               </TabItem>

            <TabItem label="pnpm">

        ```sh
        pnpm add @fontsource/ibm-plex-serif
        ```

               </TabItem>

            <TabItem label="Yarn">

        ```sh
        yarn add @fontsource/ibm-plex-serif
        ```

               </TabItem>

          </Tabs>

3.  Agrega los archivos CSS de Fontsource al arreglo `customCss` de Starlight en `astro.config.mjs`.

    ```diff lang="js"
    // astro.config.mjs
    import { defineConfig } from 'astro/config';
    import starlight from '@astrojs/starlight';

    export default defineConfig({
    	integrations: [
    		starlight({
    			title: 'Docs Con Un Tipo De Letra Personalizado',
    			customCss: [
    +				// Archivos de Fontsource para pesos de fuente regular y semi-negrita.
    +				'@fontsource/ibm-plex-serif/400.css',
    +				'@fontsource/ibm-plex-serif/600.css',
    			],
    		}),
    	],
    });
    ```

    Fontsource incluye varios archivos CSS para cada fuente. Consulta la [documentación de Fontsource](https://fontsource.org/docs/getting-started/install#4-weights-and-styles) sobre cómo incluir diferentes pesos y estilos para comprender cuál debes usar.

</Steps>

### Usar fuentes

Para aplicar la fuente que configuraste a tu sitio, utiliza el nombre de la fuente elegida en un [archivo CSS personalizado](/es/guides/css-and-tailwind/#estilos-css-personalizados).
Por ejemplo, para anular la fuente predeterminada de Starlight en todas partes, establece la propiedad personalizada `--sl-font`:

```css
/* src/styles/custom.css */

:root {
	--sl-font: 'IBM Plex Serif', serif;
}
```

También puedes escribir CSS más específico si deseas aplicar tu fuente de manera más selectiva.
Por ejemplo, para establecer una fuente solo en el contenido principal, pero no en las barras laterales:

```css
/* src/styles/custom.css */

main {
	font-family: 'IBM Plex Serif', serif;
}
```

Sigue las [instrucciones de CSS personalizado](/es/guides/css-and-tailwind/#estilos-css-personalizados) para agregar tus estilos a tu sitio.


================================================
FILE: docs/src/content/docs/es/guides/i18n.mdx
================================================
---
title: Internacionalización (i18n)
description: Aprende a configurar tu sitio Starlight para admitir varios idiomas.
---

import { FileTree, Steps } from '@astrojs/starlight/components';

Starlight proporciona soporte incorporado para sitios multilingües, incluidas las rutas, el contenido de respaldo y el soporte completo de idiomas de derecha a izquierda (RTL).

## Configura i18n

<Steps>

1. Indícale a Starlight los idiomas que admites pasando [`locales`](/es/reference/configuration/#locales) y [`defaultLocale`](/es/reference/configuration/#defaultlocale) a la integración de Starlight:

   ```js {9-26}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Mis Docs',
   			// Establece el inglés como el idioma predeterminado para este sitio.
   			defaultLocale: 'en',
   			locales: {
   				// Documentación en inglés en `src/content/docs/en/`
   				en: {
   					label: 'English',
   				},
   				// Chino simplificado en `src/content/docs/zh-cn/`
   				'zh-cn': {
   					label: '简体中文',
   					lang: 'zh-CN',
   				},
   				// Documentación en árabe en `src/content/docs/ar/`
   				ar: {
   					label: 'العربية',
   					dir: 'rtl',
   				},
   			},
   		}),
   	],
   });
   ```

   Tu `defaultLocale` se utilizará para el contenido y las etiquetas de la UI de respaldo, por lo que elige el idioma en el que es más probable que comiences a escribir contenido o que ya tengas contenido.

2. Crea un directorio para cada idioma en `src/content/docs/`.
   Por ejemplo, para la configuración mostrada anteriormente, crea las siguientes carpetas:

   <FileTree>

   - src/
     - content/
       - docs/
         - ar/
         - en/
         - zh-cn/

   </FileTree>

3. Ahora puedes agregar archivos de contenido en los directorios de tu idioma. Utiliza el mismo nombre de archivo para asociar páginas entre idiomas y aprovechar todas las características de internacionalización (i18n) de Starlight, como contenido de respaldo, avisos de traducción y más.

   Por ejemplo, crea `ar/index.md` y `en/index.md` para representar la página de inicio en árabe e inglés, respectivamente.

</Steps>

Para escenarios de i18n más avanzados, Starlight también admite la configuración de internacionalización utilizando la [opción `i18n` de Astro](https://docs.astro.build/es/guides/internationalization/#configuración-de-rutas-i18n).

### Usa una raíz de configuración regional

Puedes usar una raíz de configuración regional para servir un idioma sin ningún prefijo i18n en tu ruta. Por ejemplo, si el inglés es tu configuración regional, una ruta de página en inglés se vería como `/about` en lugar de `/en/about`.

Para establecer una configuración regional, usa la clave `root` en tu configuración de `locales`. Si la configuración regional raíz también es la configuración regional predeterminada para tu contenido, elimina `defaultLocale` o configúralo en `'root'`.

```js {9,11-14}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'My Docs',
			defaultLocale: 'root', // opcional
			locales: {
				root: {
					label: 'English',
					lang: 'en', // lang es obligatorio para los locales raíz
				},
				'zh-cn': {
					label: '简体中文',
					lang: 'zh-CN',
				},
			},
		}),
	],
});
```

Cuando uses una `root` locale, mantén las páginas para ese idioma directamente en `src/content/docs/` en lugar de en una carpeta de idioma dedicada. Por ejemplo, aquí están los archivos de la página de inicio para inglés y chino cuando se usa la configuración anterior:

<FileTree>

- src/
  - content/
    - docs/
      - **index.md**
      - zh-cn/
        - **index.md**

</FileTree>

#### Sitios monolingües

De forma predeterminada, Starlight es un sitio monolingüe (en inglés). Para crear un sitio de un solo idioma en otro idioma, configúralo como el `root` en tu configuración de `locales`:

```diff lang="js" {10-13}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';
export default defineConfig({
	integrations: [
		starlight({
			title: 'Mis docs',
			locales: {
				root: {
					label: '简体中文',
					lang: 'zh-CN',
				},
			},
		}),
	],
});
```

Esto te permite anular el idioma predeterminado de Starlight sin habilitar otras características de internacionalización para sitios multilingües, como el selector de idioma.

## Contenido de respaldo

Starlight espera que crees páginas equivalentes en todos tus idiomas. Por ejemplo, si tienes un archivo `en/about.md`, crea un archivo `about.md` para cada otro idioma que admitas. Esto permite que Starlight proporcione automáticamente contenido de respaldo para las páginas que aún no se han traducido.

Si no hay una traducción disponible para un idioma, Starlight mostrará a los lectores el contenido de esa página en el idioma predeterminado (establecido mediante `defaultLocale`). Por ejemplo, si aún no has creado una versión en francés de tu página Acerca de y tu idioma predeterminado es el inglés, los visitantes a `/fr/about` verán el contenido en inglés de `/en/about` con un aviso de que esta página aún no se ha traducido. Esto te ayuda a agregar contenido en tu idioma predeterminado y luego traducirlo progresivamente cuando tus traductores tengan tiempo.

## Traduce el título del sitio

Por defecto, Starlight usará el mismo título del sitio para todos los idiomas.
Si necesitas personalizar el título para cada idioma, puedes pasar un objeto a [`title`](/es/reference/configuration/#title-requerido) en las opciones de Starlight:

```diff lang="js"
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
-			title: 'Mi Documentación',
+			title: {
+				es: 'Mi Documentación',
+				'zh-CN': '我的文档',
+			},
			defaultLocale: 'es',
			locales: {
				es: { label: 'Español' },
				'zh-cn': { label: '简体中文', lang: 'zh-CN' },
			},
		}),
	],
});
```

## Traduce la UI de Starlight

import LanguagesList from '~/components/languages-list.astro';
import UIStringsList from '~/components/ui-strings-list.astro';

Además de alojar archivos de contenido traducidos, Starlight te permite traducir las etiquetas de UI predeterminadas (p. ej. el encabezado "En esta página" en la tabla de contenidos) para que tus lectores puedan experimentar tu sitio completamente en el idioma seleccionado.

<LanguagesList startsSentence /> los strings de UI traducidos se proporcionan de
forma predeterminada, y damos la bienvenida a [contribuciones para agregar más
idiomas
predeterminados](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md).

Puedes proprocionar traducciones para idiomas adicionales, o editar nuestras etiquetas predeterminadas, a través de la colección de datos `i18n`.

<Steps>

1. Configura la colección de datos `i18n` en `src/content/config.ts` si aún no está configurada:

   ```diff lang="js" ins=/, (i18nSchema)/
   // src/content/config.ts
   import { defineCollection } from 'astro:content';
   import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';

   export const collections = {
   	docs: defineCollection({ schema: docsSchema() }),
   +	i18n: defineCollection({ type: 'data', schema: i18nSchema() }),
   };
   ```

2. Crea un archivo JSON en `src/content/i18n/` para cada idioma adicional para el cual deseas proporcionar strings de traducción de la UI.
   Por ejemplo, esto agregaría archivos de traducción para árabe y chino simplificado:

   <FileTree>

   - src/
     - content/
       - i18n/
         - ar.json
         - zh-CN.json

   </FileTree>

3. Agrega traducciones para las claves que deseas traducir en los archivos JSON. Traduce solo los valores, dejando las claves en inglés (p. ej. `"search.label": "Buscar"`).

   Estos son los valores predeterminados en inglés de las cadenas existentes que se incluyen en Starlight:

   <UIStringsList />

   Los bloques de código de Starlight están impulsados por la biblioteca [Expressive Code](https://github.com/expressive-code/expressive-code).
   Puedes establecer traducciones para las cadenas de UI en el mismo archivo JSON utilizando las llaves `expressiveCode`:

   ```json
   {
   	"expressiveCode.copyButtonCopied": "Copied!",
   	"expressiveCode.copyButtonTooltip": "Copy to clipboard",
   	"expressiveCode.terminalWindowFallbackTitle": "Terminal window"
   }
   ```

   El modal de búsqueda de Starlight está impulsado por la biblioteca [Pagefind](https://pagefind.app/).
   Puedes establecer traducciones para la UI de Pagefind en el mismo archivo JSON utilizando claves `pagefind`:

   ```json
   {
   	"pagefind.clear_search": "Clear",
   	"pagefind.load_more": "Load more results",
   	"pagefind.search_label": "Search this site",
   	"pagefind.filters_label": "Filters",
   	"pagefind.zero_results": "No results for [SEARCH_TERM]",
   	"pagefind.many_results": "[COUNT] results for [SEARCH_TERM]",
   	"pagefind.one_result": "[COUNT] result for [SEARCH_TERM]",
   	"pagefind.alt_search": "No results for [SEARCH_TERM]. Showing results for [DIFFERENT_TERM] instead",
   	"pagefind.search_suggestion": "No results for [SEARCH_TERM]. Try one of the following searches:",
   	"pagefind.searching": "Searching for [SEARCH_TERM]..."
   }
   ```

</Steps>

### Extiende el esquema de traducción

Agrega claves personalizadas a los diccionarios de traducción de tu sitio estableciendo `extend` en las opciones de `i18nSchema()`.
En el siguiente ejemplo, una clave nueva, opcional `custom.label` se agrega a las claves predeterminadas:

```diff lang="js"
// src/content/config.ts
import { defineCollection, z } from 'astro:content';
import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';

export const collections = {
	docs: defineCollection({ schema: docsSchema() }),
	i18n: defineCollection({
		type: 'data',
		schema: i18nSchema({
+			extend: z.object({
+				'custom.label': z.string().optional(),
+			}),
		}),
	}),
};
```

Aprende más sobre los esquemas de colección de contenido en [“Definir un esquema de colección”](https://docs.astro.build/es/guides/content-collections/#definiendo-un-esquema-de-colección) en la documentación de Astro.

## Usar traducciones de UI

Puedes acceder a las [strings de UI integradas](/es/guides/i18n/#traduce-la-ui-de-starlight) de Starlight, así como a las cadenas de UI [definidas por el usuario](/es/guides/i18n/#extiende-el-esquema-de-traducción) y [proporcionadas por plugins](/es/reference/plugins/#injecttranslations) a través de una API unificada impulsada por [i18next](https://www.i18next.com/).
Esto incluye soporte para funciones como [interpolación](https://www.i18next.com/translation-function/interpolation) y [pluralización](https://www.i18next.com/translation-function/plurals).

En componentes de Astro, esta API está disponible como parte del [objeto global `Astro`](https://docs.astro.build/es/reference/api-reference/#astrolocals) como `Astro.locals.t`:

```astro title="example.astro"
<p dir={Astro.locals.t.dir()}>
	{Astro.locals.t('404.text')}
</p>
```

También puedes usar la API en [endpoints](https://docs.astro.build/es/guides/endpoints/), donde el objeto `locals` está disponible como parte del [contexto del endpoint](https://docs.astro.build/es/reference/api-reference/#contextlocals):

```ts title="src/pages/404.ts"
export const GET = (context) => {
	return new Response(context.locals.t('404.text'));
};
```

### Renderizar una string de UI

Renderiza strings de UI utilizando la función `locals.t()`.
Esta es una instancia de la función `t()` de i18next, que toma una clave de cadena de UI como su primer argumento y devuelve la traducción correspondiente para el idioma actual.

Por ejemplo, dado un archivo de traducción personalizado con el siguiente contenido:

```json title="src/content/i18n/en.json"
{
	"link.astro": "Astro documentation",
	"link.astro.custom": "Astro documentation for {{feature}}"
}
```

La primera string de UI se puede renderizar pasando `'link.astro'` a la función `t()`:

```astro {3}
<!-- src/components/Example.astro -->
<a href="https://docs.astro.build/">
	{Astro.locals.t('link.astro')}
</a>
<!-- Renderiza: <a href="...">Astro documentation</a> -->
```

La segunda string de UI utiliza la [sintaxis de interpolación](https://www.i18next.com/translation-function/interpolation) de i18next para el marcador `{{feature}}`.
El valor de `feature` debe establecerse en un objeto de opciones pasado como segundo argumento a `t()`:

```astro {3}
<!-- src/components/Example.astro -->
<a href="https://docs.astro.build/en/guides/astro-db/">
	{Astro.locals.t('link.astro.custom', { feature: 'Astro DB' })}
</a>
<!-- Renderiza: <a href="...">Astro documentation for Astro DB</a> -->
```

Ver la [documentación de i18next](https://www.i18next.com/overview/api#t) para obtener más información sobre cómo usar la función `t()` con interpolación, formato y más.

### APIs avanzadas

#### `t.all()`

La función `locals.t.all()` devuelve un objeto que contiene todas las strings de UI disponibles para el idioma actual.

```astro
---
// src/components/Example.astro
const allStrings = Astro.locals.t.all();
//    ^
//    {
//      "skipLink.label": "Skip to content",
//      "search.label": "Search",
//      …
//    }
---
```

#### `t.exists()`

Para comprobar si una clave de traducción existe para un idioma, utiliza la función `locals.t.exists()` con la clave de traducción como primer argumento.
Pasa un segundo argumento opcional si necesitas anular el idioma actual.

```astro
---
// src/components/Example.astro
const keyExistsInCurrentLocale = Astro.locals.t.exists('a.key');
//    ^ true
const keyExistsInFrench = Astro.locals.t.exists('another.key', { lng: 'fr' });
//    ^ false
---
```

Ver la [referencia de `exists()` en la documentación de i18next](https://www.i18next.com/overview/api#exists) para obtener más información.

#### `t.dir()`

La función `locals.t.dir()` devuelve la dirección del texto del idioma actual o de un idioma específico.

```astro
---
// src/components/Example.astro
const currentDirection = Astro.locals.t.dir();
//    ^
//    'ltr'
const arabicDirection = Astro.locals.t.dir('ar');
//    ^
//    'rtl'
---
```

Ver la [referencia de `dir()` en la documentación de i18next](https://www.i18next.com/overview/api#dir) para obtener más información.

## Acceder al idioma actual

Puedes usar [`Astro.currentLocale`](https://docs.astro.build/es/reference/api-reference/#astrocurrentlocale) para leer el idioma actual en componentes `.astro`.

El siguiente ejemplo lee el idioma actual y lo utiliza con la función [`getRelativeLocaleUrl()`](https://docs.astro.build/es/reference/modules/astro-i18n/#getrelativelocaleurl) para generar un enlace a una página Acerca de en el idioma actual:

```astro
---
// src/components/AboutLink.astro
import { getRelativeLocaleUrl } from 'astro:i18n';
---

<a href={getRelativeLocaleUrl(Astro.currentLocale ?? 'en', 'about')}>Acerca</a>
```


================================================
FILE: docs/src/content/docs/es/guides/overriding-components.mdx
================================================
---
title: Sobreescribiendo Componentes
description: Aprende como sobreescribir los componentes integrados de Starlight para agregar elementos personalizados a la interfaz de tu sitio de documentación.
---

import { Steps } from '@astrojs/starlight/components';

La UI por defecto de Starlight y las opciones de configuración están diseñadas para ser flexibles y funcionar para una variedad de contenidos. Gran parte de la apariencia predeterminada de Starlight se puede personalizar con [CSS](/es/guides/css-and-tailwind/) y [opciones de configuración](/es/guides/customization/).

Cuando necesites más de lo que es posible por defecto, Starlight soporta la construcción de tus propios componentes personalizados para extender o sobreescribir (reemplazar completamente) sus componentes por defecto.

## Cuando sobreescribir

Sobreescribir los componentes por defecto de Starlight puede ser útil cuando:

- Quieres cambiar como una parte de la UI de Starlight se ve de una manera que no es posible con [CSS personalizado](/es/guides/css-and-tailwind/).
- Quieres cambiar como una parte de la UI de Starlight se comporta.
- Quieres agregar partes adicionales de la UI junto a la UI existente de Starlight.

## Cómo sobreescribir

<Steps>

1. Escoge el componente de Starlight que quieres sobreescribir.
   Puedes encontrar una lista completa de componentes en la [Referencia de Personalización de Componentes](/es/reference/overrides/).

   :::tip
   ¿No estás seguro de qué componente necesitas sobreescribir? Usa el [Mapa Interactivo de Sobreescripciones de Starlight](https://starlight-overrides-map.netlify.app/) para descubrir los nombres de los componentes de UI de Starlight.
   :::

   Este ejemplo sobreescribe el componente [`SocialIcons`](/es/reference/overrides/#socialicons) de Starlight en la barra de navegación de la página.

2. Crea un componente de Astro para reemplazar el componente de Starlight.
   Este ejemplo renderiza un enlace de contacto.

   ```astro
   ---
   // src/components/EmailLink.astro
   import type { Props } from '@astrojs/starlight/props';
   ---

   <a href="mailto:houston@example.com">Escríbeme</a>
   ```

3. Dile a Starlight que use tu componente personalizado en la opción de configuración [`components`](/es/reference/configuration/#components) en `astro.config.mjs`:

   ```js {9-12}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'My Docs with Overrides',
   			components: {
   				// Sobreescribe el componente `SocialIcons` por defecto.
   				SocialIcons: './src/components/EmailLink.astro',
   			},
   		}),
   	],
   });
   ```

</Steps>

## Reusa un componente integrado

Puedes construir con los componentes de UI por defecto de Starlight de la misma manera que lo harías con los tuyos: importándolos y renderizándolos en tus propios componentes personalizados. Esto te permite mantener toda la UI básica de Starlight dentro de tu diseño, mientras agregas UI adicional junto a ellos.

El ejemplo a continuación muestra un componente personalizado que renderiza un enlace de correo electrónico junto con el componente `SocialIcons` por defecto:

```astro {4,8}
---
// src/components/EmailLink.astro
import type { Props } from '@astrojs/starlight/props';
import Default from '@astrojs/starlight/components/SocialIcons.astro';
---

<a href="mailto:houston@example.com">Escríbeme</a>
<Default {...Astro.props}><slot /></Default>
```

Cuando renderizas un componente integrado dentro de un componente personalizado:

- Propaga `Astro.props` dentro de él. Esto se asegura de que reciba todos los datos que necesita para renderizar.
- Agrega un [`<slot />`](https://docs.astro.build/es/core-concepts/astro-components/#slots) dentro del componente por defecto. Esto se asegura de que si el componente recibe cualquier elemento hijo, Astro sepa donde renderizarlos.

## Usa los datos de la página

Cuando sobreescribes un componente de Starlight, tu implementación personalizada recibe un objeto `Astro.props` estándar que contiene todos los datos de la página actual.
Esto te permite usar estos valores para controlar como se renderiza tu plantilla de componente.

Por ejemplo, puedes leer los valores de frontmatter de la página como `Astro.props.entry.data`. En el siguiente ejemplo, un componente de reemplazo [`PageTitle`](/es/reference/overrides/#pagetitle) usa esto para mostrar el título de la página actual:

```astro {5} "{title}"
---
// src/components/Title.astro
import type { Props } from '@astrojs/starlight/props';

const { title } = Astro.props.entry.data;
---

<h1 id="_top">{title}</h1>

<style>
	h1 {
		font-family: 'Comic Sans';
	}
</style>
```

Aprende más sobre todas las props disponibles en la [Referencia de Sobreescripciones](/es/reference/overrides/#props-de-componentes).

### Solo sobreescribe en páginas específicas

Los cambios de componentes se aplican a todas las páginas. Sin embargo, puedes renderizar condicionalmente usando los valores de `Astro.props` para determinar cuando mostrar tu UI personalizada, cuando mostrar la UI por defecto de Starlight, o incluso cuando mostrar algo completamente diferente.

En el siguiente ejemplo, un componente que sobreescribe el [`Footer`](/es/reference/overrides/#footer) de Starlight muestra "Construido con Starlight 🌟" solo en la página de inicio, y de otra manera muestra el footer por defecto en todas las otras páginas:

```astro
---
// src/components/ConditionalFooter.astro
import type { Props } from '@astrojs/starlight/props';
import Default from '@astrojs/starlight/components/Footer.astro';

const isHomepage = Astro.props.slug === '';
---

{
	isHomepage ? (
		<footer>Construido con Starlight 🌟</footer>
	) : (
		<Default {...Astro.props}>
			<slot />
		</Default>
	)
}
```

Aprende más sobre el renderizado condicional en la [Guía de Sintaxis de Astro](https://docs.astro.build/es/core-concepts/astro-syntax/#html-dinamico).


================================================
FILE: docs/src/content/docs/es/guides/pages.mdx
================================================
---
title: Páginas
description: Aprende cómo crear y gestionar las páginas de tu sitio de documentación con Starlight.
sidebar:
  order: 1
---

Starlight genera las páginas HTML de tu sitio basadas en tu contenido, con opciones flexibles proporcionadas a través del frontmatter de Markdown.
Además, los proyectos de Starlight tienen acceso completo a las [herramientas de generación de páginas de Astro](https://docs.astro.build/es/basics/astro-pages/).
Esta guía muestra cómo funciona la generación de páginas en Starlight.

## Páginas de contenido

### Formatos de archivo

Starlight admite la creación de contenido en Markdown y MDX sin necesidad de configuración.
Puedes agregar soporte para Markdoc siguiendo la [guía de “Markdoc”](/es/guides/authoring-content/#markdoc).

### Agregar páginas

Añade nuevas páginas a tu sitio creando archivos `.md` o `.mdx` en `src/content/docs/`.
Utiliza subcarpetas para organizar tus archivos y crear múltiples segmentos de ruta.

Por ejemplo, la siguiente estructura de archivos generará páginas en `example.com/hello-world` y `example.com/reference/faq`:

import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src/
  - content/
    - docs/
      - hello-world.md
      - reference/
        - faq.md

</FileTree>

### Frontmatter tipado

Todas las páginas de Starlight comparten un [conjunto común de propiedades de frontmatter personalizables](/es/reference/frontmatter/) para controlar cómo aparece la página:

```md
---
title: ¡Hola, mundo!
description: Esta es una página en mi sitio impulsado por Starlight
---
```

Si olvidas algo importante, Starlight te lo hará saber.

## Páginas personalizadas

Para casos de uso avanzados, puedes agregar páginas personalizadas creando un directorio `src/pages/`.
El directorio `src/pages/` utiliza [enrutamiento basado en archivos de Astro](https://docs.astro.build/es/basics/astro-pages/#enrutamiento-basado-en-archivos) e incluye soporte para archivos `.astro` entre otros formatos de página.
Esto es útil si necesitas construir páginas con un diseño completamente personalizado o generar una página desde una fuente de datos alternativa.

Por ejemplo, este proyecto mezcla contenido Markdown en `src/content/docs/` con rutas de Astro y HTML en `src/pages/`:

<FileTree>

- src/
  - content/
    - docs/
      - hello-world.md
  - pages/
    - custom.astro
    - archived.html

</FileTree>

Lee más en la [Guía de Páginas en la documentación de Astro](https://docs.astro.build/es/basics/astro-pages/).

### Usar el diseño de Starlight en páginas personalizadas

Para usar el diseño de Starlight en páginas personalizadas, envuelve el contenido de tu página con el componente `<StarlightPage />`.
Esto puede ser útil si estás generando contenido dinámicamente pero aún quieres usar el diseño de Starlight.

```astro
---
// src/pages/custom-page/example.astro
import StarlightPage from '@astrojs/starlight/components/StarlightPage.astro';
import CustomComponent from './CustomComponent.astro';
---

<StarlightPage frontmatter={{ title: 'Mi página personalizada' }}>
	<p>Esta es una página personalizada con un componente personalizado:</p>
	<CustomComponent />
</StarlightPage>
```

#### Props

El componente `<StarlightPage />` acepta las siguientes props.

##### `frontmatter` (requerido)

**tipo:** `StarlightPageFrontmatter`

Establece las [propiedades de frontmatter](/es/reference/frontmatter/) para esta página, similar al frontmatter en las páginas de Markdown.
La propiedad [`title`](/es/reference/frontmatter/#title-requerido) es requerida y todas las demás propiedades son opcionales.

Las siguientes propiedades difieren del frontmatter de Markdown:

- La propiedad [`slug`](/es/reference/frontmatter/#slug) no es compatible y se establece automáticamente en función de la URL de la página personalizada.
- La opción [`editUrl`](/es/reference/frontmatter/#editurl) requiere una URL para mostrar un enlace de edición.
- La propiedad frontmatter [`sidebar`](/es/reference/frontmatter/#sidebar) para personalizar cómo aparece la página en [grupos de enlaces autogenerados](/es/reference/configuration/#sidebar) no está disponible. Las páginas que utilizan el componente `<StarlightPage />` no forman parte de una colección y no pueden ser agregadas a un grupo de barra lateral autogenerado.
- La opción [`draft`](/es/reference/frontmatter/#draft) solo muestra un [aviso](/es/reference/overrides/#draftcontentnotice) de que la página es un borrador, pero no la excluye automáticamente de las compilaciones de producción.

##### `sidebar`

**tipo:** [`SidebarItem[]`](/es/reference/configuration/#sidebaritem)  
**por defecto:** la barra lateral generada basada en la [configuración global de `sidebar`](/es/reference/configuration/#sidebar)

Proporciona una barra lateral de navegación personalizada para esta página.
Si no se establece, la página usará la barra lateral global predeterminada.

Por ejemplo, la siguiente página anula la barra lateral predeterminada con un enlace a la página de inicio y un grupo de enlaces a varias otras páginas personalizadas.

```astro {3-13}
<StarlightPage
	frontmatter={{ title: 'Orion' }}
	sidebar={[
		{ label: 'Home', link: '/' },
		{
			label: 'Constelaciones',
			items: [
				{ label: 'Andromeda', link: '/andromeda/' },
				{ label: 'Orion', link: '/orion/', isCurrent: true },
				{ label: 'Osa Menor', link: '/ursa-minor/', badge: 'Stub' },
			],
		},
	]}
>
	Contenido de la página
</StarlightPage>
```

Ver la guía [“Navegación de la barra lateral”](/es/guides/sidebar/) para obtener más información sobre las opciones disponibles para personalizar la barra lateral.

##### `hasSidebar`

**tipo:** `boolean`  
**por defecto:** `false` si [`frontmatter.template`](/es/reference/frontmatter/#template) es `'splash'`, de lo contrario `true`

Controla si la barra lateral debe mostrarse en esta página o no.

##### `headings`

**tipo:** `{ depth: number; slug: string; text: string }[]`  
**por defecto:** `[]`

Proporciona un array de todos los encabezados en esta página.
Starlight generará la tabla de contenidos de la página a partir de estos encabezados si se proporcionan.

##### `dir`

**tipo:** `'ltr' | 'rtl'`  
**por defecto:** la dirección de escritura para la configuración regional actual

Establece la dirección de escritura para el contenido de esta página.

##### `lang`

**tipo:** `string`  
**por defecto:** el idioma de la configuración regional actual

Establece la etiqueta de idioma BCP-47 para el contenido de esta página, por ejemplo, `en`, `zh-CN` o `pt-BR`.

##### `isFallback`

**tipo:** `boolean`  
**por defecto:** `false`

Indica si esta página está utilizando [contenido alternativo](/es/guides/i18n/#contenido-de-respaldo) porque no hay traducción para el idioma actual.


================================================
FILE: docs/src/content/docs/es/guides/project-structure.mdx
================================================
---
title: Estructura del proyecto
description: Aprende cómo organizar archivos en tu proyecto Starlight
---

Esta guía te mostrará cómo se organiza un proyecto de Starlight y qué hacen los diferentes archivos en tu proyecto.

Los proyectos de Starlight generalmente siguen la misma estructura de archivos y directorios que otros proyectos de Astro. Para obtener más detalles, consulta la documentación sobre [la estructura del proyecto de Astro](https://docs.astro.build/es/core-concepts/project-structure/).

## Archivos y directorios

- `astro.config.mjs` — El archivo de configuración de Astro; incluye la integración y configuración de Starlight.
- `src/content/config.ts` — El archivo de configuración de las colecciones de contenido; añade los esquemas del frontmatter de Starlight a tu proyecto.
- `src/content/docs/` — Archivos de contenido. Starlight convierte cada archivo `.md`, `.mdx` o `.mdoc` en este directorio en una página de tu sitio.
- `src/content/i18n/` (opcional) — Datos de traducción para soportar la [internacionalización](/es/guides/i18n/).
- `src/` — Otros códigos fuente y archivos (componentes, estilos, imágenes, etc.) para tu proyecto.
- `public/` — Recursos estáticos (fuentes, favicon, PDF, etc.) que no serán procesados por Astro.

## Ejemplo de contenido de un proyecto

Un directorio de proyecto de Starlight podría lucir así:

import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- public/
  - favicon.svg
- src/
  - assets/
    - logo.svg
    - screenshot.jpg
  - components/
    - CustomButton.astro
    - InteractiveWidget.jsx
  - content/
    - docs/
      - guides/
        - 01-getting-started.md
        - 02-advanced.md
      - index.mdx
    - config.ts
  - env.d.ts
- astro.config.mjs
- package.json
- tsconfig.json

</FileTree>


================================================
FILE: docs/src/content/docs/es/guides/route-data.mdx
================================================
---
title: Datos de Ruta
description: Aprende cómo se utiliza el modelo de datos de página de Starlight para renderizar tus páginas y cómo puedes personalizarlo.
---

import { Steps } from '@astrojs/starlight/components';

Cuando Starlight renderiza una página en tu documentación, primero crea un objeto de datos de ruta para representar lo que hay en esa página.
Esta guía explica cómo se generan los datos de ruta, cómo usarlos y cómo puedes personalizarlos para modificar el comportamiento predeterminado de Starlight.

Consulta la [“Referencia de los Datos de Ruta”](/es/reference/route-data/) para obtener una lista completa de las propiedades disponibles.

## ¿Qué son los datos de ruta?

Los datos de ruta de Starlight son un objeto que contiene toda la información necesaria para renderizar una sola página.
Incluye información de la página actual, así como datos generados a partir de tu configuración de Starlight.

## Uso de los datos de ruta

Todos los componentes de Starlight utilizan los datos de ruta para decidir qué renderizar en cada página.
Por ejemplo, la cadena [`siteTitle`](/es/reference/route-data/#sitetitle) se utiliza para mostrar el título del sitio y el array [`sidebar`](/es/reference/route-data/#sidebar) se utiliza para renderizar la navegación global de la barra lateral.

Puedes acceder a estos datos desde la variable global `Astro.locals.starlightRoute` en los componentes de Astro:

```astro title="ejemplo.astro" {2}
---
const { siteTitle } = Astro.locals.starlightRoute;
---

<p>El título de este sitio es “{siteTitle}”</p>
```

Esto puede ser útil, por ejemplo, al construir [sustituciones de componentes](/es/guides/overriding-components/) para personalizar lo que se muestra.

## Personalización de los datos de ruta

Los datos de ruta de Starlight funcionan de forma predeterminada y no requieren ninguna configuración.
Sin embargo, para casos de uso avanzados, es posible que desees personalizar los datos de ruta para algunas o todas las páginas para modificar cómo se muestra tu sitio.

Este es un concepto similar a las [sustituciones de componentes](/es/guides/overriding-components/), pero en lugar de modificar cómo Starlight renderiza tus datos, modificas los datos que Starlight renderiza.

### Cuándo personalizar los datos de ruta

La personalización de los datos de ruta puede ser útil cuando deseas modificar cómo Starlight procesa tus datos de una manera que no es posible con las opciones de configuración existentes.

Por ejemplo, es posible que desees filtrar elementos de la barra lateral o personalizar los títulos de páginas específicas.
Cambios como este no requieren modificar los componentes predeterminados de Starlight, solo los datos que se pasan a esos componentes.

### Cómo personalizar los datos de ruta

Puedes personalizar los datos de ruta utilizando una forma especial de “middleware”.
Esta es una función que se llama cada vez que Starlight renderiza una página y puede modificar los valores del objeto de datos de ruta.

<Steps>

1.  Crea un nuevo archivo que exporte una función `onRequest` utilizando la utilidad `defineRouteMiddleware()` de Starlight:

    ```ts
    // src/routeData.ts
    import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

    export const onRequest = defineRouteMiddleware(() => {});
    ```

2.  Indica a Starlight dónde se encuentra tu archivo de middleware de datos de ruta en `astro.config.mjs`:

    ```js ins={9}
    // astro.config.mjs
    import { defineConfig } from 'astro/config';
    import starlight from '@astrojs/starlight';

    export default defineConfig({
    	integrations: [
    		starlight({
    			title: 'Mi increíble sitio de documentación',
    			routeMiddleware: './src/routeData.ts',
    		}),
    	],
    });
    ```

3.  Actualiza tu función `onRequest` para modificar los datos de ruta.

    El primer argumento que recibirá tu middleware es el [objeto `context` de Astro](https://docs.astro.build/es/reference/api-reference/).
    Este contiene información completa sobre la renderización de la página actual, incluyendo la URL actual y las `locals`.

    En este ejemplo, vamos a hacer que nuestra documentación sea más emocionante añadiendo un signo de exclamación al final del título de cada página.

    ```ts
    // src/routeData.ts
    import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

    export const onRequest = defineRouteMiddleware((context) => {
    	// Obtiene la entrada de la colección de contenido para esta página.
    	const { entry } = context.locals.starlightRoute;
    	// Actualiza el título para añadir un signo de exclamación.
    	entry.data.title = entry.data.title + '!';
    });
    ```

</Steps>

#### Múltiple middleware de ruta

Starlight también admite proporcionar múltiples middleware.
Establece `routeMiddleware` en un array de rutas para añadir más de un manejador de middleware:

```js {9}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Mi sitio con múltiples middleware',
			routeMiddleware: ['./src/middleware-one.ts', './src/middleware-two.ts'],
		}),
	],
});
```

#### Esperando middleware de ruta posterior

Para esperar a que se ejecute el middleware posterior en la pila antes de ejecutar tu código, puedes usar `await` en la función de callback `next()` que se pasa como segundo argumento a tu función de middleware.
Esto puede ser útil para esperar a que se ejecute el middleware de un plugin antes de realizar cambios, por ejemplo.

```ts "next" "await next();"
// src/routeData.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

export const onRequest = defineRouteMiddleware(async (context, next) => {
	// Espera a que se ejecute el middleware posterior.
	await next();
	// Modifica los datos de ruta.
	const { entry } = context.locals.starlightRoute;
	entry.data.title = entry.data.title + '!';
});
```


================================================
FILE: docs/src/content/docs/es/guides/sidebar.mdx
================================================
---
title: Barra Lateral de Navegación
description: Aprende a configurar y personalizar los enlaces de navegación de la barra lateral de tu sitio Starlight.
---

import { FileTree } from '@astrojs/starlight/components';
import SidebarPreview from '~/components/sidebar-preview.astro';

Una barra lateral bien organizada es clave para una buena documentación, ya que es una de las principales formas en que los usuarios navegarán por su sitio. Starlight proporciona un conjunto completo de opciones para personalizar el diseño y el contenido de tu barra lateral.

## Barra lateral predeterminada

Por defecto, Starlight generará automáticamente una barra lateral basada en la estructura del sistema de archivos de tu documentación, utilizando la propiedad `title` de cada archivo como entrada de la barra lateral.

Por ejemplo, dada la siguiente estructura de archivos:

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - andromeda.md
        - orion.md
      - stars/
        - betelgeuse.md

</FileTree>

La siguiente barra lateral se generará automáticamente:

<SidebarPreview
	config={[
		{
			label: 'constellations',
			items: [
				{ label: 'Andrómeda', link: '' },
				{ label: 'Orión', link: '' },
			],
		},
		{
			label: 'stars',
			items: [{ label: 'Betelgeuse', link: '' }],
		},
	]}
/>

Aprende más sobre las barras laterales generadas automáticamente en la sección [grupos autogenerados](#grupos-autogenerados).

## Agregar enlaces y grupos de enlaces

Para configurar los enlaces de tu barra lateral y grupos de enlaces (dentro de un encabezado plegable), usa la propiedad [`starlight.sidebar`](/es/reference/configuration/#sidebar) en `astro.config.mjs`.

Combinando enlaces y grupos, puedes crear una amplia variedad de diseños de barra lateral.

### Enlaces internos

Agrega un enlace a una página en `src/content/docs/` usando un objeto con la propiedad `slug`.
El título de la página vinculada se utilizará como etiqueta de forma predeterminada.

Por ejemplo, con la siguiente configuración:

```js "slug:"
starlight({
	sidebar: [
		{ slug: 'constellations/andromeda' },
		{ slug: 'constellations/orion' },
	],
});
```

Y la siguiente estructura de archivos:

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - andromeda.md
        - orion.md

</FileTree>

La siguiente barra lateral se generará automáticamente:

<SidebarPreview
	config={[
		{ label: 'Andrómeda', link: '' },
		{ label: 'Orión', link: '' },
	]}
/>

Para sobreescribir los valores inferidos del frontmatter de una página vinculada, puedes agregar las propiedades `label`, [`translations`](#internacionalización) y [`attrs`](#atributos-html-personalizados).

Ve [“Personalización de enlaces autogenerados”](#personalización-de-enlaces-autogenerados-en-el-frontmatter) para más detalles sobre cómo controlar la apariencia de la barra lateral desde el frontmatter de la página.

#### Atajo para enlaces internos

Los enlaces internos también se pueden especificar proporcionando solo un string para el slug de la página como un atajo.

Por ejemplo, la siguiente configuración es equivalente a la configuración anterior, que usaba `slug`:

```js "slug:"
starlight({
	sidebar: ['constellations/andromeda', 'constellations/orion'],
});
```

### Otros enlaces

Agrega un enlace a una página externa o un enlace que no sea de documentación usando un objeto con las propiedades `label` y `link`.

```js "label:" "link:"
starlight({
	sidebar: [
		// Un enlace a una página que no sea de documentación en este sitio.
		{ label: 'Tienda de Meteoritos', link: '/shop/' },
		// Un enlace externo al sitio web de la NASA.
		{ label: 'NASA', link: 'https://www.nasa.gov/' },
	],
});
```

La configuración anterior genera la siguiente barra lateral:

<SidebarPreview
	config={[
		{ label: 'Tienda de Meteoritos', link: '' },
		{ label: 'NASA', link: 'https://www.nasa.gov/' },
	]}
/>

### Grupos

Puedes agregar una estructura a tu barra lateral agrupando enlaces relacionados bajo un encabezado plegable.
Los Grupos pueden contener tanto enlaces como otros subgrupos.

Agrega un grupo usando un objeto con las propiedades `label` y `items`.
La `label` se utilizará como encabezado del grupo.
Agrega enlaces o subgrupos al arreglo `items`.

```js /^\s*(label:|items:)/
starlight({
	sidebar: [
		// Un grupo de enlaces etiquetado "Constelaciones".
		{
			label: 'Constelaciones',
			items: [
				'constellations/carina',
				'constellations/centaurus',
				// Un grupo anidado de enlaces para constelaciones estacionales.
				{
					label: 'Estacional',
					items: [
						'constellations/andromeda',
						'constellations/orion',
						'constellations/ursa-minor',
					],
				},
			],
		},
	],
});
```

La configuración anterior genera la siguiente barra lateral:

<SidebarPreview
	config={[
		{
			label: 'Constelaciones',
			items: [
				{ label: 'Carina', link: '' },
				{ label: 'Centaurus', link: '' },
				{
					label: 'Estacional',
					items: [
						{ label: 'Andrómeda', link: '' },
						{ label: 'Orión', link: '' },
						{ label: 'Osa Menor', link: '' },
					],
				},
			],
		},
	]}
/>

### Grupos autogenerados

Starlight puede generar automáticamente un grupo en tu barra lateral basado en un directorio de tu documentación.
Esto es útil cuando no deseas ingresar manualmente cada elemento de la barra lateral en un grupo.

Por defecto, las páginas se ordenan en orden alfabético según el [`slug`](/es/reference/overrides/#slug) del archivo.

Agrega un grupo autogenerado usando un objeto con las propiedades `label` y `autogenerate`. Tu configuración `autogenerate` debe especificar el `directory` para usar en las entradas de la barra lateral. Por ejemplo, con la siguiente configuración:

```js "label:" "autogenerate:"
starlight({
	sidebar: [
		{
			label: 'Constelaciones',
			// Un grupo de enlaces autogenerados para el directorio 'constellations'.
			autogenerate: { directory: 'constellations' },
		},
	],
});
```

Y la siguiente estructura de archivos:

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - carina.md
        - centaurus.md
        - seasonal/
          - andromeda.md

</FileTree>

La siguiente barra lateral se generará automáticamente:

<SidebarPreview
	config={[
		{
			label: 'Constelaciones',
			items: [
				{ label: 'Carina', link: '' },
				{ label: 'Centaurus', link: '' },
				{
					label: 'seasonal',
					items: [{ label: 'Andrómeda', link: '' }],
				},
			],
		},
	]}
/>

## Personalización de enlaces autogenerados en el frontmatter

Usa el campo [`sidebar`](/es/reference/frontmatter/#sidebar) en las páginas individuales para personalizar los enlaces autogenerados.

Las opciones del frontmatter de la barra lateral te permiten establecer un [etiqueta personalizada](/es/reference/frontmatter/#label) o agregar una [insignia](/es/reference/frontmatter/#badge) a un enlace, [ocultar](/es/reference/frontmatter/#hidden) un enlace de la barra lateral o definir un [peso de ordenación personalizado](/es/reference/frontmatter/#order).

```md "sidebar:"
---
title: Mi página
sidebar:
  # Configura una etiqueta personalizada para el enlace
  label: Etiqueta personalizada de la barra lateral
  # Establece un orden personalizado para el enlace (los números más bajos se muestran más arriba)
  order: 2
  # Agrega una insignia al enlace
  badge:
    text: Nuevo
    variant: tip
---
```

Un grupo autogenerado que incluye una página con el frontmatter anterior generará la siguiente barra lateral:

<SidebarPreview
	config={[
		{
			label: 'Guías',
			items: [
				{ label: 'Una página', link: '' },
				{
					label: 'Etiqueta personalizada de la barra lateral',
					link: '',
					badge: { text: 'Nuevo', variant: 'tip' },
				},
				{ label: 'Otra página', link: '' },
			],
		},
	]}
/>

:::note
El frontmatter `sidebar` solo se utiliza para enlaces en grupos autogenerados y enlaces de documentos definidos con la propiedad `slug`. No se aplica a los enlaces definidos con la propiedad `link`.
:::

## Insignias

Los enlaces, grupos y grupos autogenerados también pueden incluir una propiedad `badge` para mostrar una insignia junto a la etiqueta del enlace.

```js {9,16}
starlight({
	sidebar: [
		{
			label: 'Estrellas',
			items: [
				// Un enlace con una insignia "Supergigante".
				{
					slug: 'stars/persei',
					badge: 'Supergigante',
				},
			],
		},
		// Un grupo autogenerado con una insignia "Obsoleto".
		{
			label: 'Moons',
			badge: 'Obsoleto',
			autogenerate: { directory: 'moons' },
		},
	],
});
```

La configuración anterior genera la siguiente barra lateral:

<SidebarPreview
	config={[
		{
			label: 'Estrellas',
			items: [
				{
					label: 'Persei',
					link: '',
					badge: { text: 'Supergigante', variant: 'default' },
				},
			],
		},
		{
			label: 'Lunas',
			badge: { text: 'Obsoleto', variant: 'default' },
			items: [
				{
					label: 'Ío',
					link: '',
				},
				{
					label: 'Europa',
					link: '',
				},
				{
					label: 'Ganímedes',
					link: '',
				},
			],
		},
	]}
/>

### Variantes de insignia y estilos personalizados

Personaliza el estilo de la insignia usando un objeto con las propiedades `text`, `variant` y `class`.

La propiedad `text` representa el contenido a mostrar (por ejemplo, "Nuevo").
Por defecto, la insignia usará el color de acento de tu sitio. Para usar un estilo de insignia integrado, establece la propiedad `variant` en uno de los siguientes valores: `note`, `tip`, `danger`, `caution` o `success`.

Opcionalmente, puedes crear un estilo de insignia personalizado estableciendo la propiedad `class` en un nombre de clase CSS.

```js {9}
starlight({
	sidebar: [
		{
			label: 'Estrellas',
			items: [
				// Un enlace con una insignia "Stub" amarilla.
				{
					slug: 'stars/sirius',
					badge: { text: 'Stub', variant: 'caution' },
				},
			],
		},
	],
});
```

La configuración anterior genera la siguiente barra lateral:

<SidebarPreview
	config={[
		{
			label: 'Estrellas',
			items: [
				{
					label: 'Sirio',
					link: '',
					badge: { text: 'Stub', variant: 'caution' },
				},
			],
		},
	]}
/>

## Atributos HTML personalizados

Los enlaces también pueden incluir una propiedad `attrs` para agregar atributos HTML personalizados al elemento de enlace.

En el siguiente ejemplo, `attrs` se usa para agregar un atributo `target="_blank"`, de modo que el enlace se abra en una nueva pestaña, y para aplicar un atributo `style` personalizado para poner en cursiva la etiqueta del enlace:

```js {9}
starlight({
	sidebar: [
		{
			label: 'Recursos',
			items: [
				{
					label: 'NASA',
					link: 'https://www.nasa.gov/',
					attrs: { target: '_blank', style: 'font-style: italic' },
				},
			],
		},
	],
});
```

La configuración anterior genera la siguiente barra lateral:

<SidebarPreview
	config={[
		{
			label: 'Recursos',
			items: [
				{
					label: 'NASA',
					link: 'https://www.nasa.gov/',
					attrs: {
						target: '_blank',
						style: 'font-style: italic',
					},
				},
			],
		},
	]}
/>

## Internacionalización

Usa la propiedad `translations` en las entradas de enlace y grupo para traducir la etiqueta del enlace o grupo para cada idioma compatible especificando una etiqueta de idioma [BCP-47](https://www.w3.org/International/questions/qa-choosing-language-tags), p. ej. `"en"`, `"ar"`, o `"zh-CN"`, como clave, y la etiqueta traducida como valor.

La propiedad `label` se utilizará para el idioma predeterminado y para los idiomas sin traducción.

```js {5-7,11-13,18-20}
starlight({
	sidebar: [
		{
			label: 'Constelaciones',
			translations: {
				'pt-BR': 'Constelações',
			},
			items: [
				{
					label: 'Andrómeda',
					translations: {
						'pt-BR': 'Andrômeda',
					},
					slug: 'constellations/andromeda',
				},
				{
					label: 'Escorpio',
					translations: {
						'pt-BR': 'Escorpião',
					},
					slug: 'constellations/scorpius',
				},
			],
		},
	],
});
```

Navegar por la documentación en portugués de Brasil generará la siguiente barra lateral:

<SidebarPreview
	config={[
		{
			label: 'Constelação',
			items: [
				{ label: 'Andrômeda', link: '' },
				{ label: 'Escorpião', link: '' },
			],
		},
	]}
/>

### Internacionalización con enlaces internos

[Los Enlaces internos](#enlaces-internos) utilizarán automáticamente los títulos de página traducidos del frontmatter de contenido de forma predeterminada:

```js {9-10}
starlight({
	sidebar: [
		{
			label: 'Constellations',
			translations: {
				'pt-BR': 'Constelações',
			},
			items: [
				{ slug: 'constellations/andromeda' },
				{ slug: 'constellations/scorpius' },
			],
		},
	],
});
```

Navegando por la documentación en portugués de Brasil generará la siguiente barra lateral:

<SidebarPreview
	config={[
		{
			label: 'Constelações',
			items: [
				{ label: 'Andrômeda', link: '' },
				{ label: 'Escorpião', link: '' },
			],
		},
	]}
/>
En sitios multilingües, el valor de `slug` no incluye la parte del idioma de la
URL. Por ejemplo, si tienes páginas en `en/intro` y `pt-br/intro`, el slug es
`intro` al configurar la barra lateral.

### Internacionalización con insignias

Para [insignias](#insignias), la propiedad `text` puede ser un string, o para sitios multilingües, un objeto con valores para cada idioma diferente.
Cuando se usa la forma de objeto, las claves deben ser etiquetas [BCP-47](https://www.w3.org/International/questions/qa-choosing-language-tags) (p. ej. `en`, `ar`, o `zh-CN`):

```js {11-16}
starlight({
	sidebar: [
		{
			label: 'Constellations',
			translations: {
				'pt-BR': 'Constelações',
			},
			items: [
				{
					slug: 'constellations/andromeda',
					badge: {
						text: {
							en: 'New',
							'pt-BR': 'Novo',
						},
					},
				},
			],
		},
	],
});
```

Navegando por la documentación en portugués de Brasil generará la siguiente barra lateral:

<SidebarPreview
	config={[
		{
			label: 'Constelações',
			items: [
				{
					label: 'Andrômeda',
					link: '',
					badge: { text: 'Novo', variant: 'default' },
				},
			],
		},
	]}
/>

## Grupos colapsables

Los grupos de enlaces pueden colapsarse por defecto estableciendo la propiedad `collapsed` en `true`.

```js {5-6}
starlight({
	sidebar: [
		{
			label: 'Constelaciones',
			// Collapsa el grupo de forma predeterminada.
			collapsed: true,
			items: ['constellations/andromeda', 'constellations/orion'],
		},
	],
});
```

La configuración anterior genera la siguiente barra lateral:

<SidebarPreview
	config={[
		{
			label: 'Constelaciones',
			collapsed: true,
			items: [
				{ label: 'Andrómeda', link: '' },
				{ label: 'Orion', link: '' },
			],
		},
	]}
/>

[Grupos autogenerados](#grupos-autogenerados) respetan el valor `collapsed` de su grupo padre:

```js {5-6}
starlight({
	sidebar: [
		{
			label: 'Constelaciones',
			// Colapsa el grupo y sus subgrupos autogenerados de forma predeterminada.
			collapsed: true,
			autogenerate: { directory: 'constellations' },
		},
	],
});
```

La configuración anterior genera la siguiente barra lateral:

<SidebarPreview
	config={[
		{
			label: 'Constelaciones',
			collapsed: true,
			items: [

    			{ label: 'Carina', link: '' },
    			{ label: 'Centaurus', link: '' },
    			{
    				label: 'seasonal',
    				collapsed: true,
    				items: [{ label: 'Andrómeda', link: '' }],
    			},
    		],
    	},
    ]}

/>

Este comportamiento puede remplazarse definiendo la propiedad `autogenerate.collapsed`.

```js {5-7} "collapsed: true"
starlight({
	sidebar: [
		{
			label: 'Constelaciones',
			// No colapsa el grupo "Constelattions" pero colapsa sus
			// subgrupos autogenerados.
			collapsed: false,
			autogenerate: { directory: 'constellations', collapsed: true },
		},
	],
});
```

La configuración anterior genera la siguiente barra lateral:

<SidebarPreview
	config={[
		{
			label: 'Constelaciones',
			items: [
				{ label: 'Carina', link: '' },
				{ label: 'Centaurus', link: '' },
				{
					label: 'seasonal',
					collapsed: true,
					items: [{ label: 'Andrómeda', link: '' }],
				},
			],
		},
	]}
/>


================================================
FILE: docs/src/content/docs/es/guides/site-search.mdx
================================================
---
title: Búsqueda en el sitio
description: Aprende sobre las funciones de búsqueda de sitios integradas de Starlight y cómo personalizarlas.
---

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

Por defecto, los sitios de Starlight incluyen una búsqueda de texto completo impulsada por [Pagefind](https://pagefind.app/), que es una herramienta de búsqueda rápida y de bajo ancho de banda para sitios estáticos.

No es necesaria ninguna configuración para habilitar la búsqueda. Construye e implementa tu sitio, luego usa la barra de búsqueda en el encabezado del sitio para encontrar contenido.

## Ocultar contenido en los resultados de búsqueda

### Excluye una página

Para excluir una página del índice de búsqueda, agrega [`pagefind: false`](/es/reference/frontmatter/#pagefind) al frontmatter de la página:

```md title="src/content/docs/not-indexed.md" ins={3}
---
title: Contenido para ocultar de la búsqueda
pagefind: false
---
```

### Excluye parte de una página

Pagefind ignorará el contenido dentro de un elemento con el atributo [`data-pagefind-ignore`](https://pagefind.app/docs/indexing/#removing-individual-elements-from-the-index).

En el siguiente ejemplo, el primer párrafo se mostrará en los resultados de búsqueda, pero el contenido del `<div>` no:

```md title="src/content/docs/partially-indexed.md" ins="data-pagefind-ignore"
---
title: Página parcialmente indexada
---

Este texto será descubrible a través de la búsqueda.

<div data-pagefind-ignore>

Este texto estará oculto de la búsqueda.

</div>
```

## Proveedores de búsqueda alternativos

### Algolia DocSearch

Si tienes acceso al [programa DocSearch de Algolia](https://docsearch.algolia.com/) y quieres usarlo en lugar de Pagefind, puedes usar el plugin oficial Starlight DocSearch.

<Steps>

1. Instala `@astrojs/starlight-docsearch`:

   <Tabs syncKey="pkg">

   <TabItem label="npm">

   ```sh
   npm install @astrojs/starlight-docsearch
   ```

   </TabItem>

   <TabItem label="pnpm">

   ```sh
   pnpm add @astrojs/starlight-docsearch
   ```

   </TabItem>

   <TabItem label="Yarn">

   ```sh
   yarn add @astrojs/starlight-docsearch
   ```

   </TabItem>

   </Tabs>

2. Agrega DocSearch a tu configuración de Starlight [`plugins`](/es/reference/configuration/#plugins) en `astro.config.mjs` y pásale tu `appId`, `apiKey` e `indexName` de Algolia:

   ```js ins={4,10-16}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';
   import starlightDocSearch from '@astrojs/starlight-docsearch';

   export default defineConfig({
   	integrations: [
   		starlight({
        title: 'Sitio con DocSearch',
   			plugins: [
   				starlightDocSearch({
            appId: 'TU_ID_DE_APP'
            apiKey: 'TU_LLAVE_DE_API_DE_BÚSQUEDA'
            indexName: 'TU_NOMBRE_DE_ÍNDICE',
   				}),
   			],
   		}),
   	],
   });
   ```

</Steps>

Con esta configuración actualizada, la barra de búsqueda de tu sitio ahora abrirá un modal de Algolia en lugar del modal de búsqueda predeterminado.

#### Traduciendo la UI de DocSearch

DocSearch solo proporciona cadenas de UI en inglés de forma predeterminada.
Para agregar traducciones de la UI al modal en otros idiomas, usa el [sistema de internacionalización](/es/guides/i18n/#traduce-la-ui-de-starlight) incorporado de Starlight.

<Steps>

1. Extiende la definición de la colección de contenido `i18n` de Starlight con el esquema de DocSearch en `src/content/config.ts`:

   ```js ins={4} ins=/{ extend: .+ }/
   // src/content/config.ts
   import { defineCollection } from 'astro:content';
   import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';
   import { docSearchI18nSchema } from '@astrojs/starlight-docsearch/schema';

   export const collections = {
   	docs: defineCollection({ schema: docsSchema() }),
   	i18n: defineCollection({
   		type: 'data',
   		schema: i18nSchema({ extend: docSearchI18nSchema() }),
   	}),
   };
   ```

2. Agrega traducciones a tus archivos JSON en `src/content/i18n/`.

   Estas son las predeterminadas en inglés que usa DocSearch:

   ```json title="src/content/i18n/en.json"
   {
   	"docsearch.searchBox.resetButtonTitle": "Clear the query",
   	"docsearch.searchBox.resetButtonAriaLabel": "Clear the query",
   	"docsearch.searchBox.cancelButtonText": "Cancel",
   	"docsearch.searchBox.cancelButtonAriaLabel": "Cancel",
   	"docsearch.searchBox.searchInputLabel": "Search",

   	"docsearch.startScreen.recentSearchesTitle": "Recent",
   	"docsearch.startScreen.noRecentSearchesText": "No recent searches",
   	"docsearch.startScreen.saveRecentSearchButtonTitle": "Save this search",
   	"docsearch.startScreen.removeRecentSearchButtonTitle": "Remove this search from history",
   	"docsearch.startScreen.favoriteSearchesTitle": "Favorite",
   	"docsearch.startScreen.removeFavoriteSearchButtonTitle": "Remove this search from favorites",

   	"docsearch.errorScreen.titleText": "Unable to fetch results",
   	"docsearch.errorScreen.helpText": "You might want to check your network connection.",

   	"docsearch.footer.selectText": "to select",
   	"docsearch.footer.selectKeyAriaLabel": "Enter key",
   	"docsearch.footer.navigateText": "to navigate",
   	"docsearch.footer.navigateUpKeyAriaLabel": "Arrow up",
   	"docsearch.footer.navigateDownKeyAriaLabel": "Arrow down",
   	"docsearch.footer.closeText": "to close",
   	"docsearch.footer.closeKeyAriaLabel": "Escape key",
   	"docsearch.footer.searchByText": "Search by",

   	"docsearch.noResultsScreen.noResultsText": "No results for",
   	"docsearch.noResultsScreen.suggestedQueryText": "Try searching for",
   	"docsearch.noResultsScreen.reportMissingResultsText": "Believe this query should return results?",
   	"docsearch.noResultsScreen.reportMissingResultsLinkText": "Let us know."
   }
   ```

</Steps>


================================================
FILE: docs/src/content/docs/es/index.mdx
================================================
---
title: Starlight 🌟 Construye sitios de documentación con Astro
head:
  - tag: title
    content: Starlight 🌟 Construye sitios de documentación con Astro
description: Starlight te ayuda a construir sitios web de documentación hermosos y de alto rendimiento utilizando Astro.
template: splash
editUrl: false
lastUpdated: false
hero:
  title: Haz que tus docs brillen con Starlight
  tagline: Todo lo que necesitas para construir un sitio web de documentación estelar. Rápido, accesible y fácil de usar.
  image:
    file: ~/assets/hero-star.webp
  actions:
    - text: Empezar
      icon: right-arrow
      link: /es/getting-started/
    - text: Ver en GitHub
      icon: external
      variant: minimal
      link: https://github.com/withastro/starlight
---

import { CardGrid, Card } from '@astrojs/starlight/components';
import AboutAstro from '~/components/about-astro.astro';
import TestimonialGrid from '~/components/testimonial-grid.astro';
import Testimonial from '~/components/testimonial.astro';

<CardGrid stagger>
	<Card title="Documentación que deleita" icon="open-book">
		Incluye: navegación del sitio, búsqueda, internacionalización, SEO,
		tipografía fácil de leer, resaltado de código, modo oscuro y mucho más.
	</Card>
	<Card title="Impulsado por Astro" icon="rocket">
		Aprovecha todo el poder y rendimiento de Astro. Amplía Starlight con tus
		integraciones y bibliotecas favoritas de Astro.
	</Card>
	<Card title="Markdown, Markdoc y MDX" icon="document">
		Lleva tu lenguaje de marcado favorito. Starlight te ofrece validación de
		frontmatter integrada con seguridad de tipos en TypeScript.
	</Card>
	<Card title="Lleva tus propios componentes de UI" icon="puzzle">
		Starlight se ofrece como una solución completa para la documentación,
		independiente de cualquier framework. Puedes extenderlo con React, Vue,
		Svelte, Solid y otros.
	</Card>
</CardGrid>

<TestimonialGrid title="Lo que nuestros usuarios opinan">
  <Testimonial
    name="Rachel"
    handle="rachelnabors"
    cite="https://twitter.com/astrodotbuild/status/1724934718745915558"
  >
	El equipo de Astro ha EVOLUCIONADO la forma en que se pueden hacer la documentación y puedes obtenerlo todo directamente con tu proyecto Starlight.
  </Testimonial>
  <Testimonial
    name="Flavio"
    handle="flaviocopes"
    cite="https://twitter.com/flaviocopes/status/1738237658717905108"
  >
	La plantilla oficial de Astro Starlight es una herramienta realmente increíble para construir un sitio web de documentación
  </Testimonial>
  <Testimonial
    name="Tomek"
    handle="sulco"
    cite="https://twitter.com/sulco/status/1735610348730802342"
  >
	Starlight es nuestro ejemplo de una gran DX: la velocidad, la comodidad y 
	la atención a los detalles son inspiradores. Se encarga de la tecnología y el aspecto, 
	para que puedas centrarte en tu contenido 👏

¡El equipo de StackBlitz lo ama absolutamente!

  </Testimonial>
  <Testimonial
    name="Roberto"
    handle="RmeetsH"
    cite="https://twitter.com/RmeetsH/status/1735783992018760090"
  >
	Starlight ha sido un cambio de juego para mí, permitiéndome centrarme en la creación de contenido.

    Su diseño intuitivo no solo agiliza mi flujo de trabajo, sino que también reduce el tiempo de incorporación para los desarrolladores de código abierto.

  </Testimonial>
  <Testimonial
    name="Joel"
    handle="jhooks"
    cite="https://twitter.com/jhooks/status/1727405160547418405"
  >
	Pasé más tiempo con Starlight para la documentación de Course Builder y ha sido genial hasta ahora. Muchos toques agradables y puedo centrarme en escribir en Markdown y no en jugar con el sitio.
  </Testimonial>
  <Testimonial
    name="Rick"
    handle="rick_viscomi"
    cite="https://twitter.com/rick_viscomi/status/1665867447910510593"
  >
	Empecé a jugar con Starlight. Tengo que decir que estoy muy impresionado con el rendimiento que ofrece de forma predeterminada.

    💯💯💯💯

  </Testimonial>
  <Testimonial
    name="Nicolas"
    handle="beaussan"
    cite="https://twitter.com/beaussan/status/1735625189583466893"
  >
	Starlight es la mejor manera de empezar con la documentación, entre la 
	potencia y la velocidad de Astro y las herramientas de Starlight 
	coinciden con el cielo.

    ¡Ha sido mi elección durante un tiempo y sigo amándolo!

  </Testimonial>
  <Testimonial
    name="Sylwia"
    handle="SylwiaVargas"
    cite="https://x.com/SylwiaVargas/status/1726556825741578286"
  >
	Yo usé Starlight en mi último trabajo y me encantó. Buenos componentes, diseño 
	intuitivo y una comunidad super receptiva (cuando alguien necesitaba algo, 
	lo enviaban pronto o te decían una solución alternativa). Una experiencia muy agradable.
  </Testimonial>
  <Testimonial
    name="Lou Cyx"
    handle="loucyx"
    cite="https://elk.zone/m.webtoo.ls/@loucyx@mastodon.social/111587380021362284"
  >
	La documentación del monorepo de mi sitio se ve mejor que nunca gracias a Starlight. Es extremadamente fácil de usar sin perder todo el poder de Astro. ¡Gracias por trabajar en ello!
  </Testimonial>
  <Testimonial
    name="BowTiedWebReaper"
    handle="BowTiedWebReapr"
    cite="https://twitter.com/BowTiedWebReapr/status/1735633399501697517"
  >
	Starlight es mi herramienta de documentación por defecto. Hizo que fuera muy fácil añadir documentación a mi sitio web de producto Astro existente, en lugar de necesitar un subdominio para usar con otra herramienta.
  </Testimonial>
  <Testimonial
    name="Jeff"
    handle="J_Everhart383"
    cite="https://twitter.com/J_Everhart383/status/1691900590048292908"
  >
	Yo he estado reconstruyendo la documentación de la plataforma WPEngine Atlas. Créeme cuando digo que Starlight tiene todo lo que necesitas para hacer una plataforma de documentación A+ 🙌
  </Testimonial>
  <Testimonial
    name="Chloe"
    handle="solelychloe"
    cite="https://twitter.com/solelychloe/status/1695115277602628082"
  >
	¡Dale una oportunidad a Starlight!

    Yo lo uso para algunos de mis sitios y es genial.

  </Testimonial>
</TestimonialGrid>

<AboutAstro title="Presentado por">
Astro es el framework web todo en uno diseñado para la velocidad. Obtén tu contenido desde cualquier lugar y despliégalo en cualquier parte, todo potenciado por tus componentes y bibliotecas de UI favoritas.

[Aprende sobre Astro](https://astro.build/)

</AboutAstro>


================================================
FILE: docs/src/content/docs/es/manual-setup.mdx
================================================
---
title: Configuración Manual
description: Aprende como configurar Starlight manualmente para agregarlo a un proyecto Astro existente.
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

La manera más rápida de crear un nuevo sitio Starlight es usando `create astro` como se muestra en la [Guía de Inicio Rápido](/es/getting-started/#crea-un-nuevo-proyecto).
Si quieres agregar Starlight a un proyecto de Astro existente, esta guía te explicará como hacerlo.

## Configuración de Starlight

Para seguir esta guía, necesitarás un proyecto de Astro existente.

### Agregando la integración de Starlight

Starlight es una [integración de Astro](https://docs.astro.build/es/guides/integrations-guide/). Agregala a tu sitio ejecutando el comando `astro add` en el directorio raíz de tu proyecto:

<Tabs syncKey="pkg">
    <TabItem label="npm">
        ```sh
        npx astro add starlight
        ```

    </TabItem>
    <TabItem label="pnpm">
        ```sh
        pnpm astro add starlight
        ```
    </TabItem>
    <TabItem label="Yarn">
        ```sh
        yarn astro add starlight
        ```
    </TabItem>

</Tabs>

Esto instalará las dependencias necesarias y agregará Starlight al array `integrations` en el archivo de configuración de Astro.

### Configurando la integración

La integración de Starlight está configurada en tu archivo `astro.config.mjs`.

Agrega un `title` para comenzar:

```js ins={8}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Mi encantador sitio de documentos',
		}),
	],
});
```

Encuentra todas las opciones disponibles en la [referencia de configuración de Starlight](/es/reference/configuration/).

### Configura las colecciones de contenido

Starlight está construido sobre las [colecciones de contenido](https://docs.astro.build/es/guides/content-collections/) de Astro, las cuales están configuradas en el archivo `src/content/config.ts`.

Crea o actualiza el archivo de configuración de contenido, agregando una colección `docs` que usa el `docsSchema` de Starlight:

```js ins={3,6}
// src/content/config.ts
import { defineCollection } from 'astro:content';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
	docs: defineCollection({ schema: docsSchema() }),
};
```

### Agrega contenido

¡Starlight está configurado y es hora de agregar contenido!

Crea un directorio `src/content/docs/` y comienza agregando un archivo `index.md`.
Esta será la página de inicio de tu nuevo sitio:

```md
---
# src/content/docs/index.md
title: Mis Documentos
description: Aprende más sobre mi proyecto en este sitio de documentación construido con Starlight.
---

¡Bienvenido a mi proyecto!
```

Starlight usa el enrutamiento basado en archivos, lo que significa que cada archivo Markdown, MDX o Markdoc en `src/content/docs/` se convertirá en una página en tu sitio. Los metadatos de la parte frontal (los campos `title` y `description` en el ejemplo anterior) pueden cambiar la forma en que se muestra cada página.
Revisa todas las opciones disponibles en la [referencia de metadatos de la parte frontal](/es/reference/frontmatter/).

## Consejos para sitios existentes

Si tienes un proyecto de Astro existente, puedes usar Starlight para agregar rápidamente una sección de documentación a tu sitio.

### Usa Starlight en una subruta

Para agregar todas las páginas de Starlight en una subruta, coloca todo tu contenido de documentación dentro de un subdirectorio de `src/content/docs/`.

Por ejemplo, si las páginas de Starlight deben comenzar con `/guides/`, agrega tu contenido en el directorio `src/content/docs/guides/`:

import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src/
  - content/
    - docs/
      - **guides/**
        - guide.md
        - index.md
  - pages/
- astro.config.mjs

</FileTree>

En el futuro, planeamos soportar mejor este caso de uso para evitar la necesidad de un directorio anidado extra en `src/content/docs/`.

### Usa Starlight con SSR

Para habilitar el SSR, sigue la guía [“Adaptadores de Renderizado bajo Demanda”](https://docs.astro.build/es/guides/server-side-rendering/) en la documentación de Astro para agregar un adaptador de servidor a tu proyecto Starlight.

Las páginas de documentación generadas por Starlight se pre-renderizan de forma predeterminada independientemente del modo de salida de tu proyecto. Para excluir tus páginas de Starlight de la pre-renderización, establece la [opción de configuración `prerender`](/es/reference/configuration/#prerender) en `false`.


================================================
FILE: docs/src/content/docs/es/reference/configuration.mdx
================================================
---
title: Referencia de Configuración
description: Una descripción general de todas las opciones de configuración que admite Starlight.
---

## Configurar la integración `starlight`

Starlight es una integración construida sobre el framework [Astro](https://astro.build). Puedes configurar tu proyecto dentro del archivo de configuración `astro.config.mjs`:

```js
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';
export default defineConfig({
	integrations: [
		starlight({
			title: 'Mi encantador sitio de documentación',
		}),
	],
});
```

Puedes pasar las siguientes opciones a la integración `starlight`.

### `title` (requerido)

**tipo:** `string | Record<string, string>`

Establece el título de tu sitio web. Se utilizará en los metadatos y en el título de la pestaña del navegador.

El valor puede ser un string o para sitios multilingües, un objeto con valores para cada idioma diferente.
Cuando se usa la forma de objeto, las claves deben ser etiquetas BCP-47 (por ejemplo, `en`, `ar` o `zh-CN`):

```ts
starlight({
	title: {
		es: 'Mi encantador sitio de documentación',
		de: 'Meine bezaubernde Dokumentationsseite',
	},
});
```

### `description`

**tipo:** `string`

Establece la descripción de tu sitio web. Es usada en los metadatos compartidos con los motores de búsqueda en la etiqueta `<meta name="description">` si no se establece `description` en el frontmatter de una página.

### `logo`

**tipo:** [`LogoConfig`](#logoconfig)

Establece un logotipo para mostrarlo en la barra de navegación junto al título del sitio o en su lugar. Puedes establecer una única propiedad `src` o establecer fuentes de imagen separadas para `light` y `dark`.

```js
starlight({
	logo: {
		src: './src/assets/mi-logo.svg',
	},
});
```

#### `LogoConfig`

```ts
type LogoConfig = { alt?: string; replacesTitle?: boolean } & (
	| { src: string }
	| { light: string; dark: string }
);
```

### `tableOfContents`

**tipo:** `false | { minHeadingLevel?: number; maxHeadingLevel?: number; }`  
**por defecto:** `{ minHeadingLevel: 2; maxHeadingLevel: 3; }`

Configura la tabla de contenidos que se muestra a la derecha de cada página. De forma predeterminada, los encabezados `<h2>` y `<h3>` se incluirán en esta tabla de contenidos.

### `editLink`

**tipo:** `{ baseUrl: string }`

Hablita "Editar los enlaces" de está página estableciendo la URL base que se debe usar. El enlace final será `editLink.baseUrl` + la ruta de la página actual. Por ejemplo, para habilitar la edición de páginas en el repositorio `withastro/starlight` en GitHub:

```js
starlight({
	editLink: {
		baseUrl: 'https://github.com/withastro/starlight/edit/main/',
	},
});
```

Con esta configuración, una página `/introduction` tendría un enlace de edición que apunta a `https://github.com/withastro/starlight/edit/main/src/content/docs/introduction.md`.

### `sidebar`

**tipo:** [`SidebarItem[]`](#sidebaritem)

Configura los elementos de navegación de la barra lateral de tu sitio.

Una barra lateral es un conjunto de enlaces y grupos de enlaces.
Con la excepción de los elementos que usan `slug`, cada elemento debe tener una `label` y una de las siguientes propiedades:

- `link` — Un solo enlace a una URL específica, p. ej. `'/home'` o `'https://example.com'`.

- `slug` — una referencia a una página interna, p. ej. `'guides/getting-started'`.

- `items` — Un array que contiene más enlaces de la barra lateral y subgrupos.

- `autogenerate` — Un objeto que especifica un directorio de tus documentos para generar automáticamente un grupo de enlaces.

Los enlaces internos también se pueden especificar como una cadena en lugar de un objeto con una propiedad `slug`.

```js
starlight({
	sidebar: [
		// Un solo elemento de enlace etiquetado como “Home”.
		{ label: 'Home', link: '/' },
		// Un grupo etiquetado como "Start Here" que contiene cuatro enlaces.
		{
			label: 'Start Here',
			items: [
				// Usando `slug` para enlaces internos.
				{ slug: 'intro' },
				{ slug: 'installation' },
				// O usando la forma abreviada para enlaces internos.
				'tutorial',
				'next-steps',
			],
		},
		// Un grupo que enlaza a todas las páginas del directorio de referencia.
		{
			label: 'Reference',
			autogenerate: {
				directory: 'reference',
			},
		},
	],
});
```

#### Ordenación

Los grupos de la barra lateral generados automáticamente se ordenan alfabéticamente por el nombre del archivo.
Por ejemplo, una página generada a partir de `astro.md` aparecería por encima de la página `starlight.md`.

#### Colapsando grupos

Los grupos de enlaces se expanden de forma predeterminada. Puedes cambiar este comportamiento estableciendo la propiedad `collapsed` de un grupo como `true`.

Los subgrupos generados automáticamente respetan por defecto la propiedad `collapsed` de su grupo padre. Puedes establecer la propiedad `autogenerate.collapsed` para anular esto.

```js {5,13}
sidebar: [
  // Un grupo colapsado de enlaces.
  {
    label: 'Collapsed Links',
    collapsed: true,
    items: ['intro', 'next-steps'],
  },
  // Un grupo expandido que contiene subgrupos generados automáticamente colapsados.
  {
    label: 'Reference',
    autogenerate: {
      directory: 'reference',
      collapsed: true,
    },
  },
],
```

#### Traduciendo etiquetas

Si tu sitio es multilingüe, se considera que la etiqueta de cada elemento está en el idioma predeterminado. Puedes establecer una propiedad de `translations` para proporcionar etiquetas en los otros idiomas que tu sitio admita:

```js {5,9,14}
sidebar: [
  // Un ejemplo de barra lateral con etiquetas traducidas al portugués de Brasil.
  {
    label: 'Start Here',
    translations: { 'pt-BR': 'Comece Aqui' },
    items: [
      {
        label: 'Getting Started',
        translations: { 'pt-BR': 'Introdução' },
        link: '/getting-started',
      },
      {
        label: 'Project Structure',
        translations: { 'pt-BR': 'Estrutura de Projetos' },
        link: '/structure',
      },
    ],
  },
],
```

#### `SidebarItem`

```ts
type SidebarItem =
	| string
	| ({
			translations?: Record<string, string>;
			badge?: string | BadgeConfig;
	  } & (
			| {
					// Enlace
					link: string;
					label: string;
					attrs?: Record<string, string | number | boolean | undefined>;
			  }
			| {
					// Enlace interno
					slug: string;
					label?: string;
					attrs?: Record<string, string | number | boolean | undefined>;
			  }
			| {
					// Grupo de enlaces
					label: string;
					items: SidebarItem[];
					collapsed?: boolean;
			  }
			| {
					// Grupo de enlaces autogenerado
					label: string;
					autogenerate: { directory: string; collapsed?: boolean };
					collapsed?: boolean;
			  }
	  ));
```

#### `BadgeConfig`

```ts
interface BadgeConfig {
	text: string;
	variant?: 'note' | 'tip' | 'caution' | 'danger' | 'success' | 'default';
	class?: string;
}
```

### `locales`

**tipo:** <code>\{ \[dir: string\]: [LocaleConfig](#localeconfig) \}</code>

[Configura la internacionalización (i18n)](/es/guides/i18n/) para tu sitio estableciendo qué `locales` se admiten.

Cada entrada debe usar el directorio donde se guardan los archivos de ese idioma como clave.

```js
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'My Docs',
			// Establece el inglés como el idioma predeterminado para este sitio.
			defaultLocale: 'en',
			locales: {
				// Los documentos en inglés en `src/content/docs/en/`
				en: {
					label: 'English',
				},
				// Los documentos en chino simplificado en `src/content/docs/zh-cn/`
				'zh-cn': {
					label: '简体中文',
					lang: 'zh-CN',
				},
				// Los documentos en árabe en `src/content/docs/ar/`
				ar: {
					label: 'العربية',
					dir: 'rtl',
				},
			},
		}),
	],
});
```

#### `LocaleConfig`

```ts
interface LocaleConfig {
	label: string;
	lang?: string;
	dir?: 'ltr' | 'rtl';
}
```

Puedes establecer las siguientes opciones para cada idioma:

##### `label` (requerido)

**tipo:** `string`

La etiqueta para este idioma que se muestra a los usuarios, por ejemplo, en el selector de idioma. Lo más probable es que quieras que este sea el nombre del idioma como un usuario de ese idioma esperaría leerlo, por ejemplo, `"English"`, `"العربية"` o `"简体中文"`.

##### `lang`

**tipo:** `string`

La etiqueta BCP-47 para este lenguaje, por ejemplo, `"en"`, `"ar"` o `"zh-CN"`. Si no se establece, se utilizará el nombre del directorio del idioma de forma predeterminada. Las etiquetas de idioma con subetiquetas regionales (por ejemplo, `"pt-BR"` o `"en-US"`) utilizarán las traducciones de la interfaz de usuario integradas para su idioma base si no se encuentran traducciones específicas de la región.

##### `dir`

**tipo:** `'ltr' | 'rtl'`

La dirección de escritura de este idioma; `"ltr"` para de izquierda a derecha (el valor predeterminado) o `"rtl"` para de derecha a izquierda.

#### Idioma raíz

Puedes servir el idioma predeterminado sin un directorio `/lang/` estableciendo un idioma `root`:

```js {3-6}
starlight({
	locales: {
		root: {
			label: 'English',
			lang: 'en',
		},
		fr: {
			label: 'Français',
		},
	},
});
```

Por ejemplo, esto te permite servir `/getting-started/` como una ruta en inglés y usar `/fr/getting-started/` como la página francesa equivalente.

### `defaultLocale`

**tipo:** `string`

Establece el idioma que es el predeterminado para este sitio.
Este valor debe coincidir con una de las claves de tu objeto [`locales`](#locales).
(Si tu idioma predeterminado es tu [idioma raíz](#idioma-raíz), puedes omitir esto.)

El idioma predeterminado se utilizará para proporcionar contenido de respaldo donde faltan las traducciones.

### `social`

import SocialLinksType from '~/components/social-links-type.astro';

**tipo:** <SocialLinksType />

Detalles opcionales sobre las cuentas de redes sociales para este sitio. Agregar cualquiera de estos los mostrará como enlaces de iconos en el encabezado del sitio.

```js
starlight({
	social: {
		codeberg: 'https://codeberg.org/knut/examples',
		discord: 'https://astro.build/chat',
		github: 'https://github.com/withastro/starlight',
		linkedin: 'https://www.linkedin.com/company/astroinc',
		mastodon: 'https://m.webtoo.ls/@astro',
		threads: 'https://www.threads.net/@nmoodev',
		twitch: 'https://www.twitch.tv/bholmesdev',
		twitter: 'https://twitter.com/astrodotbuild',
		'x.com': 'https://x.com/astrodotbuild',
		youtube: 'https://youtube.com/@astrodotbuild',
	},
});
```

### `customCss`

**tipo:** `string[]`

Proporciona archivos CSS para personalizar el aspecto y la sensación de tu sitio Starlight.

Admite archivos CSS locales relativos a la raíz de tu proyecto, por ejemplo, `'./src/custom.css'`, y CSS que instalaste como un módulo npm, por ejemplo, `'@fontsource/roboto'`.

```js
starlight({
	customCss: ['./src/custom-styles.css', '@fontsource/roboto'],
});
```

### `expressiveCode`

**tipo:** `StarlightExpressiveCodeOptions | boolean`  
**por defecto:** `true`

Starlight usa [Expressive Code](https://github.com/expressive-code/expressive-code/tree/main/packages/astro-expressive-code) para renderizar bloques de código y agregar soporte para resaltar partes de ejemplos de código, agregar nombres de archivo a bloques de código y más.
Consulta la [guía de “Bloques de código”](/es/guides/authoring-content/#bloques-de-código) para aprender a usar la sintaxis de Expressive Code en tu contenido Markdown y MDX.

Puedes usar cualquier de las [opciones de configuración estándar de Expressive Code](https://github.com/expressive-code/expressive-code/blob/main/packages/astro-expressive-code/README.md#configuration) así como algunas propiedades específicas de Starlight, estableciéndolas en la opción `expressiveCode` de Starlight.
Por ejemplo, establece la opción `styleOverrides` de Expressive Code para anular el CSS predeterminado. Esto permite personalizaciones como darle a tus bloques de código esquinas redondeadas:

```js ins={2-4}
starlight({
	expressiveCode: {
		styleOverrides: { borderRadius: '0.5rem' },
	},
});
```

Si quieres deshabilitar Expressive Code, establece `expressiveCode: false` en tu configuración de Starlight:

```js ins={2}
starlight({
	expressiveCode: false,
});
```

Adicionalmente a las opciones estándar de Expressive Code, también puedes establecer las siguientes propiedades específicas de Starlight en tu configuración `expressiveCode` para personalizar aún más el comportamiento del tema para tus bloques de código:

#### `themes`

**tipo:** `Array<string | ThemeObject | ExpressiveCodeTheme>`  
**por defecto:** `['starlight-dark', 'starlight-light']`

Establece los temas utilizados para dar estilo a los bloques de código.
Consulta la [documentación de temas de Expressive Code](https://github.com/expressive-code/expressive-code/blob/main/packages/astro-expressive-code/README.md#themes) para obtener detalles de los formatos de tema admitidos.

Starlight usa por defecto las variantes oscura y clara del [tema Night Owl](https://github.com/sdras/night-owl-vscode-theme) de Sarah Drasner.

Si proporcionas por lo menos un tema oscuro y uno claro, Starlight mantendrá automáticamente el tema de bloque de código activo sincronizado con el tema actual del sitio.
Configura este comportamiento con la opción [`useStarlightDarkModeSwitch`](#usestarlightdarkmodeswitch).

#### `useStarlightDarkModeSwitch`

**tipo:** `boolean`  
**por defecto:** `true`

Cuando sea `true`, los bloques de código cambian automáticamente entre temas claros y oscuros cuando cambia el tema del sitio.
Cuando sea `false`, debes agregar manualmente CSS para manejar el cambio entre múltiples temas.

:::note
Cuando estableces `themes`, debes proporcionar por lo menos un tema oscuro y uno claro para que el interruptor de modo oscuro de Starlight funcione.
:::

#### `useStarlightUiThemeColors`

**tipo:** `boolean`  
**por defecto:** `true` si `themes` no está establecido, de lo contrario `false`

Cuando sea `true`, se utilizan las variables CSS de Starlight para los colores de los elementos de la UI del bloque de código (fondos, botones, sombras, etc.), coincidiendo con el [tema de color del sitio](/es/guides/css-and-tailwind/#temas).
Cuando sea `false`, se utilizan los colores proporcionados por el tema de resaltado de sintaxis activo para estos elementos.

:::note
Cuando usas temas personalizados y estableces esto en `true`, debes proporcionar por lo menos un tema oscuro y uno claro para asegurar un contraste de color adecuado.
:::

### `pagefind`

**tipo:** `boolean`  
**por defecto:** `true`

Define si el proveedor de búsqueda predeterminado de Starlight [Pagefind](https://pagefind.app/) está habilitado.

Establece esta opción a `false` para excluir una página de los resultados de búsqueda.
Esto también ocultará la interfaz de usuario de búsqueda predeterminada si está en uso.

Pagefind no puede estar habilitado cuando la opción [`prerender`](#prerender) está establecida en `false`.

### `prerender`

**tipo:** `boolean`  
**por defecto:** `true`

Define si las páginas de Starlight deben ser pre-renderizadas a HTML estático o renderizadas bajo demanda por un [adaptador SSR](https://docs.astro.build/es/guides/server-side-rendering/).

Las páginas de Starlight se pre-renderizan de forma predeterminada.
Si estás usando un adaptador SSR y deseas renderizar las páginas de Starlight bajo demanda, establece `prerender: false`.

### `head`

**tipo:** [`HeadConfig[]`](#headconfig)

Agrega etiquetas personalizadas a la etiqueta `<head>` de tu sitio Starlight.
Puede ser útil para agregar análisis y otros scripts y recursos de terceros.

```js
starlight({
	head: [
		// Ejemplo: agregar etiqueta de script de análisis de Fathom.
		{
			tag: 'script',
			attrs: {
				src: 'https://cdn.usefathom.com/script.js',
				'data-site': 'MY-FATHOM-ID',
				defer: true,
			},
		},
	],
});
```

Las entradas en el `head` son convertidas directamente a elementos HTML y no pasan por el [procesamiento de script](https://docs.astro.build/es/guides/client-side-scripts/#procesamiento-de-scripts) o [estilo](https://docs.astro.build/es/guides/styling/#estilando-en-astro) de Astro.
Si necesitas importar activos locales como scripts, estilos o imágenes, [anula el componente Head](/es/guides/overriding-components/#reusa-un-componente-integrado).

#### `HeadConfig`

```ts
interface HeadConfig {
	tag: string;
	attrs?: Record<string, string | boolean | undefined>;
	content?: string;
}
```

### `lastUpdated`

**type:** `boolean`  
**default:** `false`

Controla si se muestra el pie de página que indica cuándo se actualizó por última vez la página.

De forma predeterminada, esta función se basa en el historial Git de tu repositorio y puede no ser precisa en algunas plataformas de implementación que realizan [copias superficiales](https://git-scm.com/docs/git-clone#Documentation/git-clone.txt---depthltdepthgt). Una página puede anular esta configuración o la fecha basada en Git utilizando el campo [`lastUpdated`](/es/reference/frontmatter/#lastupdated) en el frontmatter.

### `pagination`

**tipo:** `boolean`  
**por defecto:** `true`

Define si el pie de página debe incluir enlaces a la página anterior y siguiente.

Una página puede anular esta configuración o el texto del enlace y/o la URL utilizando los campos de metadatos [`prev`](/es/reference/frontmatter/#prev) y [`next`](/es/reference/frontmatter/#next).

### `favicon`

**tipo:** `string`  
**por defecto:** `'/favicon.svg'`

Establece la ruta del favicon predeterminado para tu sitio web, el cual debería ubicarse en el directorio `public/` y ser un archivo de icono válido (`.ico`, `.gif`, `.jpg`, `.png` o `.svg`).

```js
starlight({
  favicon: '/images/favicon.svg',
}),
```

Si necesitas establecer variantes adicionales o favicons de respaldo, puedes agregar etiquetas utilizando la opción [`head`](#head):

```js
starlight({
	favicon: '/images/favicon.svg',
	head: [
		// Agregar un favicon ICO de respaldo para Safari.
		{
			tag: 'link',
			attrs: {
				rel: 'icon',
				href: '/images/favicon.ico',
				sizes: '32x32',
			},
		},
	],
});
```

### `titleDelimiter`

**tipo:** `string`  
**por defecto:** `'|'`

Establece un delimitador entre el título de la página y el título del sitio web en la etiqueta `<title>`, que se muestra en las pestañas del navegador.

Por defecto, cada página tiene un `<title>` de `Título de la página | Título del sitio web`.
Por ejemplo, esta página es titulada "Referencia de Configuración" y este sitio web es titulado "Starlight", por lo que el `<title>` de esta página es "Referencia de Configuración | Starlight".

### `disable404Route`

**tipo:** `boolean`  
**por defecto:** `false`

Deshabilita la inyección de la [página 404](https://docs.astro.build/es/core-concepts/astro-pages/#página-de-error-404-personalizada) predeterminada de Starlight. Para usar una ruta `src/pages/404.astro` personalizada en tu proyecto, establece esta opción en `true`.

### `components`

**tipo:** `Record<string, string>`

Proporciona las rutas a los componentes para sobreescribir las implementaciones predeterminadas de Starlight.

```js
starlight({
	components: {
		SocialLinks: './src/components/MySocialLinks.astro',
	},
});
```

Consulta la [Referencia de Personalización de Componentes](/es/reference/overrides/) para obtener detalles de todos los componentes que puedes anular.

### `plugins`

**tipo:** [`StarlightPlugin[]`](/es/reference/plugins/#referencia-rápida-de-la-api)

Extiende Starlight con plugins personalizados.
Los plugins aplican cambios a tu proyecto para modificar o agregar a las funcionalidades a Starlight.

Visita la [exhibición de plugins](/es/resources/plugins/#plugins) para ver una lista de los plugins disponibles.

```js
starlight({
	plugins: [starlightPlugin()],
});
```

Consulta la [Referencia de Plugins](/es/reference/plugins/) para obtener detalles sobre cómo crear tus propios plugins.

### `credits`

Habilita la visualización de un enlace “Hecho con Starlight” en el pie de página de tu sitio.

```js
starlight({
	credits: true,
});
```


================================================
FILE: docs/src/content/docs/es/reference/frontmatter.md
================================================
---
title: Referencia de Frontmatter
description: Una visión general de los campos de frontmatter predeterminados que admite Starlight.
---

Puedes personalizar individualmente las páginas Markdown y MDX en Starlight estableciendo valores en su frontmatter. Por ejemplo, una página regular podría establecer los campos `title` y `description`:

```md {3-4}
---
# src/content/docs/example.md
title: Acerca de este proyecto
description: Aprende más sobre el proyecto en el que estoy trabajando.
---

¡Bienvenido a la página Acerca de!
```

## Campos de frontmatter

### `title` (requerido)

**tipo:** `string`

Debes proporcionar un título para cada página. Este se mostrará en la parte superior de la página, en las pestañas del navegador y en los metadatos de la página.

### `description`

**tipo:** `string`

La descripción de la página es usada para los metadatos de la página y será recogida por los motores de búsqueda y en las vistas previas de las redes sociales.

### `slug`

**tipo**: `string`

Sobreescribe el slug de la página. Consulta [“Definiendo slugs personalizados”](https://docs.astro.build/es/guides/content-collections/#definiendo-slugs-personalizados) en la documentación de Astro para más detalles.

### `editUrl`

**tipo:** `string | boolean`

Reemplaza la [configuración global `editLink`](/es/reference/configuration/#editlink). Establece a `false` para deshabilitar el enlace "Editar página" para una página específica o proporciona una URL alternativa donde el contenido de esta página es editable.

### `head`

**tipo:** [`HeadConfig[]`](/es/reference/configuration/#headconfig)

Puedes agregar etiquetas adicionales a la etiqueta `<head>` de tu página usando el campo `head` del frontmatter. Esto significa que puedes agregar estilos personalizados, metadatos u otras etiquetas a una sola página. Similar a la [opción global `head`](/es/reference/configuration/#head).

```md
---
# src/content/docs/example.md
title: Acerca de nosotros
head:
  # Usa una etiqueta <title> personalizada
  - tag: title
    content: Título personalizado sobre nosotros
---
```

### `tableOfContents`

**tipo:** `false | { minHeadingLevel?: number; maxHeadingLevel?: number; }`

Reemplaza la [configuración global `tableOfContents`](/es/reference/configuration/#tableofcontents).
Personaliza los niveles de encabezado que se incluirán o establece en `false` para ocultar la tabla de contenidos en esta página.

```md
---
# src/content/docs/example.md
title: Página con solo encabezados H2 en la tabla de contenidos
tableOfContents:
  minHeadingLevel: 2
  maxHeadingLevel: 2
---
```

```md
---
# src/content/docs/example.md
title: Página sin tabla de contenidos
tableOfContents: false
---
```

### `template`

**tipo:** `'doc' | 'splash'`  
**por defecto:** `'doc'`

Establece la plantilla de diseño para esta página.
Las páginas usan el diseño `'doc'` por defecto.
Establece `'splash'` para usar un diseño más amplio sin barras laterales diseñado para las landing pages.

### `hero`

**tipo:** [`HeroConfig`](#heroconfig)

Agrega un componente hero en la parte superior de esta página. Funciona bien con `template: splash`.

Por ejemplo, esta configuración muestra algunas opciones comunes, incluyendo la carga de una imagen desde tu repositorio.

```md
---
# src/content/docs/example.md
title: Mi página de inicio
template: splash
hero:
  title: 'Mi proyecto: Cosas estelares más pronto'
  tagline: Lleva tus cosas a la luna y de vuelta en un abrir y cerrar de ojos.
  image:
    alt: Un logotipo brillante, de colores brillantes
    file: ../../assets/logo.png
  actions:
    - text: Cuéntame más
      link: /getting-started/
      icon: right-arrow
    - text: View on GitHub
      link: https://github.com/astronaut/my-project
      icon: external
      variant: minimal
      attrs:
        rel: me
---
```

Puedes mostrar diferentes versiones de la imagen hero en los modos claro y oscuro.

```md
---
# src/content/docs/example.md
hero:
  image:
    alt: Un logotipo brillante, de colores brillantes
    dark: ../../assets/logo-dark.png
    light: ../../assets/logo-light.png
---
```

#### `HeroConfig`

```ts
interface HeroConfig {
  title?: string;
  tagline?: string;
  image?:
    | {
        // Ruta relativa a una imagen en tu repositorio.
        file: string;
        // Texto alternativo para hacer que la imagen sea accesible a la tecnología de asistencia
        alt?: string;
      }
    | {
        // Ruta relativa a una imagen en tu repositorio para usar en el modo oscuro.
        dark: string;
        // Ruta relativa a una imagen en tu repositorio para usar en el modo claro.
        light: string;
        // Texto alternativo para hacer que la imagen sea accesible a la tecnología de asistencia
        alt?: string;
      }
    | {
        // HTML crudo para usar en el espacio de la imagen.
        // Podría ser una etiqueta `<img>` personalizada o un `<svg>` en línea.
        html: string;
      };
  actions?: Array<{
    text: string;
    link: string;
    variant?: 'primary' | 'secondary' | 'minimal';
    icon?: string;
    attrs?: Record<string, string | number | boolean>;
  }>;
}
```

### `banner`

**tipo:** `{ content: string }`

Muestra un banner de anuncio en la parte superior de esta página.

El valor `content` puede incluir HTML para enlaces u otro contenido.
Por ejemplo, esta página muestra un banner que incluye un enlace a `example.com`.

```md
---
# src/content/docs/example.md
title: Página con un banner
banner:
  content: |
    ¡Acabamos de lanzar algo genial!
    <a href="https://example.com">Checalo</a>
---
```

### `lastUpdated`

**type:** `Date | boolean`

Sobrescribe la [opción global `lastUpdated`](/es/reference/configuration/#lastupdated). Si se especifica una fecha, debe ser una [marca de tiempo YAML](https://yaml.org/type/timestamp.html) válida y sobrescribirá la fecha almacenada en el historial de Git para esta página.

```md
---
# src/content/docs/example.md
title: Página con una fecha de última actualización personalizada
lastUpdated: 2022-08-09
---
```

### `prev`

**tipo:** `boolean | string | { link?: string; label?: string }`

Anula la [opción global de `pagination`](/es/reference/configuration/#pagination). Si se especifica un string, el texto del enlace generado se reemplazará, y si se especifica un objeto, tanto el enlace como el texto serán anulados.

```md
---
# src/content/docs/example.md
# Ocultar el enlace de la página anterior
prev: false
---
```

```md
---
# src/content/docs/example.md
# Sobrescribir el texto del enlace de la página anterior
prev: Continuar con el tutorial
---
```

```md
---
# src/content/docs/example.md
# Sobrescribir tanto el enlace de la página anterior como el texto
prev:
  link: /página-no-relacionada/
  label: Echa un vistazo a esta otra página
---
```

### `next`

**tipo:** `boolean | string | { link?: string; label?: string }`

Lo mismo que [`prev`](#prev), pero para el enlace de la página siguiente.

```md
---

# src/content/docs/example.md

# Ocultar el enlace de la página siguiente

next: false
```

### `pagefind`

**tipo:** `boolean`  
**por defecto:** `true`

Establece si esta página debe incluirse en el índice de búsqueda de [Pagefind](https://pagefind.app/). Establece en `false` para excluir una página de los resultados de búsqueda:

```md
---
# src/content/docs/example.md
# Ocultar esta página del índice de búsqueda
pagefind: false
---
```

### `draft`

**tipo:** `boolean`  
**por defecto:** `false`

Establece si esta página debe considerarse como un borrador y no incluirse en las [compilaciones de producción](https://docs.astro.build/es/reference/cli-reference/#astro-build) y [grupos de enlaces autogenerados](/es/guides/sidebar/#grupos-autogenerados). Establece en `true` para marcar una página como borrador y hacerla visible solo durante el desarrollo.

```md
---
# src/content/docs/example.md
# Excluye esta página de las compilaciones de producción
draft: true
---
```

### `sidebar`

**tipo:** [`SidebarConfig`](#sidebarconfig)

Controla cómo se muestra esta página en el [sidebar](/es/reference/configuration/#sidebar) al utilizar un grupo de enlaces generado automáticamente.

#### `SidebarConfig`

```ts
interface SidebarConfig {
  label?: string;
  order?: number;
  hidden?: boolean;
  badge?: string | BadgeConfig;
  attrs?: Record<string, string | number | boolean | undefined>;
}
```

#### `label`

**tipo:** `string`  
**por defecto:** El [`title`](#title-requerido) de la página

Establece la etiqueta para esta página en la barra lateral cuando se muestra en un grupo de enlaces generado automáticamente.

```md
---
# src/content/docs/example.md
title: Acerca de este proyecto
sidebar:
  label: Acerca de
---
```

#### `order`

**tipo:** `number`

Controla el orden de esta página al ordenar un grupo de enlaces generado automáticamente.
Los números más bajos se muestran más arriba en el grupo de enlaces.

```md
---
# src/content/docs/example.md
title: Página para mostrar primero
sidebar:
  order: 1
---
```

#### `hidden`

**tipo:** `boolean`
**por defecto:** `false`

Previene que esta página se incluya en un grupo de enlaces generado automáticamente en la barra lateral.

```md
---
# src/content/docs/example.md
title: Página para ocultar de la barra lateral autogenerada
sidebar:
  hidden: true
---
```

#### `badge`

**tipo:** <code>string | <a href="/es/reference/configuration/#badgeconfig">BadgeConfig</a></code>

Agrega una insignia a la página en la barra lateral cuando se muestra en un grupo de enlaces generado automáticamente.
Cuando se usa un string, la insignia se mostrará con el color de acento predeterminado.
Opcionalmente, pasa un objeto [`BadgeConfig`](/es/reference/configuration/#badgeconfig) con los campos `text`, `variant` y `class` para personalizar la insignia.

```md
---
# src/content/docs/example.md
title: Página con una insignia
sidebar:
  # Usa la variante predeterminada que coincide con el color de acento de tu sitio
  badge: Nuevo
---
```

```md
---
# src/content/docs/example.md
title: Página con una insignia
sidebar:
  badge:
    text: Experimental
    variant: caution
---
```

#### `attrs`

**type:** `Record<string, string | number | boolean | undefined>`

Atributos HTML para agregar al enlace de la página en la barra lateral cuando se muestra en un grupo de enlaces generado automáticamente.

```md
---
# src/content/docs/example.md
title: Página que se abre en una nueva pestaña
sidebar:
  # Abre la página en una nueva pestaña
  attrs:
    target: _blank
---
```

## Personaliza el esquema del frontmatter

El esquema del frontmatter para la colección de contenido `docs` de Starlight se configura en `src/content/config.ts` usando el auxiliar `docsSchema()`:

```ts {3,6}
// src/content/config.ts
import { defineCollection } from 'astro:content';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
  docs: defineCollection({ schema: docsSchema() }),
};
```

Aprende más sobre los esquemas de colección de contenido en [“Definir un esquema de colección”](https://docs.astro.build/es/guides/content-collections/#definiendo-un-esquema-de-colección) en la documentación de Astro.

`docsSchema()` toma las siguientes opciones:

### `extend`

**tipo:** esquema Zod o función que devuelve un esquema Zod
**por defecto:** `z.object({})`

Extiende el esquema de Starlight con campos adicionales estableciendo `extend` en las opciones de `docsSchema()`.
El valor debe ser un [esquema Zod](https://docs.astro.build/es/guides/content-collections/#definiendo-tipos-de-datos-con-zod).

En el siguiente ejemplo, proporcionamos un tipo más estricto para `description` para hacerlo requerido y agregamos un nuevo campo opcional `category`:

```ts {8-13}
// src/content/config.ts
import { defineCollection, z } from 'astro:content';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
  docs: defineCollection({
    schema: docsSchema({
      extend: z.object({
        // Hacer un campo integrado requerido en lugar de opcional.
        description: z.string(),
        // Agrega un nuevo campo al esquema.
        category: z.enum(['tutorial', 'guide', 'reference']).optional(),
      }),
    }),
  }),
};
```

Para tomar ventaja del [auxiliar `image()` de Astro](https://docs.astro.build/es/guides/images/#imágenes-en-colecciones-de-contenido), usa una función que devuelva tu extensión de esquema:

```ts {8-13}
// src/content/config.ts
import { defineCollection, z } from 'astro:content';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
  docs: defineCollection({
    schema: docsSchema({
      extend: ({ image }) => {
        return z.object({
          // Agrega un campo que debe resolverse a una imagen local.
          cover: image(),
        });
      },
    }),
  }),
};
```


================================================
FILE: docs/src/content/docs/es/reference/icons.mdx
================================================
---
title: Referencia de iconos
description: Una descripción general de todos los iconos disponibles en Starlight.
---

Starlight proporciona un conjunto de iconos integrados que puedes mostrar en tu contenido usando el componente `<Icon>`.

## Usar iconos

Los iconos se pueden mostrar usando el componente [`<Icon>`](/es/components/icons/).
Estos también se utilizan a menudo en otros componentes, como [tarjetas](/es/components/cards/) o configuraciones como [acciones de hero](/es/reference/frontmatter/#hero).

## Todos los iconos

Una lista de todos los iconos disponibles se muestra a continuación con sus nombres asociados. Haz clic en un icono para copiar su nombre al portapapeles.

import IconsList from '~/components/icons-list.astro';

<IconsList labels={{ copied: '¡Copiado!' }} />


================================================
FILE: docs/src/content/docs/es/reference/overrides.md
================================================
---
title: Referencia de Personalización de Componentes
description: Una descripción general de los componentes y props de componentes compatibles con los reemplazos de Starlight.
tableOfContents:
  maxHeadingLevel: 4
---

Puedes reemplazar los componentes integrados de Starlight proporcionando rutas a los componentes en la opción de configuración [`components`](/es/reference/configuration/#components) de Starlight.

Esta página enumera todos los componentes disponibles para reemplazar y enlaces a sus implementaciones predeterminadas en GitHub.

Aprende más en la [Guía para Personalizar Componentes](/es/guides/overriding-components/).

## Props de Componentes

Todos los componentes pueden acceder a un objeto estándar `Astro.props` que contiene información sobre la página actual.

Para escribir los tipos de tus componentes personalizados, importa el tipo `Props` de Starlight:

```astro
---
// src/components/Custom.astro
import type { Props } from '@astrojs/starlight/props';

const { hasSidebar } = Astro.props;
//      ^ tipo: boolean
---
```

Esto te dará autocompletado y tipos al acceder a `Astro.props`.

### Props

Starlight pasará las siguientes props a tus componentes personalizados.

#### `dir`

**Tipo:** `'ltr' | 'rtl'`

La dirección de escritura de la página.

#### `lang`

**Tipo:** `string`

Etiqueta de idioma BCP-47 para la configuración regional de esta página, por ejemplo, `en`, `zh-CN` o `pt-BR`.

#### `locale`

**Tipo:** `string | undefined`

La ruta base en la que se sirve un idioma. `undefined` para los slugs de idioma raíz.

#### `siteTitle`

**Tipo:** `string`

El título del sitio para el idioma de esta página.

#### `siteTitleHref`

**Tipo:** `string`

El valor del atributo `href` del título del sitio, enlazando de vuelta a la página de inicio, por ejemplo `/`.
Para sitios multilingües, esto incluirá la configuración regional actual, por ejemplo, `/en/` o `/zh-cn/`.

#### `slug`

**Tipo:** `string`

El slug se genera a partir del nombre de archivo de contenido.

#### `id`

**Tipo:** `string`

El ID único para esta página basado en el nombre de archivo de contenido.

#### `isFallback`

**Tipo:** `true | undefined`

`true` si esta página no está traducida en el idioma actual y está utilizando contenido de respaldo del idioma predeterminado.
Solo se usa en sitios multilingües.

#### `entryMeta`

**Tipo:** `{ dir: 'ltr' | 'rtl'; lang: string }`

Metadatos de configuración regional para el contenido de la página. Puede ser diferente de los valores de configuración regional de nivel superior cuando una página está utilizando contenido de respaldo.

#### `entry`

La entrada de la colección de contenido Astro para la página actual.
Incluye los valores de frontmatter para la página actual en `entry.data`.

```ts
entry: {
  data: {
    title: string;
    description: string | undefined;
    // etc.
  }
}
```

Aprende más sobre la forma de este objeto en la referencia de [Tipo de Entrada de la Colección de Astro](https://docs.astro.build/es/reference/api-reference/#tipo-de-entrada-de-la-colección).

#### `sidebar`

**Tipo:** `SidebarEntry[]`

Navegación de sitio entradas de barra lateral para esta página.

#### `hasSidebar`

**Tipo:** `boolean`

Si la barra lateral debe mostrarse o no en esta página.

#### `pagination`

**Tipo:** `{ prev?: Link; next?: Link }`

Los enlaces a la página anterior y siguiente en la barra lateral si están habilitados.

#### `toc`

**Tipo:** `{ minHeadingLevel: number; maxHeadingLevel: number; items: TocItem[] } | undefined`

Tabla de contenidos para esta página si está habilitada.

#### `headings`

**Tipo:** `{ depth: number; slug: string; text: string }[]`

Array de todos los encabezados Markdown extraídos de la página actual.
Usa [`toc`](#toc) en su lugar si deseas construir un componente de tabla de contenidos que respete las opciones de configuración de Starlight.

#### `lastUpdated`

**Tipo:** `Date | undefined`

Objeto `Date` de JavaScript que representa cuándo se actualizó por última vez esta página si está habilitado.

#### `editUrl`

**Tipo:** `URL | undefined`

Objeto `URL` para la dirección donde se puede editar esta página si está habilitado.

---

## Componentes

### Head

Estos componentes son renderizados dentro del elemento `<head>` de cada página.
Solo deben incluir [elementos permitidos dentro de `<head>`](https://developer.mozilla.org/es/docs/Web/HTML/Element/head#see_also).

#### `Head`

**Componente por defecto:** [`Head.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Head.astro)

Componente renderizado dentro del elemento `<head>` de cada página.
Incluye etiquetas importantes como `<title>` y `<meta charset="utf-8">`.

Reemplaza este componente como último recurso.
Si es posible, prefiere la opción [`head`](/es/reference/configuration/#head) de la configuración de Starlight si es posible.

#### `ThemeProvider`

**Componente por defecto:** [`ThemeProvider.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/ThemeProvider.astro)

Componente renderizado dentro de `<head>` que configura el soporte de tema claro/oscuro.
La implementación predeterminada incluye un script en línea y una `<template>` utilizada por el script en [`<ThemeSelect />`](#themeselect).

---

### Accesibilidad

#### `SkipLink`

**Componente por defecto:** [`SkipLink.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/SkipLink.astro)

El componente renderizado como el primer elemento dentro de `<body>` que enlaza al contenido principal de la página para la accesibilidad.
La implementación predeterminada está oculta hasta que un usuario la enfoca al presionar la tecla de tabulación con su teclado.

---

### Plantilla

Estos componentes son responsables de la ubicación de los componentes de Starlight y de la gestión de las vistas en diferentes tamaños de pantalla.
Reemplazar estos componentes viene con una complejidad significativa.
Cuando sea posible, es preferible reemplazar un componente de nivel inferior.

#### `PageFrame`

**Componente por defecto:** [`PageFrame.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/PageFrame.astro)

El componente plantilla que envuelve la mayor parte del contenido de la página.
La implementación predeterminada configura la plantilla header-sidebar-main e incluye slots nombrados `header` y `sidebar` con un slot predeterminado para el contenido principal.
También renderiza [`<MobileMenuToggle />`](#mobilemenutoggle) para alternar el renderizado de la navegación de la barra lateral en pantallas estrechas (móviles).

#### `MobileMenuToggle`

**Componente por defecto:** [`MobileMenuToggle.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MobileMenuToggle.astro)

Componente renderizado dentro de [`<PageFrame>`](#pageframe) que es responsable de alternar la navegación de la barra lateral en pantallas estrechas (móviles).

#### `TwoColumnContent`

**Componente por defecto:** [`TwoColumnContent.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/TwoColumnContent.astro)

Componente plantilla que envuelve la columna de contenido principal y la barra lateral derecha (tabla de contenidos).
La implementación predeterminada maneja el cambio entre un diseño de una sola columna, en pantallas estrechas y un diseño de dos columnas en pantallas más grande.

---

### Header

Estos componentes renderizan la barra de navegación superior de Starlight.

#### `Header`

**Componente por defecto:** [`Header.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Header.astro)

Componente de encabezado que se muestra en la parte superior de cada página.
La implementación predeterminada muestra [`<SiteTitle />`](#sitetitle-1), [`<Search />`](#search), [`<SocialIcons />`](#socialicons), [`<ThemeSelect />`](#themeselect) y [`<LanguageSelect />`](#languageselect).

#### `SiteTitle`

**Componente por defecto:** [`SiteTitle.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/SiteTitle.astro)

Componente renderizado al comienzo del encabezado para renderizar el título de la web.
La implementación predeterminada incluye lógica para renderizar logotipos definidos en la configuración de Starlight.

#### `Search`

**Componente por defecto:** [`Search.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Search.astro)

Componente utilizado para renderizar la UI de búsqueda de Starlight.
La implementación predeterminada incluye el botón en el encabezado y el código para mostrar un modal de búsqueda cuando se hace clic y cargar la UI de [Pagefind](https://pagefind.app/).

Cuando [`pagefind`](/es/reference/configuration/#pagefind) está deshabilitado, el componente de búsqueda predeterminado no se renderizará. Sin embargo, si reemplazas `Search`, tu componente personalizado siempre se renderizará incluso si la opción de configuración `pagefind` es `false`. Esto te permite agregar una interfaz de usuario para proveedores de búsqueda alternativos cuando se deshabilita Pagefind.

#### `SocialIcons`

**Componente por defecto:** [`SocialIcons.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/SocialIcons.astro)

Componente renderizado en el encabezado del sitio que incluye enlaces de iconos sociales.
La implementación predeterminada utiliza la opción [`social`](/es/reference/configuration/#social) en la configuración de Starlight para renderizar iconos y enlaces.

#### `ThemeSelect`

**Componente por defecto:** [`ThemeSelect.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/ThemeSelect.astro)

Componente renderizado en el encabezado del sitio que permite a los usuarios seleccionar su esquema de color preferido.

#### `LanguageSelect`

**Componente por defecto:** [`LanguageSelect.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/LanguageSelect.astro)

Componente renderizado en el encabezado del sitio que permite a los usuarios cambiar a un idioma diferente.

---

### Barra lateral global

La barra lateral global de Starlight incluye la navegación principal del sitio.
En los pantallas estrechas esto está oculto detrás de un menú desplegable.

#### `Sidebar`

**Componente por defecto:** [`Sidebar.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Sidebar.astro)

Componente renderizado antes del contenido de la página que contiene la navegación global.
La implementación predeterminada muestra una barra lateral lo suficientemente ancha y dentro de un menú desplegable en pantallas estrechas (móviles).
También renderiza [`<MobileMenuFooter />`](#mobilemenufooter) para mostrar elementos adicionales dentro del menú móvil.

#### `MobileMenuFooter`

**Componente por defecto:** [`MobileMenuFooter.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MobileMenuFooter.astro)

Componente renderizado en la parte inferior del menú desplegable móvil.
La implementación por defecto renderiza [`<ThemeSelect />`](#themeselect) y [`<LanguageSelect />`](#languageselect).

---

### Barra lateral de la página

La barra lateral de la página de Starlight es responsable de mostrar una tabla de contenidos que describe los subtítulos de la página actual.
En pantallas estrechas esto se colapsa en un menú desplegable fijado.

#### `PageSidebar`

**Componente por defecto:** [`PageSidebar.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/PageSidebar.astro)

El componente renderizado antes del contenido principal de la página para mostrar una tabla de contenidos.
La implementación renderiza [`<TableOfContents />`](#tableofcontents) y [`<MobileTableOfContents />`](#mobiletableofcontents)

#### `TableOfContents`

**Componente por defecto:** [`TableOfContents.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/TableOfContents.astro)

Componente que renderiza la tabla de contenidos de la página actual en pantallas más anchas.

#### `MobileTableOfContents`

**Componente por defecto:** [`MobileTableOfContents.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MobileTableOfContents.astro)

Componente que renderiza la tabla de contenidos de la página actual en pantallas más estrechas (móviles).

---

### Contenido

Estos componentes se renderizan en la columna principal del contenido de la página.

#### `Banner`

**Componente por defecto:** [`Banner.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Banner.astro)

Componente Banner renderizado en la parte superior de cada página.
La implementación predeterminada usa el valor de frontmatter [`banner`](/es/reference/frontmatter/#banner) de la página para decidir si renderizar o no.

#### `ContentPanel`

**Componente por defecto:** [`ContentPanel.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/ContentPanel.astro)

Componente plantilla utilizado para envolver secciones de la columna de contenido principal.

#### `PageTitle`

**Componente por defecto:** [`PageTitle.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/PageTitle.astro)

Componente que contiene el elemento `<h1>` de la página actual.

Las implementaciones deben asegurarse de establecer `id="_top"` en el elemento `<h1>` como en la implementación predeterminada.

#### `DraftContentNotice`

**Componente por defecto:** [`DraftContentNotice.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/DraftContentNotice.astro)

Aviso mostrado a los usuarios durante el desarrollo cuando la página actual está marcada como borrador.

#### `FallbackContentNotice`

**Componente por defecto:** [`FallbackContentNotice.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/FallbackContentNotice.astro)

Aviso mostrado a los usuarios en páginas donde no está disponible una traducción para el idioma actual.

Solo se usa en sitios multilingües.

#### `Hero`

**Componente por defecto:** [`Hero.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Hero.astro)

Componente renderizado en la parte superior de la página cuando [`hero`](/es/reference/frontmatter/#hero) está establecido en frontmatter.
La implementación predeterminada muestra un título grande, un lema y enlaces de llamada a la acción junto con una imagen opcional.

#### `MarkdownContent`

**Componente por defecto:** [`MarkdownContent.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MarkdownContent.astro)

Componente renderizado alrededor del contenido principal de cada página.
La implementación predeterminada configura estilos básicos para aplicar al contenido de Markdown.

Los estilos de contenido Markdown también están expuestos en `@astrojs/starlight/style/markdown.css` y están limitados al ámbito de la clase CSS `.sl-markdown-content`.

---

### Pie de página

Estos componentes se renderizan en la parte inferior de la columna principal del contenido de la página.

#### `Footer`

**Componente por defecto:** [`Footer.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Footer.astro)

Componente de pie de página que se muestra en la parte inferior de cada página.
La implementación predeterminada muestra [`<LastUpdated />`](#lastupdated), [`<Pagination />`](#pagination) y [`<EditLink />`](#editlink).

#### `LastUpdated`

**Componente por defecto:** [`LastUpdated.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/LastUpdated.astro)

Componente renderizado en el pie de página de la página para mostrar la fecha de la última actualización.

#### `EditLink`

**Componente por defecto:** [`EditLink.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/EditLink.astro)

Componente renderizado en el pie de página de la página para mostrar un enlace a donde se puede editar la página.

#### `Pagination`

**Componente por defecto:** [`Pagination.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Pagination.astro)

Componente renderizado en el pie de página de la página para mostrar flechas de navegación entre páginas anteriores/siguientes.


================================================
FILE: docs/src/content/docs/es/reference/plugins.md
================================================
---
title: Referencia de Plugins
description: Una descripción general de la API de plugins de Starlight.
tableOfContents:
  maxHeadingLevel: 4
---

Los plugins de Starlight pueden personalizar la configuración, la UI y el comportamiento, mientras que son fáciles de compartir y reutilizar.
Esta página de referencia documenta la API a la que tienen acceso los plugins.

Aprende más sobre el uso de un plugin de Starlight en la [Referencia de Configuración](/es/reference/configuration/#plugins) o visita la [exhibición de plugins](/es/resources/plugins/#plugins) para ver una lista de los plugins disponibles.

## Referencia rápida de la API

Un plugin de Starlight tiene la siguiente forma.
Consulta a continuación los detalles de las diferentes propiedades y parámetros del hook.

```ts
interface StarlightPlugin {
  name: string;
  hooks: {
    setup: (options: {
      config: StarlightUserConfig;
      updateConfig: (newConfig: StarlightUserConfig) => void;
      addIntegration: (integration: AstroIntegration) => void;
      astroConfig: AstroConfig;
      command: 'dev' | 'build' | 'preview';
      isRestart: boolean;
      logger: AstroIntegrationLogger;
    }) => void | Promise<void>;
  };
}
```

## `name`

**tipo:** `string`

Un plugin debe proporcionar un nombre único que lo describa. El nombre se utiliza cuando se [registran mensajes](#logger) relacionados con este plugin y puede ser utilizado por otros plugins para detectar la presencia de este plugin.

## `hooks`

Los hooks son funciones que Starlight llama para ejecutar código de plugin en momentos específicos. Actualmente, Starlight admite un único hook `setup`.

### `hooks.setup`

La función de configuración es llamada cuando se inicializa Starlight (durante el hook de integración [`astro:config:setup`](https://docs.astro.build/es/reference/integrations-reference/#astroconfigsetup)).

El hook `setup` se puede utilizar para actualizar la configuración de Starlight o añadir integraciones de Astro.

Este hook es llamado con las siguientes opciones:

#### `config`

**tipo:** `StarlightUserConfig`

Una copia de lectura de la [configuración de Starlight](/es/reference/configuration/) proporcionada por el usuario.
Esta configuración puede haber sido actualizada por otros plugins configurados antes del actual.

#### `updateConfig`

**tipo:** `(newConfig: StarlightUserConfig) => void`

Una función callback para actualizar la [configuración de Starlight](/es/reference/configuration/).
Proporciona las claves de configuración de nivel raíz que deseas sobreescribir.
Para actualizar los valores de configuración anidados, debes proporcionar el objeto anidado completo.

Para extender una opción de configuración existente sin sobreescribirla, extiende el valor existente en tu nuevo valor.
En el siguiente ejemplo, se agrega una nueva cuenta en [`social`](/es/reference/configuration/#social) a la configuración existente extendiendo 'config.social' en el nuevo objeto social:

```ts {6-11}
// plugin.ts
export default {
  name: 'add-twitter-plugin',
  hooks: {
    setup({ config, updateConfig }) {
      updateConfig({
        social: {
          ...config.social,
          twitter: 'https://twitter.com/astrodotbuild',
        },
      });
    },
  },
};
```

#### `addIntegration`

**tipo:** `(integration: AstroIntegration) => void`

Una función callback para añadir una [integración de Astro](https://docs.astro.build/es/reference/integrations-reference/) requerida por el plugin.

En el siguiente ejemplo, el plugin primero comprueba si la [integración de React de Astro](https://docs.astro.build/es/guides/integrations-guide/react/) está configurada y, si no lo está, utiliza `addIntegration()` para añadirla:

```ts {14} "addIntegration,"
// plugin.ts
import react from '@astrojs/react';

export default {
  name: 'plugin-using-react',
  hooks: {
    setup({ addIntegration, astroConfig }) {
      const isReactLoaded = astroConfig.integrations.find(
        ({ name }) => name === '@astrojs/react'
      );

      // Solo agrega la integración de React si aún no está cargada.
      if (!isReactLoaded) {
        addIntegration(react());
      }
    },
  },
};
```

#### `astroConfig`

**tipo:** `AstroConfig`

Una copia de lectura de la [configuración de Astro](https://docs.astro.build/es/reference/configuration-reference/) proporcionada por el usuario.

#### `command`

**tipo:** `'dev' | 'build' | 'preview'`

El comando usado para ejecutar Starlight:

- `dev` - El proyecto se ejecuta con `astro dev`
- `build` - El proyecto se ejecuta con `astro build`
- `preview` - El proyecto se ejecuta con `astro preview`

#### `isRestart`

**tipo:** `boolean`

`false` cuando el servidor de desarrollo se inicia, `true` cuando se activa una recarga.
Common reasons for a restart include a user editing their `astro.config.mjs` while the dev server is running.

#### `logger`

**tipo:** `AstroIntegrationLogger`

Una instancia del [logger de integración de Astro](https://docs.astro.build/es/reference/integrations-reference/#astrointegrationlogger) que puedes utilizar para escribir logs.
Todos los mensajes de registro se prefijarán con el nombre del plugin.

```ts {6}
// plugin.ts
export default {
  name: 'long-process-plugin',
  hooks: {
    setup({ logger }) {
      logger.info('Empezando un proceso largo…');
      // Algun proceso largo…
    },
  },
};
```

El ejemplo anterior registrará un mensaje que incluye el mensaje de información proporcionado:

```shell
[long-process-plugin] Empezando un proceso largo…
```

#### `injectTranslations`

**tipo:** `(translations: Record<string, Record<string, string>>) => void`

Una función callback para añadir o actualizar las strings de traducción utilizadas en las [APIs de localización](/es/guides/i18n/#usar-traducciones-de-ui) de Starlight.

En el siguiente ejemplo, un plugin inyecta traducciones para una string de UI personalizada llamada `myPlugin.doThing` para los locales `en` y `fr`:

```ts {6-13} /(injectTranslations)[^(]/
// plugin.ts
export default {
  name: 'plugin-with-translations',
  hooks: {
    setup({ injectTranslations }) {
      injectTranslations({
        en: {
          'myPlugin.doThing': 'Do the thing',
        },
        fr: {
          'myPlugin.doThing': 'Faire le truc',
        },
      });
    },
  },
};
```

Para usar las traducciones inyectadas en tu plugin de UI, sigue la [guía “Usar traducciones de UI”](/es/guides/i18n/#usar-traducciones-de-ui).

Los tipos para las strings de traducción inyectadas en un plugin se generan automáticamente en el proyecto de un usuario, pero aún no están disponibles cuando trabajas en el código de tu plugin.
Para tipar el objeto `locals.t` en el contexto de tu plugin, declara los siguientes espacios de nombres globales en un archivo de declaración de TypeScript:

```ts
// env.d.ts
declare namespace App {
  type StarlightLocals = import('@astrojs/starlight').StarlightLocals;
  // Define el objeto `locals.t` en el contexto de un plugin.
  interface Locals extends StarlightLocals {}
}

declare namespace StarlightApp {
  // Define las traducciones adicionales del plugin en la interfaz `I18n`.
  interface I18n {
    'myPlugin.doThing': string;
  }
}
```

También puedes inferir los tipos para la interfaz `StarlightApp.I18n` a partir de un archivo fuente si tienes un objeto que contiene tus traducciones.

Por ejemplo, dado el siguiente archivo fuente:

```ts title="ui-strings.ts"
export const UIStrings = {
  en: { 'myPlugin.doThing': 'Do the thing' },
  fr: { 'myPlugin.doThing': 'Faire le truc' },
};
```

La siguiente declaración inferiría los tipos de las claves en inglés del archivo fuente:

```ts title="env.d.ts"
declare namespace StarlightApp {
  type UIStrings = typeof import('./ui-strings').UIStrings.en;
  interface I18n extends UIStrings {}
}
```


================================================
FILE: docs/src/content/docs/es/reference/route-data.mdx
================================================
---
title: Referencia de los Datos de Ruta
description: La documentación de referencia completa para el objeto de datos de ruta de Starlight.
---

El objeto de datos de ruta de Starlight contiene información sobre la página actual.
Aprende más sobre cómo funciona el modelo de datos de Starlight en la guía de [“Datos de Ruta”](/es/guides/route-data/).

En los componentes de Astro, accede a los datos de ruta desde `Astro.locals.starlightRoute`:

```astro {4}
---
// src/components/Custom.astro

const { hasSidebar } = Astro.locals.starlightRoute;
---
```

En el [middleware de ruta](/es/guides/route-data/#personalización-de-los-datos-de-ruta), accede a los datos de ruta desde el objeto de contexto pasado a tu función de middleware:

```ts {5}
// src/routeData.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

export const onRequest = defineRouteMiddleware((context) => {
	const { hasSidebar } = context.locals.starlightRoute;
});
```

## `starlightRoute`

El objeto `starlightRoute` tiene las siguientes propiedades:

### `dir`

**Tipo:** `'ltr' | 'rtl'`

Dirección de escritura de la página.

### `lang`

**Tipo:** `string`

Etiqueta de idioma BCP-47 para la configuración regional de esta página, por ejemplo, `en`, `zh-CN` o `pt-BR`.

### `locale`

**Tipo:** `string | undefined`

La ruta base en la que se sirve un idioma. `undefined` para los slugs de la configuración regional raíz.

### `siteTitle`

**Tipo:** `string`

El título del sitio para la configuración regional de esta página.

### `siteTitleHref`

**Tipo:** `string`

El valor para el atributo `href` del título del sitio, que enlaza de vuelta a la página de inicio, por ejemplo, `/`.
Para sitios multilingües, esto incluirá la configuración regional actual, por ejemplo, `/en/` o `/zh-cn/`.

### `slug`

**Tipo:** `string`

El slug para esta página generado a partir del nombre del archivo de contenido.

Esta propiedad está obsoleta y se eliminará en una futura versión de Starlight.
Migra a la nueva API de Content Layer utilizando el [`docsLoader`](/es/manual-setup/#configura-las-colecciones-de-contenido) de Starlight y utiliza la propiedad [`id`](#id) en su lugar.

### `id`

**Tipo:** `string`

El slug para esta página o el ID único para esta página basado en el nombre del archivo de contenido si se utiliza el flag [`legacy.collections`](https://docs.astro.build/en/reference/legacy-flags/#collections).

### `isFallback`

**Tipo:** `boolean | undefined`

`true` si esta página no está traducida en el idioma actual y está utilizando contenido de respaldo de la configuración regional predeterminada.
Solo se utiliza en sitios multilingües.

### `entryMeta`

**Tipo:** `{ dir: 'ltr' | 'rtl'; lang: string }`

Metadatos de configuración regional para el contenido de la página. Puede ser diferente de los valores de configuración regional de nivel superior cuando una página está utilizando contenido de respaldo.

### `entry`

La entrada de la colección de contenido de Astro para la página actual.
Incluye los valores del frontmatter para la página actual en `entry.data`.

```ts
entry: {
	data: {
		title: string;
		description: string | undefined;
		// etc.
	}
}
```

Aprende más sobre la forma de este objeto en la referencia del [Tipo de Entrada de Colección de Astro](https://docs.astro.build/en/reference/modules/astro-content/#collectionentry).

### `sidebar`

**Tipo:** `SidebarEntry[]`

Entradas de la barra lateral de navegación del sitio para esta página.

### `hasSidebar`

**Tipo:** `boolean`

Indica si la barra lateral debe mostrarse o no en esta página.

### `pagination`

**Tipo:** `{ prev?: Link; next?: Link }`

Enlaces a la página anterior y siguiente en la barra lateral si está habilitada.

### `toc`

**Tipo:** `{ minHeadingLevel: number; maxHeadingLevel: number; items: TocItem[] } | undefined`

Tabla de contenido para esta página si está habilitada.

### `headings`

**Tipo:** `{ depth: number; slug: string; text: string }[]`

Array de todos los encabezados de Markdown extraídos de la página actual.
Utiliza [`toc`](#toc) en su lugar si deseas construir un componente de tabla de contenido que respete las opciones de configuración de Starlight.

### `lastUpdated`

**Tipo:** `Date | undefined`

Objeto `Date` de JavaScript que representa cuándo se actualizó por última vez esta página si está habilitado.

### `editUrl`

**Tipo:** `URL | undefined`

Objeto `URL` para la dirección donde se puede editar esta página si está habilitado.

### `head`

**tipo:** [`HeadConfig[]`](/es/reference/configuration/#headconfig)

Array de todas las etiquetas para incluir en el `<head>` de la página actual.
Incluye etiquetas importantes como `<title>` y `<meta charset="utf-8">`.

## Utilidades

### `defineRouteMiddleware()`

Utiliza la utilidad `defineRouteMiddleware()` para ayudar a tipar tu módulo de middleware de ruta:

```ts "defineRouteMiddleware"
// src/routeData.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

export const onRequest = defineRouteMiddleware((context) => {
	// ...
});
```

### Tipo `StarlightRouteData`

Si estás escribiendo código que necesita trabajar con los datos de ruta de Starlight, puedes importar el tipo `StarlightRouteData` para que coincida con la forma de `Astro.locals.starlightRoute`.

En el siguiente ejemplo, una función `usePageTitleInTOC()` actualiza los datos de ruta para utilizar el título de la página actual como etiqueta para el primer elemento de la tabla de contenido, reemplazando la etiqueta predeterminada "Overview".
El tipo `StarlightRouteData` te permite verificar si los cambios en los datos de ruta son válidos.

```ts "StarlightRouteData"
// src/route-utils.ts
import type { StarlightRouteData } from '@astrojs/starlight/route-data';

export function usePageTitleInTOC(starlightRoute: StarlightRouteData) {
	const overviewLink = starlightRoute.toc?.items[0];
	if (overviewLink) {
		overviewLink.text = starlightRoute.entry.data.title;
	}
}
```

Esta función se puede llamar desde un middleware de ruta:

```ts {3,6}
// src/route-middleware.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';
import { usePageTitleInTOC } from './route-utils';

export const onRequest = defineRouteMiddleware((context) => {
	usePageTitleInTOC(context.locals.starlightRoute);
});
```


================================================
FILE: docs/src/content/docs/es/resources/community-content.mdx
================================================
---
title: Contenido de la comunidad
description: ¡Descubre guías, artículos y videos producidos por la comunidad para ayudarte a aprender y construir con Starlight!
---

:::tip[¡Agrega el tuyo!]
¿Has producido contenido sobre Starlight?
¡Abre una PR añadiendo un enlace a esta página!
:::

import { CardGrid, LinkCard } from '@astrojs/starlight/components';

## Artículos y Reseñas

Aquí tienes una colección de publicaciones y artículos para aprender más sobre Starlight y las experiencias de otras personas:

<CardGrid>
	<LinkCard
		href="https://devm.io/open-source/starlight-astro"
		title="Generación de sitios estáticos con Starlight"
		description="“Ninguna idea es demasiado grande o demasiado pequeña al diseñar componentes” — una entrevista con Chris Swithinbank, líder de Starlight"
	/>
	<LinkCard
		href="https://frontendatscale.com/blog/hybrid-frontend-architecture/"
		title="Arquitectura híbrida de frontend con Astro y Starlight."
		description="Maxi Ferreira y Ben Holmes construyen un sitio de documentación con Starlight, TinaCMS, y un Playground de API interactivo con autenticación."
	/>
	<LinkCard
		href="https://www.olets.dev/posts/comparing-docs-site-builders-vuepress-vs-starlight/"
		title="Comparando constructores de sitios de documentación: VuePress vs. Starlight"
		description="¿Cómo se comparan estos dos frameworks?"
	/>
</CardGrid>

## Recetas y Guías

Las Recetas suelen ser cortas, centradas en guiar al lector a través de la realización de un ejemplo práctico de una tarea específica. ¡Las Recetas son una forma estupenda de añadir nuevas características o comportamientos a tu proyecto de Starlight siguiendo las instrucciones paso a paso! Otras guías pueden explicar conceptos relacionados con un área de contenido específica, como el uso de imágenes o trabajar con MDX.

Explora contenido producido por la comunidad mantenido por usuarios de Starlight:

<CardGrid>
	<LinkCard
		href="https://www.webpro.nl/scraps/versioned-docs-with-starlight-and-vercel"
		title="Documentación versionada con Starlight y Vercel"
		description="Una guía para implementar versiones separadas de la documentación para cada versión principal de un proyecto."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-heading-links"
		title="Agrega enlaces a los encabezados de Starlight"
		description="Una guía sobre cómo usar el plugin de rehype para compartir enlaces en secciones específicas de tu documentación"
	/>
	<LinkCard
		href="https://blog.otterlord.dev/posts/starlight-sponsors/"
		title="Agrega patrocinadores a tu sitio de Starlight"
		description="Una guía para implementar un componente personalizado de patrocinadores en la barra lateral de tu documentación"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-og-images"
		title="Agrega imágenes Open Graph a Starlight"
		description="Una guía para generar imágenes sociales y las etiquetas meta correspondientes para tus páginas"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-third-party-icon-sets"
		title="Utiliza conjuntos de iconos de terceros en Starlight"
		description="Una guía para usar unplugin-icons para ampliar la selección de los iconos disponibles para Starlight"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-custom-html-head"
		title="Edita las sección head del HTML para las páginas de Starlight"
		description="Aprende como agregar contenido común en la sección head como analíticas web, fuentes y scripts"
	/>
	<LinkCard
		href="https://dev.to/mrrobot/publishing-documentation-with-astro-starlight-691"
		title="Publicación de documentación con Astro Starlight"
		description="Comenzando con la documentación de Starlight."
	/>
	<LinkCard
		href="https://events-3bg.pages.dev/jotter/starlight/guide/"
		title="Habilita View Transitions"
		description="Consigue esa apariencia SPA con el soporte de View Transitions de Bag of Tricks"
	/>
	<LinkCard
		href="https://jamcomments.com/posts/structured-data-with-starlight"
		title="Agregando datos estructurados a las páginas de Starlight"
		description="Aprende a construir datos estructurados JSON-LD dinámicos para tus páginas de documentación."
	/>
	<LinkCard
		href="https://starlight-examples.netlify.app/"
		title="Ejemplos de Starlight"
		description="Una colección de embeds de StackBlitz que demuestran formas prácticas de hacer cosas en sitios de documentación de Starlight."
	/>
</CardGrid>

## Contenido en Video

Descubre videos y canales con contenido de Starlight, incluyendo transmisiones en vivo y contenido educativo.

import YouTubeGrid from '~/components/youtube-grid.astro';

### Videos de Astro

<YouTubeGrid
	videos={[
		{
			href: 'https://www.youtube.com/watch?v=5u0Ds7wzUeI',
			title: 'Starlight por Astro',
			description: 'Mira el video oficial del lanzamiento de Starlight',
		},
		{
			href: 'https://www.youtube.com/shorts/zjOWezSzd18',
			title: '🌟 MENOS DE 1 MINUTO',
			description:
				'¡Mira como Ben crea un nuevo sitio de Starlight en menos de un minuto!',
		},
	]}
/>

### Videos de la Comunidad y Transmisiones

<YouTubeGrid
	videos={[
		{
			href: 'https://www.youtube.com/watch?v=sF6UcV3moZg',
			title: 'Construyendo documentación con Starlight y Astro',
			description:
				'Ve a Chris y Alex sumergirse en Starlight en Code with CodingCat.dev',
		},
		{
			href: 'https://www.youtube.com/watch?v=sWkkHbwDeQc',
			title: 'Astro Starlight',
			description: 'Introducción a Starlight en menos de un minuto.',
		},
		{
			href: 'https://www.youtube.com/watch?v=-Ki-1E5gNCk',
			title:
				'Plantilla de documentación de Astro Starlight (¡construye documentación personalizada para tu aplicación!)',
			description:
				'Pon en marcha un nuevo sitio de Starlight en unos 5 minutos',
		},
		{
			href: 'https://www.youtube.com/watch?v=12o7WxjAxjM',
			title:
				'Incluye la documentación de Starlight en un proyecto de Next.js con proxies',
			description:
				'Configura Starlight como un proyecto de subdirectorio dentro de un sitio web de Next.js',
		},
		{
			href: 'https://www.youtube.com/watch?v=5pq80drDrNs',
			title:
				'Recreé la documentación de Shadcn en 30 minutos con esta increíble herramienta',
			description:
				'En este video repaso lo que hace que Starlight sea tan genial y por qué querrías probarlo en tu próximo proyecto.',
		},
		{
			href: 'https://www.youtube.com/watch?v=Q1E4Gkt63ko',
			title: 'Astro Starlight y emoji-blast con Chris Swithinbank',
			description:
				'Donde Chris, el creador del framework sobre framework Starlight de Astro, me guía a través de la configuración de un nuevo sitio web de emoji-blast. 🌟 🎇',
		},
	]}
/>


================================================
FILE: docs/src/content/docs/es/resources/plugins.mdx
================================================
---
title: Plugins e Integraciones
description: ¡Descubre herramientas de la comunidad como plugins e integraciones que amplían Starlight!
sidebar:
  order: 1
---

:::tip[¡Agrega el tuyo!]
¿Has construido un plugin o herramienta para Starlight?
¡Abre una PR añadiendo un enlace a esta página!
:::

## Plugins

Los [Plugins](/es/reference/plugins/) pueden personalizar la configuración, UI y comportamiento de Starlight, a la vez que son fáciles de compartir y reutilizar.
Amplia tu sitio con un plugins oficiales respaldados por el equipo de Starlight y plugins de la comunidad mantenidos por usuario de Starlight.

### Plugins oficiales

<CardGrid>
	<LinkCard
		href="/es/guides/site-search/#algolia-docsearch"
		title="Algolia DocSearch"
		description="Reemplaza Pagefind, el proveedor de búsqueda por defecto, por Algolia DocSearch."
	/>
</CardGrid>

### Plugins de la comunidad

<CardGrid>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-links-validator"
		title="starlight-links-validator"
		description="Comprueba si hay enlaces rotos en tus páginas de Starlight."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-typedoc"
		title="starlight-typedoc"
		description="Genera páginas de Starlight desde TypeScript usando TypeDoc"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-blog"
		title="starlight-blog"
		description="Agrega un blog a tu sitio de documentación."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-openapi"
		title="starlight-openapi"
		description="Crea páginas de documentación a partir de especificaciones OpenAPI/Swagger."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-obsidian"
		title="starlight-obsidian"
		description="Publica bóvedas de Obsidian en tu sitio de Starlight."
	/>
	<LinkCard
		href="https://astro-ghostcms.xyz/intro/starlight/install/"
		title="starlight-ghostcms"
		description="Agrega tus publicaciones de blog de GhostCMS junto con tus documentos de Starlight."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-image-zoom"
		title="starlight-image-zoom"
		description="Agrega capacidades de zoom a las imágenes de tu documentación."
	/>
	<LinkCard
		href="https://github.com/lorenzolewis/starlight-utils"
		title="starlight-utils"
		description="Extiende Starlight con una colección de utilidades comunes."
	/>
	<LinkCard
		href="https://github.com/trueberryless/starlight-view-modes"
		title="starlight-view-modes"
		description="Agrega diferentes capacidades de modo de vista a tu sitio de documentación."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-versions"
		title="starlight-versions"
		description="Agrega versiones a tus páginas de documentación de Starlight."
	/>
	<LinkCard
		href="https://inox-tools.fryuni.dev/star-warp"
		title="star-warp"
		description="Viaja a través de los resultados de búsqueda en tu documentación"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-heading-badges"
		title="starlight-heading-badges"
		description="Agrega insignias a tus encabezados de Markdown y MDX."
	/>
</CardGrid>

### Temas de la comunidad

Un tema es un plugin de Starlight que cambia la apariencia visual de un sitio con reemplazos de componentes, CSS personalizado u otras nuevas características.

<CardGrid>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-theme-rapide"
		title="starlight-theme-rapide"
		description="Tema de Starlight inspirado en el tema Vitesse de Visual Studio Code."
	/>
</CardGrid>

## Herramientas e integraciones de la comunidad

import { CardGrid, LinkCard } from '@astrojs/starlight/components';

Estas herramientas e integraciones de la comunidad se pueden utilizar para añadir características a tu sitio de Starlight.

<CardGrid>
	<LinkCard
		href="https://www.feelback.dev/blog/new-astro-starlight-integration/"
		title="FeelBack"
		description="Agrega un sistema de comentarios de usuarios a la páginas de tus docs."
	/>
	<LinkCard
		href="https://github.com/val-town/notion-to-astro"
		title="notion-to-astro"
		description="Convierte las exportaciones de Notion a docs de Astro Starlight."
	/>
	<LinkCard
		href="https://github.com/mattjennings/astro-live-code"
		title="astro-live-code"
		description="Renderiza bloques de código MDX como componentes interactivos."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-i18n"
		title="starlight-i18n"
		description="Extensión de Visual Studio Code para ayudar a traducir páginas de Starlight."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-package-managers"
		title="starlight-package-managers"
		description="Muestra rápidamente comandos relacionados con npm para varios gestores de paquetes."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-showcases"
		title="starlight-showcases"
		description="Conjunto de componentes de Starlight para crear páginas de vitrina."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/generator-starlight-plugin"
		title="@hideoo/starlight-plugin"
		description="Un generador para crear rápidamente plugins de Starlight."
	/>
	<LinkCard
		href="https://docs.contentisland.net/templates/starlight/"
		title="contentisland-cli"
		description="Conecta y sincroniza tu proyecto Starlight con Content Island Headless CMS para editar y gestionar tu documentación."
	/>
</CardGrid>


================================================
FILE: docs/src/content/docs/es/resources/showcase.mdx
================================================
---
title: Exhibición de Starlight
description: ¡Descubre sitios construidos con Starlight!
sidebar:
  label: Galería de sitios
---

:::tip[¡Agrega el tuyo!]
¿Has construido un sitio de Starlight o una herramienta para Starlight?
¡[Abre una PR](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md#showcase) agregando un enlace a esta página!
:::

## Sitios

import ShowcaseSites from '~/components/showcase-sites.astro';

Starlight ya está siendo usado en producción. Estos son algunos de los sitios en la web:

<ShowcaseSites />

Mira todos los [repositorios públicos de proyectos usando Starlight en GitHub](https://github.com/withastro/starlight/network/dependents).


================================================
FILE: docs/src/content/docs/es/resources/themes.mdx
================================================
---
title: Temas
description: Dale estilo a tus documentos con un tema de la comunidad para Starlight
tableOfContents: false
sidebar:
  order: 2
head:
  - tag: style
    content: |
      body { --sl-content-width: 66.75rem; }
---

import ThemeGrid from '~/components/theme-grid.astro';

Un tema es un plugin de Starlight que cambia la apariencia visual de un sitio con [CSS personalizado](/es/guides/css-and-tailwind/), [sustituciones de componentes](/es/guides/overriding-components/) u otras nuevas funcionalidades.

## Temas de la Comunidad

Instala un tema creado por la comunidad para personalizar rápidamente la apariencia de tu sitio.

<ThemeGrid
	labels={{
		/** Etiqueta accesible para el interruptor de tema. */
		legend: 'Vista previa',
		/** Etiqueta accesible para la variante de esquema de color oscuro. */
		dark: 'Oscuro',
		/** Etiqueta accesible para la variante de esquema de color claro. */
		light: 'Claro',
	}}
	themes={[
		{
			title: 'Starlight Rapide',
			description:
				'Tema de Starlight inspirado en el tema Vitesse de Visual Studio Code.',
			href: 'https://starlight-theme-rapide.vercel.app/',
			previews: { light: 'rapide-light.png', dark: 'rapide-dark.png' },
		},
		{
			title: 'Starlight Obsidian Theme',
			description:
				'Tema de Starlight inspirado en el estilo de los sitios de Obsidian Publish.',
			href: 'https://fevol.github.io/starlight-theme-obsidian/',
			previews: { light: 'obsidian-light.png', dark: 'obsidian-dark.png' },
		},
		{
			title: 'Catppuccin for Starlight',
			description: 'Suave tema pastel para Starlight.',
			href: 'https://catppuccin-starlight.otterlord.dev/',
			previews: { light: 'catppuccin-light.png', dark: 'catppuccin-dark.png' },
		},
		{
			title: 'Ion',
			description: 'Un tema elegante y moderno para Starlight.',
			href: 'https://louisescher.github.io/starlight-ion-theme/',
			previews: { light: 'ion-light.png', dark: 'ion-dark.png' },
		},
		{
			title: 'Starlight Black',
			description: 'Tema de Starlight inspirado en la documentación de shadcn.',
			href: 'https://starlight-theme-black.vercel.app/',
			previews: { light: 'black-light.png', dark: 'black-dark.png' },
		},
		{
			title: 'Starlight Flexoki',
			description:
				'Un tema cálido y amigable basado en la paleta de colores Flexoki.',
			href: 'https://delucis.github.io/starlight-theme-flexoki/',
			previews: { light: 'flexoki-light.png', dark: 'flexoki-dark.png' },
		},
		{
			title: 'Starlight Nova',
			description: 'Un tema moderno y hermoso para Starlight.',
			href: 'https://starlight-theme-nova.pages.dev/',
			previews: { light: 'nova-light.png', dark: 'nova-dark.png' },
		},
		{
			title: 'Tema Starlight NextJS',
			description: 'Tema de Starlight inspirado en la documentación de NextJS.',
			href: 'https://starlight-nextjs-theme.trueberryless.org/',
			previews: { light: 'nextjs-light.png', dark: 'nextjs-dark.png' },
		},
	]}
/>

:::tip[¡Añade el tuyo!]
¿Has creado un tema para Starlight?
¡[Abre una PR](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md#themes) añadiendo tu tema a esta página!
:::


================================================
FILE: docs/src/content/docs/fr/404.md
================================================
---
title: Page Introuvable
template: splash
editUrl: false
lastUpdated: false
hero:
  title: '404'
  tagline: <strong>Houston, nous avons un problème.</strong> Nous n’avons pas pu trouver cette page.<br>Vérifiez l’URL ou essayez la barre de recherche.
  actions:
    - text: Retourner à l’accueil
      icon: right-arrow
      link: /fr/
      variant: primary
---


================================================
FILE: docs/src/content/docs/fr/components/asides.mdx
================================================
---
title: Encarts
description: Apprenez à utiliser les encarts dans Starlight pour afficher des informations secondaires à côté du contenu principal d'une page.
---

import { Aside } from '@astrojs/starlight/components';

Pour afficher des informations secondaires à côté du contenu principal d'une page, utilisez le composant `<Aside>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<Aside slot="preview">
Incluez des informations supplémentaires non essentielles avec le composant `<Aside>`.
</Aside>

</Preview>

## Importation

```tsx
import { Aside } from '@astrojs/starlight/components';
```

## Utilisation

Affichez un encart (également connus sous le nom de « admonition » ou « aside » en anglais) en utilisant le composant `<Aside>`.

Le composant `<Aside>` peut avoir un attribut facultatif [`type`](#type), qui contrôle la couleur, l'icône et le titre par défaut de l'encart.

<Preview>

````mdx
import { Aside } from '@astrojs/starlight/components';

<Aside>Un peu de contenu dans un encart.</Aside>

<Aside type="caution">Quelques mises en garde.</Aside>

<Aside type="tip">

D'autres contenus sont également pris en charge dans les encarts.

```js
// Un extrait de code, par exemple.
```

</Aside>

<Aside type="danger">Ne communiquez votre mot de passe à personne.</Aside>
````

<Fragment slot="markdoc">

````markdoc
{% aside %}
Un peu de contenu dans un encart.
{% /aside %}

{% aside type="caution" %}
Quelques mises en garde.
{% /aside %}

{% aside type="tip" %}
D'autres contenus sont également pris en charge dans les encarts.

```js
// Un extrait de code, par exemple.
```
{% /aside %}

{% aside type="danger" %}
Ne communiquez votre mot de passe à personne.
{% /aside %}
````

</Fragment>

<Fragment slot="preview">

    <Aside>Un peu de contenu dans un encart.</Aside>

    <Aside type="caution">Quelques mises en garde.</Aside>

    <Aside type="tip">

    D'autres contenus sont également pris en charge dans les encarts.

    ```js
    // Un extrait de code, par exemple.
    ```

    </Aside>

    <Aside type="danger">Ne communiquez votre mot de passe à personne.</Aside>

</Fragment>

</Preview>

Starlight fournit également une syntaxe personnalisée pour afficher des encarts dans du contenu Markdown et MDX comme alternative au composant `<Aside>`.
Voir le guide [« Création de contenu en Markdown »](/fr/guides/authoring-content/#encarts) pour plus de détails sur la syntaxe personnalisée.

### Utiliser des titres personnalisés

Remplacez les titres par défaut des encarts en utilisant l'attribut [`title`](#title).

<Preview>

```mdx 'title="Attention !"'
import { Aside } from '@astrojs/starlight/components';

<Aside type="caution" title="Attention !">
	Un encart d'avertissement *avec* un titre personnalisé.
</Aside>
```

<Fragment slot="markdoc">

```markdoc 'title="Attention !"'
{% aside type="caution" title="Attention !" %}
Un encart d'avertissement *avec* un titre personnalisé.
{% /aside %}
```

</Fragment>

<Aside slot="preview" type="caution" title="Attention !">
	Un encart d'avertissement *avec* un titre personnalisé.
</Aside>

</Preview>

### Utiliser des icônes personnalisées

Remplacez les icônes par défaut des encarts en utilisant l'attribut [`icon`](#icon) défini avec le nom de [l'une des icônes intégrées à Starlight](/fr/reference/icons/#toutes-les-icônes).

<Preview>

```mdx 'icon="starlight"'
import { Aside } from '@astrojs/starlight/components';

<Aside type="tip" icon="starlight">
	Un encart d'astuce *avec* une icône personnalisée.
</Aside>
```

<Fragment slot="markdoc">

```markdoc 'icon="starlight"'
{% aside type="tip" icon="starlight" %}
Un encart d'astuce *avec* une icône personnalisée.
{% /aside %}
```

</Fragment>

<Aside slot="preview" type="tip" icon="starlight">
	Un encart d'astuce *avec* une icône personnalisée.
</Aside>

</Preview>

## Props de `<Aside>`

**Implémentation :** [`Aside.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Aside.astro)

Le composant `<Aside>` accepte les props suivantes :

### `type`

**Type :** `'note' | 'tip' | 'caution' | 'danger'`  
**Par défaut :** `'note'`

Le type d'encart à afficher :

- L'encart `note` (par défaut) est bleu et affiche une icône d'information.
- L'encart `tip` est violet et affiche une icône de fusée.
- L'encart `caution` est jaune et affiche une icône d'avertissement triangulaire.
- L'encart `danger` est rouge et affiche une icône d'avertissement octogonale.

### `title`

**Type :** `string`

Le titre de l'encart à afficher.
Si `title` n'est pas défini, le titre par défaut du `type` de l'encart en cours sera utilisé.

### `icon`

**Type :** [`StarlightIcon`](/fr/reference/icons/#type-starlighticon)

Un encart peut inclure un attribut `icon` défini avec le nom de [l'une des icônes intégrées à Starlight](/fr/reference/icons/#toutes-les-icônes).


================================================
FILE: docs/src/content/docs/fr/components/badges.mdx
================================================
---
title: Badges
description: Apprenez à utiliser les badges dans Starlight pour afficher des informations supplémentaires.
---

import { Badge } from '@astrojs/starlight/components';

Pour afficher de petits éléments d'information, tels qu'un statut ou une étiquette, utilisez le composant `<Badge>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<Badge slot="preview" text="Nouveau" />

</Preview>

## Importation

```tsx
import { Badge } from '@astrojs/starlight/components';
```

## Utilisation

Affichez un badge en utilisant le composant `<Badge>` et passez le contenu que vous souhaitez afficher à l'attribut [`text`](#text) du composant `<Badge>`.

Par défaut, le badge utilisera la couleur d'accentuation du thème de votre site.
Pour utiliser une des couleurs de badge disponibles, définissez l'attribut [`variant`](#variant) à l'une des valeurs prises en charge.

<Preview>

```mdx
import { Badge } from '@astrojs/starlight/components';

- <Badge text="Note" variant="note" />
- <Badge text="Succès" variant="success" />
- <Badge text="Astuce" variant="tip" />
- <Badge text="Attention" variant="caution" />
- <Badge text="Danger" variant="danger" />
```

<Fragment slot="markdoc">

```markdoc
- {% badge text="Note" variant="note" /%}
- {% badge text="Succès" variant="success" /%}
- {% badge text="Astuce" variant="tip" /%}
- {% badge text="Attention" variant="caution" /%}
- {% badge text="Danger" variant="danger" /%}
```

</Fragment>

<Fragment slot="preview">
	- <Badge text="Note" variant="note" />
	- <Badge text="Succès" variant="success" />
	- <Badge text="Astuce" variant="tip" />
	- <Badge text="Attention" variant="caution" />
	- <Badge text="Danger" variant="danger" />
</Fragment>

</Preview>

### Utiliser différentes tailles

Utilisez l'attribut [`size`](#size) pour contrôler la taille du texte du badge.

<Preview>

```mdx /size="\w+"/
import { Badge } from '@astrojs/starlight/components';

- <Badge text="Nouveau" size="small" />
- <Badge text="Nouveau et amélioré" size="medium" />
- <Badge text="Nouveau, amélioré et plus grand" size="large" />
```

<Fragment slot="markdoc">

```markdoc /size="\w+"/
- {% badge text="Nouveau" size="small" /%}
- {% badge text="Nouveau et amélioré" size="medium" /%}
- {% badge text="Nouveau, amélioré et plus grand" size="large" /%}
```

</Fragment>

<Fragment slot="preview">
	- <Badge text="Nouveau" size="small" />
	- <Badge text="Nouveau et amélioré" size="medium" />
	- <Badge text="Nouveau, amélioré et plus grand" size="large" />
</Fragment>

</Preview>

### Personnaliser les badges

Personnalisez les badges en utilisant n'importe quel autre attribut de l'élément `<span>` tel que `class` ou `style` avec du CSS personnalisé.

<Preview>

```mdx "style={{ fontStyle: 'italic' }}"
import { Badge } from '@astrojs/starlight/components';

<Badge text="Personnalisé" variant="success" style={{ fontStyle: 'italic' }} />
```

<Fragment slot="markdoc">

```markdoc 'style="font-style: italic;"'
{% badge text="Personnalisé" variant="success" style="font-style: italic;" /%}
```

</Fragment>

<Badge
	slot="preview"
	text="Personnalisé"
	variant="success"
	style={{ fontStyle: 'italic' }}
/>

</Preview>

## Props de `<Badge>`

**Implémentation :** [`Badge.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Badge.astro)

Le composant `<Badge>` accepte les props suivantes ainsi que [tous les autres attributs de l'élément `<span>`](https://developer.mozilla.org/fr/docs/Web/HTML/Global_attributes) :

### `text`

**Obligatoire**  
**Type :** `string`

Le texte à afficher dans le badge.

### `variant`

**Type :** `'note' | 'danger' | 'success' | 'caution' | 'tip' | 'default'`  
**Par défaut :** `'default'`

La variante de couleur du badge à utiliser : `note` (bleu), `tip` (violet), `danger` (rouge), `caution` (orange), `success` (vert), ou `default` (couleur d'accentuation du thème).

### `size`

**Type :** `'small' | 'medium' | 'large'`

Définit la taille du badge à afficher.


================================================
FILE: docs/src/content/docs/fr/components/card-grids.mdx
================================================
---
title: Grilles de cartes
description: Apprenez à regrouper plusieurs cartes dans une grille dans Starlight.
sidebar:
  order: 4
---

import { Card, CardGrid, LinkCard } from '@astrojs/starlight/components';

Pour regrouper plusieurs composants [`<Card>`](/fr/components/cards/) ou [`<LinkCard>`](/fr/components/link-cards/) dans une grille, utilisez le composant `<CardGrid>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<CardGrid slot="preview">
	<Card title="Étoiles" icon="star">
		Sirius, Véga, Bételgeuse
	</Card>
	<Card title="Lunes" icon="moon">
		Io, Europe, Ganymède
	</Card>
</CardGrid>

</Preview>

## Importation

```tsx
import { CardGrid } from '@astrojs/starlight/components';
```

## Utilisation

### Grouper des cartes

Affichez plusieurs composants [`<Card>`](/fr/components/cards/) côte à côte lorsqu'il y a suffisamment d'espace en les regroupant à l'aide du composant `<CardGrid>`.

<Preview>

```mdx {3,10}
import { Card, CardGrid } from '@astrojs/starlight/components';

<CardGrid>
	<Card title="Regardez-ça" icon="open-book">
		Contenu intéressant que vous souhaitez mettre en évidence.
	</Card>
	<Card title="Et autre chose" icon="information">
		Plus d'informations que vous souhaitez partager.
	</Card>
</CardGrid>
```

<Fragment slot="markdoc">

```markdoc {1,9}
{% cardgrid %}
{% card title="Regardez-ça" icon="open-book" %}
Contenu intéressant que vous souhaitez mettre en évidence.
{% /card %}

{% card title="Et autre chose" icon="information" %}
Plus d'informations que vous souhaitez partager.
{% /card %}
{% /cardgrid %}
```

</Fragment>

<CardGrid slot="preview">
	<Card title="Regardez-ça" icon="open-book">
		Contenu intéressant que vous souhaitez mettre en évidence.
	</Card>
	<Card title="Et autre chose" icon="information">
		Plus d'informations que vous souhaitez partager.
	</Card>
</CardGrid>

</Preview>

### Grouper des cartes de liaison

Affichez plusieurs composants [`<LinkCard>`](/fr/components/link-cards/) côte à côte lorsqu'il y a suffisamment d'espace en les regroupant à l'aide du composant `<CardGrid>`.

<Preview>

```mdx {3,9}
import { LinkCard, CardGrid } from '@astrojs/starlight/components';

<CardGrid>
	<LinkCard
		title="Création de contenu en Markdown"
		href="/fr/guides/authoring-content/"
	/>
	<LinkCard title="Composants" href="/fr/components/using-components/" />
</CardGrid>
```

<Fragment slot="markdoc">

```markdoc {1,7}
{% cardgrid %}
{% linkcard
   title="Création de contenu en Markdown"
	 href="/fr/guides/authoring-content/" /%}

{% linkcard title="Composants" href="/fr/components/using-components/" /%}
{% /cardgrid %}
```

</Fragment>

<CardGrid slot="preview">
	<LinkCard
		title="Création de contenu en Markdown"
		href="/fr/guides/authoring-content/"
	/>
	<LinkCard title="Composants" href="/fr/components/using-components/" />
</CardGrid>

</Preview>

### Décaler des cartes

Décalez la deuxième colonne de la grille verticalement pour ajouter un intérêt visuel en ajoutant l'attribut [`stagger`](#stagger) au composant `<CardGrid>`.

Cet attribut est utile sur votre page d'accueil pour afficher les principales fonctionnalités de votre projet.

<Preview>

```mdx "stagger"
import { Card, CardGrid } from '@astrojs/starlight/components';

<CardGrid stagger>
	<Card title="Regardez-ça" icon="open-book">
		Contenu intéressant que vous souhaitez mettre en évidence.
	</Card>
	<Card title="Et autre chose" icon="information">
		Plus d'informations que vous souhaitez partager.
	</Card>
</CardGrid>
```

<Fragment slot="markdoc">

```markdoc "stagger=true"
{% cardgrid stagger=true %}
{% card title="Regardez-ça" icon="open-book" %}
Contenu intéressant que vous souhaitez mettre en évidence.
{% /card %}

{% card title="Et autre chose" icon="information" %}
Plus d'informations que vous souhaitez partager.
{% /card %}
{% /cardgrid %}
```

</Fragment>

<CardGrid slot="preview" stagger>
	<Card title="Regardez-ça" icon="open-book">
		Contenu intéressant que vous souhaitez mettre en évidence.
	</Card>
	<Card title="Et autre chose" icon="information">
		Plus d'informations que vous souhaitez partager.
	</Card>
</CardGrid>

</Preview>

## Props de `<CardGrid>`

**Implémentation :** [`CardGrid.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/CardGrid.astro)

Le composant `<CardGrid>` accepte les props suivantes :

### `stagger`

**Type :** `boolean`

Définit si les cartes de la grille doivent être décalées ou non.


================================================
FILE: docs/src/content/docs/fr/components/cards.mdx
================================================
---
title: Cartes
description: Apprenez à utiliser des cartes dans Starlight pour afficher du contenu dans un cadre.
sidebar:
  order: 2
---

import { Card } from '@astrojs/starlight/components';

Pour afficher du contenu dans un cadre correspondant aux styles de Starlight, utilisez le composant `<Card>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<Card slot="preview" title="Lunes" icon="moon">
	Io, Europe, Ganymède
</Card>

</Preview>

## Importation

```tsx
import { Card } from '@astrojs/starlight/components';
```

## Utilisation

Affichez une carte en utilisant le composant `<Card>` et fournissez un titre à la carte en utilisant la propriété [`title`](#title).

<Preview>

```mdx
import { Card } from '@astrojs/starlight/components';

<Card title="Regardez-ça">
	Contenu intéressant que vous souhaitez mettre en évidence.
</Card>
```

<Fragment slot="markdoc">

```markdoc
{% card title="Regardez-ça" %}
Contenu intéressant que vous souhaitez mettre en évidence.
{% /card %}
```

</Fragment>

<Card slot="preview" title="Regardez-ça">
	Contenu intéressant que vous souhaitez mettre en évidence.
</Card>

</Preview>

### Ajouter des icônes aux cartes

Incluez une icône dans une carte en utilisant l'attribut [`icon`](#icon) défini avec le nom de [l'une des icônes intégrées à Starlight](/fr/reference/icons/#toutes-les-icônes).

<Preview>

```mdx 'icon="star"'
import { Card } from '@astrojs/starlight/components';

<Card title="Étoiles" icon="star">
	Sirius, Véga, Bételgeuse
</Card>
```

<Fragment slot="markdoc">

```markdoc 'icon="star"'
{% card title="Étoiles" icon="star" %}
Sirius, Véga, Bételgeuse
{% /card %}
```

</Fragment>

<Card slot="preview" title="Étoiles" icon="star">
	Sirius, Véga, Bételgeuse
</Card>

</Preview>

### Grouper des cartes

Affichez plusieurs cartes côte à côte lorsqu'il y a suffisamment d'espace en les regroupant à l'aide du composant [`<CardGrid>`](/fr/components/card-grids/).
Consultez le guide [« Grouper des cartes »](/fr/components/card-grids/#grouper-des-cartes) pour un exemple.

## Props de `<Card>`

**Implémentation :** [`Card.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Card.astro)

Le composant `<Card>` accepte les props suivantes :

### `title`

**Obligatoire**  
**Type :** `string`

Le titre de la carte à afficher.

### `icon`

**Type :** `string`

Une carte peut inclure un attribut `icon` défini avec le nom de [l'une des icônes intégrées à Starlight](/fr/reference/icons/#toutes-les-icônes).


================================================
FILE: docs/src/content/docs/fr/components/code.mdx
================================================
---
title: Code
description: Apprenez à afficher du code avec coloration syntaxique dans Starlight sans blocs de code Markdown.
---

import { Code } from '@astrojs/starlight/components';

Le composant `<Code>` affiche du code avec coloration syntaxique.
Il est utile lorsque l'utilisation d'un [bloc de code Markdown](/fr/guides/authoring-content/#blocs-de-code) n'est pas possible, par exemple pour afficher des données provenant de sources externes comme des fichiers, des bases de données ou des API.

import Preview from '~/components/component-preview.astro';

<Preview>

<Code
	slot="preview"
	code={`## Bienvenue

Bonjour depuis **l'espace** !`}
lang="md"
title="exemple.md"
ins={3}
/>

</Preview>

## Importation

```tsx
import { Code } from '@astrojs/starlight/components';
```

## Utilisation

Utilisez le composant `<Code>` pour afficher du code avec coloration syntaxique, par exemple lorsque vous affichez du code provenant de sources externes.

Consultez la [documentation sur le « Composant Code » d'Expressive Code](https://expressive-code.com/key-features/code-component/) pour plus de détails sur l'utilisation du composant `<Code>` et la liste des props disponibles.

<Preview>

```mdx
import { Code } from '@astrojs/starlight/components';

export const exampleCode = `console.log("Cela peut provenir d'un fichier ou d'un CMS !");`;
export const fileName = 'exemple.js';
export const highlights = ['fichier', 'CMS'];

<Code code={exampleCode} lang="js" title={fileName} mark={highlights} />
```

<Fragment slot="markdoc">

```markdoc
{% code
	 code="console.log(\"Cela peut provenir d'un fichier ou d'un CMS !\");"
   lang="js"
   title="exemple.js"
   meta="'fichier' 'CMS'" /%}
```

</Fragment>

export const exampleCode = `console.log("Cela peut provenir d'un fichier ou d'un CMS !");`;
export const fileName = 'exemple.js';
export const highlights = ['fichier', 'CMS'];

<Code
	slot="preview"
	code={exampleCode}
	lang="js"
	title={fileName}
	mark={highlights}
/>

</Preview>

### Afficher du code importé

Dans les fichiers MDX et les composants Astro, utilisez le [suffixe d'importation `?raw` de Vite](https://vite.dev/guide/assets#importing-asset-as-string) pour importer n'importe quel fichier de code sous forme de chaîne de caractères.
Vous pouvez ensuite passer cette chaîne importée au composant `<Code>` pour l'inclure dans votre page.

<Preview>

```mdx "?raw"
# src/content/docs/example.mdx

import { Code } from '@astrojs/starlight/components';
import importedCode from '/tsconfig.json?raw';

<Code code={importedCode} lang="json" title="tsconfig.json" />
```

import importedCode from '../../../../../../examples/basics/tsconfig.json?raw';

<Code slot="preview" code={importedCode} lang="json" title="tsconfig.json" />

</Preview>

## Props de `<Code>`

**Implémentation :** [`Code.astro`](https://github.com/expressive-code/expressive-code/blob/main/packages/astro-expressive-code/components/Code.astro)

Le composant `<Code>` accepte toutes les props documentées dans la [documentation sur le « Composant Code » d'Expressive Code](https://expressive-code.com/key-features/code-component/#available-props).


================================================
FILE: docs/src/content/docs/fr/components/file-tree.mdx
================================================
---
title: Arborescence de fichiers
description: Apprenez à afficher la structure d'un répertoire avec des icônes de fichiers et des sous-répertoires repliables dans Starlight.
---

import { FileTree } from '@astrojs/starlight/components';

Pour afficher la structure d'un répertoire avec des icônes de fichiers et des sous-répertoires repliables, utilisez le composant `<FileTree>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<FileTree slot="preview">

- astro.config.mjs un fichier **important**
- package.json
- README.md
- src
  - components
    - **Header.astro**
  - …
- pages/

</FileTree>

</Preview>

## Importation

```tsx
import { FileTree } from '@astrojs/starlight/components';
```

## Utilisation

Affichez une arborescence de fichiers avec des icônes de fichiers et des sous-répertoires repliables en utilisant le composant `<FileTree>`.

Spécifiez la structure de vos fichiers et répertoires avec une [liste Markdown non ordonnée](https://www.markdownguide.org/basic-syntax/#unordered-lists) à l'intérieur de `<FileTree>`.
Créez un sous-répertoire à l'aide d'une liste imbriquée ou ajoutez un `/` à la fin d'un élément de liste pour l'afficher comme un répertoire sans contenu spécifique.

<Preview>

```mdx
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- astro.config.mjs
- package.json
- src
  - components
    - Header.astro
    - Title.astro
  - pages/

</FileTree>
```

<Fragment slot="markdoc">

```markdoc
{% filetree %}
- astro.config.mjs
- package.json
- src
  - components
    - Header.astro
    - Title.astro
  - pages/
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- astro.config.mjs
- package.json
- src
  - components
    - Header.astro
    - Title.astro
  - pages/

</FileTree>

</Preview>

### Mettre en évidence les entrées

Faites ressortir un fichier ou un répertoire en mettant son nom en gras, par exemple `**README.md**`.

<Preview>

```mdx {7}
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src
  - components
    - **Header.astro**
    - Title.astro

</FileTree>
```

<Fragment slot="markdoc">

```markdoc {4}
{% filetree %}
- src
  - components
    - **Header.astro**
    - Title.astro
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- src
  - components
    - **Header.astro**
    - Title.astro

</FileTree>

</Preview>

### Ajouter des commentaires

Ajoutez un commentaire à un fichier ou à un répertoire en ajoutant du texte après le nom.
La syntaxe de mise en forme Markdown, telle que le gras et l'italique, est prise en charge dans les commentaires.

<Preview>

```mdx {7}
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src
  - components
    - Header.astro un fichier **important**
    - Title.astro

</FileTree>
```

<Fragment slot="markdoc">

```markdoc {4}
{% filetree %}
- src
  - components
    - Header.astro un fichier **important**
    - Title.astro
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- src
  - components
    - Header.astro un fichier **important**
    - Title.astro

</FileTree>

</Preview>

### Ajouter des entrées fictives

Ajoutez des fichiers et des répertoires fictifs en utilisant soit `...` soit `…` comme nom.
Cela peut être utile pour indiquer à un lecteur qu'un dossier est censé contenir plus d'éléments sans les spécifier tous explicitement.

<Preview>

```mdx {8}
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src
  - components
    - Header.astro
    - …

</FileTree>
```

<Fragment slot="markdoc">

```markdoc {5}
{% filetree %}
- src
  - components
    - Header.astro
    - …
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- src
  - components
    - Header.astro
    - …

</FileTree>

</Preview>

### Échapper les caractères spéciaux

Échappez les caractères spéciaux tels que les tirets bas ou les espaces dans les noms de fichiers en entourant le nom de fichier avec des accents graves.

<Preview>

```mdx
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- `__init__.py`
- `Hello world.txt`
- **`À LIRE EN PREMIER.md`**

</FileTree>
```

<Fragment slot="markdoc">

```markdoc
{% filetree %}
- `__init__.py`
- `Hello world.txt`
- **`À LIRE EN PREMIER.md`**
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- `__init__.py`
- `Hello world.txt`
- **`À LIRE EN PREMIER.md`**

</FileTree>

</Preview>

## Props de `<FileTree>`

**Implémentation :** [`FileTree.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/FileTree.astro)

Le composant `<FileTree>` n'accepte aucune props.


================================================
FILE: docs/src/content/docs/fr/components/icons.mdx
================================================
---
title: Icônes
description: Apprenez à afficher des icônes avec Starlight.
---

import { Icon } from '@astrojs/starlight/components';

Pour afficher des icônes depuis un [ensemble d'icônes disponibles](/fr/reference/icons/#toutes-les-icônes) avec Starlight, utilisez le composant `<Icon>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<Icon
	slot="preview"
	name="open-book"
	color="var(--sl-color-text-accent)"
	size="4rem"
/>

</Preview>

## Importation

```tsx
import { Icon } from '@astrojs/starlight/components';
```

## Utilisation

Affichez une icône en utilisant le composant `<Icon>`.
Une icône requiert un attribut [`name`](#name) défini avec [une des icônes disponibles avec Starlight](/fr/reference/icons/#toutes-les-icônes) et peut éventuellement inclure un [`label`](#label) pour fournir un contexte aux lecteurs d'écran.

<Preview>

```mdx
import { Icon } from '@astrojs/starlight/components';

<Icon name="star" />
<Icon name="starlight" label="Le logo de Starlight" />
```

<Fragment slot="markdoc">

```markdoc
{% icon name="star" /%}
{% icon name="starlight" label="Le logo de Starlight" /%}
```

</Fragment>

<Fragment slot="preview">
	<Icon name="star" />
	<Icon name="starlight" label="Le logo de Starlight" />
</Fragment>

</Preview>

### Personnaliser les icônes

Les attributs [`size`](#size) et [`color`](#color) peuvent être utilisés pour ajuster l'apparence de l'icône en utilisant des unités et valeurs de couleur CSS.
L'attribut [`class`](#class) peut être utilisé pour ajouter des classes CSS personnalisées à l'icône.

<Preview>

```mdx
import { Icon } from '@astrojs/starlight/components';

<Icon name="star" color="goldenrod" size="2rem" />
<Icon name="rocket" color="var(--sl-color-text-accent)" />
```

<Fragment slot="markdoc">

```markdoc
{% icon name="star" color="goldenrod" size="2rem" /%}
{% icon name="rocket" color="var(--sl-color-text-accent)" /%}
```

</Fragment>

<Fragment slot="preview">
	<Icon name="star" color="goldenrod" size="2rem" />
	<Icon name="rocket" color="var(--sl-color-text-accent)" />
</Fragment>

</Preview>

## Props de `<Icon>`

**Implémentation :** [`Icon.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Icon.astro)

Le composant `<Icon>` accepte les props suivants :

### `name`

**Obligatoire**  
**Type :** [`StarlightIcon`](/fr/reference/icons/#type-starlighticon)

Le nom de l'icône à afficher correspondant à [une des icônes disponibles avec Starlight](/fr/reference/icons/#toutes-les-icônes).

### `label`

**Type :** `string`

Une étiquette optionnelle pour fournir un contexte aux technologies d'assistance, comme les lecteurs d'écran.

Quand l'attribut `label` n'est pas défini, l'icône sera complètement masquée des technologies d'assistance.
Dans ce cas, assurez-vous que le contexte reste compréhensible sans l'icône.
Par exemple, un lien contenant uniquement l'icône **doit** inclure l'attribut `label` pour être accessible, mais si un lien contient du texte et que l'icône est purement décorative, omettre l'attribut `label` peut avoir du sens.

### `size`

**Type :** `string`

La taille de l'icône utilisant des unités CSS.

### `color`

**Type :** `string`

La couleur de l'icône utilisant une valeur de couleur CSS.

### `class`

**Type :** `string`

Classes CSS personnalisées à ajouter à l'icône.


================================================
FILE: docs/src/content/docs/fr/components/link-buttons.mdx
================================================
---
title: Boutons de liaison
description: Apprenez à créer des boutons de liaison dans Starlight pour des liens visuellement distincts qui appellent à l'action.
---

import { LinkButton } from '@astrojs/starlight/components';

Pour afficher des liens visuellement distincts qui appellent à l'action (également connus sous le nom de « call-to-action » ou « CTA » en anglais), utilisez le composant `<LinkButton>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<LinkButton slot="preview" href="/fr/getting-started/">
	Lire la documentation
</LinkButton>

</Preview>

## Importation

```tsx
import { LinkButton } from '@astrojs/starlight/components';
```

## Utilisation

Utilisez le composant `<LinkButton>` pour afficher un lien visuellement distinct qui appelle à l'action.
Un bouton de liaison est utile pour diriger les utilisateurs vers le contenu le plus pertinent ou actionnable et est souvent utilisé sur les pages d'accueil.

Le composant `<LinkButton>` nécessite un attribut [`href`](#href).
Facultativement, personnalisez l'apparence du bouton de liaison en utilisant l'attribut [`variant`](#variant), qui peut être défini sur `primary` (la valeur par défaut), `secondary` ou `minimal`.

<Preview>

```mdx
import { LinkButton } from '@astrojs/starlight/components';

<LinkButton href="/fr/getting-started/">Mise en route</LinkButton>
<LinkButton href="/fr/reference/configuration/" variant="secondary">
	Référence de configuration
</LinkButton>
```

<Fragment slot="markdoc">

```markdoc
{% linkbutton href="/fr/getting-started/" %}Mise en route{% /linkbutton %}

{% linkbutton href="/fr/reference/configuration/" variant="secondary" %}
Référence de configuration
{% /linkbutton %}
```

</Fragment>

<Fragment slot="preview">
	<LinkButton href="/fr/getting-started/">Mise en route</LinkButton>
	<LinkButton href="/fr/reference/configuration/" variant="secondary">
		Référence de configuration
	</LinkButton>
</Fragment>

</Preview>

### Ajouter des icônes aux boutons de liaison

Incluez une icône dans un bouton de liaison en utilisant l'attribut [`icon`](#icon) défini avec [une des icônes disponibles avec Starlight](/fr/reference/icons/#toutes-les-icônes).

L'attribut [`iconPlacement`](#iconplacement) peut être utilisé pour positionner l'icône avant le texte en le définissant sur `start` (par défaut à `end`).

<Preview>

```mdx {6-7}
import { LinkButton } from '@astrojs/starlight/components';

<LinkButton
	href="https://docs.astro.build/fr/"
	variant="secondary"
	icon="external"
	iconPlacement="start"
>
	Référence : Astro
</LinkButton>
```

<Fragment slot="markdoc">

```markdoc {4-5}
{% linkbutton
   href="https://docs.astro.build/fr/"
	 variant="secondary"
	 icon="external"
	 iconPlacement="start" %}
Référence : Astro
{% /linkbutton %}
```

</Fragment>

<LinkButton
	slot="preview"
	href="https://docs.astro.build/fr/"
	variant="secondary"
	icon="external"
	iconPlacement="start"
>
	Référence : Astro
</LinkButton>

</Preview>

## Props de `<LinkButton>`

**Implémentation :** [`LinkButton.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/LinkButton.astro)

Le composant `<LinkButton>` accepte les props suivantes et également tout [autre attribut de l'élément `<a>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/a) :

### `href`

**Obligatoire**  
**Type :** `string`

L'URL vers laquelle le bouton de liaison pointe.

### `variant`

**Type :** `'primary' | 'secondary' | 'minimal'`  
**Par défaut :** `'primary'`

L'apparence du bouton de liaison.
Définissez `primary` pour un lien qui appelle à l'action proéminent utilisant la couleur d'accentuation du thème, `secondary` pour un lien moins proéminent, ou `minimal` pour un lien avec un style minimal.

### `icon`

**Type :** `string`

Un bouton de liaison peut inclure un attribut `icon` défini avec [une des icônes disponibles avec Starlight](/fr/reference/icons/#toutes-les-icônes).

### `iconPlacement`

**Type :** `'start' | 'end'`  
**Par défaut :** `'end'`

Détermine la position de l'icône par rapport au texte du bouton de liaison.


================================================
FILE: docs/src/content/docs/fr/components/link-cards.mdx
================================================
---
title: Cartes de liaison
description: Apprenez à afficher des liens de manière proéminente sous forme de cartes dans Starlight.
sidebar:
  order: 3
---

import { LinkCard } from '@astrojs/starlight/components';

Pour afficher des liens vers différentes pages de manière proéminente, utilisez le composant `<LinkCard>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<LinkCard
	slot="preview"
	title="Personnaliser Starlight"
	description="Apprenez à vous approprier votre site Starlight avec des styles personnalisés, des polices de caractères, et plus encore."
	href="/fr/guides/customization/"
/>

</Preview>

## Importation

```tsx
import { LinkCard } from '@astrojs/starlight/components';
```

## Utilisation

Affichez un lien en évidence en utilisant le composant `<LinkCard>`.
Chaque `<LinkCard>` nécessite un attribut [`title`](#title) ainsi qu'un attribut [`href`](#href).

<Preview>

```mdx
import { LinkCard } from '@astrojs/starlight/components';

<LinkCard
	title="Création de contenu en Markdown"
	href="/fr/guides/authoring-content/"
/>
```

<Fragment slot="markdoc">

```markdoc
{% linkcard
   title="Création de contenu en Markdown"
	 href="/fr/guides/authoring-content/" /%}
```

</Fragment>

<LinkCard
	slot="preview"
	title="Création de contenu en Markdown"
	href="/fr/guides/authoring-content/"
/>

</Preview>

### Ajouter une description à un lien

Ajoutez une courte description à une carte de liaison en utilisant l'attribut [`description`](#description).

<Preview>

```mdx {6}
import { LinkCard } from '@astrojs/starlight/components';

<LinkCard
	title="Internationalisation"
	href="/fr/guides/i18n/"
	description="Configurer Starlight pour prendre en charge plusieurs langues."
/>
```

<Fragment slot="markdoc">

```markdoc {4}
{% linkcard
   title="Internationalisation"
	 href="/fr/guides/i18n/"
	 description="Configurer Starlight pour prendre en charge plusieurs langues." /%}
```

</Fragment>

<LinkCard
	slot="preview"
	title="Internationalisation"
	href="/fr/guides/i18n/"
	description="Configurer Starlight pour prendre en charge plusieurs langues."
/>

</Preview>

### Grouper des cartes de liaison

Affichez plusieurs cartes de liaison côte à côte lorsqu'il y a suffisamment d'espace en les regroupant à l'aide du composant [`<CardGrid>`](/fr/components/card-grids/).
Consultez le guide [« Grouper des cartes de liaison »](/fr/components/card-grids/#grouper-des-cartes-de-liaison) pour un exemple.

## Props de `<LinkCard>`

**Implémentation :** [`LinkCard.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/LinkCard.astro)

Le composant `<LinkCard>` accepte les props suivantes, ainsi que tous les autres [attributs de l'élément `<a>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/a) :

### `title`

**Obligatoire**  
**Type :** `string`

Le titre de la carte de liaison à afficher.

### `href`

**Obligatoire**  
**Type :** `string`

L'URL vers laquelle pointer lors d'une interaction avec la carte.

### `description`

**Type :** `string`

Une description facultative à afficher sous le titre.


================================================
FILE: docs/src/content/docs/fr/components/steps.mdx
================================================
---
title: Étapes
description: Apprenez à mettre en forme des listes numérotées de tâches pour créer des guides étape par étape dans Starlight.
---

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

Pour mettre en forme une liste numérotée de tâches et créer des guides étape par étape, utilisez le composant `<Steps>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<Steps slot="preview">

1. Créez un nouveau projet Starlight :

   <Tabs syncKey="pkg">

   <TabItem label="npm">

   ```sh
   npm create astro@latest -- --template starlight
   ```

   </TabItem>

   <TabItem label="pnpm">

   ```sh
   pnpm create astro --template starlight
   ```

   </TabItem>

   <TabItem label="Yarn">

   ```sh
   yarn create astro --template starlight
   ```

   </TabItem>

   </Tabs>

2. Écrivez votre première page de documentation.

</Steps>

</Preview>

## Importation

```tsx
import { Steps } from '@astrojs/starlight/components';
```

## Utilisation

Utilisez le composant `<Steps>` pour mettre en forme des listes numérotées de tâches.
Celui-ci est utile pour des guides étape par étape plus complexes où chaque étape doit être clairement mise en évidence.

Entourez une liste ordonnée standard Markdown avec le composant `<Steps>`.
Toute la syntaxe Markdown habituelle est utilisable à l'intérieur de `<Steps>`.

<Preview>

````mdx
import { Steps } from '@astrojs/starlight/components';

<Steps>

1. Importez le composant dans votre fichier MDX :

   ```js
   import { Steps } from '@astrojs/starlight/components';
   ```

2. Entourez les éléments de votre liste ordonnée avec `<Steps>`.

</Steps>
````

<Fragment slot="markdoc">

````markdoc
{% steps %}

1. Importez le composant dans votre fichier MDX :

   ```js
   import { Steps } from '@astrojs/starlight/components';
   ```

2. Entourez les éléments de votre liste ordonnée avec `<Steps>`.

{% /steps %}
````

</Fragment>

<Steps slot="preview">

1. Importez le composant dans votre fichier MDX :

   ```js
   import { Steps } from '@astrojs/starlight/components';
   ```

2. Entourez les éléments de votre liste ordonnée avec `<Steps>`.

</Steps>

</Preview>

## Props de `<Steps>`

**Implémentation :** [`Steps.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Steps.astro)

Le composant `<Steps>` n'accepte pas de props.


================================================
FILE: docs/src/content/docs/fr/components/tabs.mdx
================================================
---
title: Onglets
description: Apprenez à créer des interfaces à onglets dans Starlight pour regrouper des informations équivalentes.
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

Pour créer une interface à onglets, utilisez les composants `<Tabs>` et `<TabItem>`.
Des onglets sont utiles pour regrouper des informations équivalentes où un utilisateur n'a besoin de voir qu'une des options.

import Preview from '~/components/component-preview.astro';

<Preview>

<Tabs slot="preview">
	<TabItem label="Étoiles">Sirius, Véga, Bételgeuse</TabItem>
	<TabItem label="Lunes">Io, Europe, Ganymède</TabItem>
</Tabs>

</Preview>

## Importation

```tsx
import { Tabs, TabItem } from '@astrojs/starlight/components';
```

## Utilisation

Affichez une interface à onglets en utilisant les composants `<Tabs>` et `<TabItem>`.
Chaque composant `<TabItem>` doit avoir un [`label`](#label) à afficher aux utilisateurs.

<Preview>

```mdx
import { Tabs, TabItem } from '@astrojs/starlight/components';

<Tabs>
	<TabItem label="Étoiles">Sirius, Véga, Bételgeuse</TabItem>
	<TabItem label="Lunes">Io, Europe, Ganymède</TabItem>
</Tabs>
```

<Fragment slot="markdoc">

```markdoc
{% tabs %}
{% tabitem label="Étoiles" %}
Sirius, Véga, Bételgeuse
{% /tabitem %}

{% tabitem label="Lunes" %}
Io, Europe, Ganymède
{% /tabitem %}
{% /tabs %}
```

</Fragment>

<Tabs slot="preview">
	<TabItem label="Étoiles">Sirius, Véga, Bételgeuse</TabItem>
	<TabItem label="Lunes">Io, Europe, Ganymède</TabItem>
</Tabs>

</Preview>

### Synchroniser des onglets

Conservez plusieurs groupes d'onglets synchronisés en ajoutant l'attribut [`syncKey`](#synckey).

Tous les composants `<Tabs>` avec la même valeur `syncKey` afficheront le même label actif.
Cela permet à votre lecteur de choisir une fois (par exemple, son système d'exploitation ou son gestionnaire de paquets) et de voir son choix persister en naviguant entre différentes pages.

Pour synchroniser des onglets liés, ajoutez une propriété `syncKey` identique à chaque composant `<Tabs>` et assurez-vous qu'ils utilisent tous les mêmes libellés avec le composant `<TabItem>` :

<Preview>

```mdx 'syncKey="constellations"'
import { Tabs, TabItem } from '@astrojs/starlight/components';

_Quelques étoiles :_

<Tabs syncKey="constellations">
	<TabItem label="Orion">Bellatrix, Rigel, Bételgeuse</TabItem>
	<TabItem label="Gémeaux">Pollux, Castor A, Castor B</TabItem>
</Tabs>

_Quelques exoplanètes :_

<Tabs syncKey="constellations">
	<TabItem label="Orion">HD 34445 b, Gliese 179 b, Wasp-82 b</TabItem>
	<TabItem label="Gémeaux">Pollux b, HAT-P-24b, HD 50554 b</TabItem>
</Tabs>
```

<Fragment slot="markdoc">

```markdoc 'syncKey="constellations"'
_Quelques étoiles :_

{% tabs syncKey="constellations" %}
{% tabitem label="Orion" %}
Bellatrix, Rigel, Bételgeuse
{% /tabitem %}

{% tabitem label="Gémeaux" %}
Pollux, Castor A, Castor B
{% /tabitem %}
{% /tabs %}

_Quelques exoplanètes :_

{% tabs syncKey="constellations" %}
{% tabitem label="Orion" %}
HD 34445 b, Gliese 179 b, Wasp-82 b
{% /tabitem %}

{% tabitem label="Gémeaux" %}
Pollux b, HAT-P-24b, HD 50554 b
{% /tabitem %}
{% /tabs %}
```

</Fragment>

<Fragment slot="preview">

_Quelques étoiles :_

<Tabs syncKey="constellations">
	<TabItem label="Orion">Bellatrix, Rigel, Bételgeuse</TabItem>
	<TabItem label="Gémeaux">Pollux, Castor A, Castor B</TabItem>
</Tabs>

_Quelques exoplanètes :_

<Tabs syncKey="constellations">
	<TabItem label="Orion">HD 34445 b, Gliese 179 b, Wasp-82 b</TabItem>
	<TabItem label="Gémeaux">Pollux b, HAT-P-24b, HD 50554 b</TabItem>
</Tabs>

</Fragment>

</Preview>

### Ajouter des icônes aux onglets

Incluez une icône dans un onglet en utilisant l'attribut [`icon`](#icon) défini avec [une des icônes disponibles avec Starlight](/fr/reference/icons/#toutes-les-icônes) pour afficher une icône à côté du libellé.

<Preview>

```mdx /icon="\w+"/
import { Tabs, TabItem } from '@astrojs/starlight/components';

<Tabs>
	<TabItem label="Étoiles" icon="star">
		Sirius, Véga, Bételgeuse
	</TabItem>
	<TabItem label="Lunes" icon="moon">
		Io, Europe, Ganymède
	</TabItem>
</Tabs>
```

<Fragment slot="markdoc">

```markdoc /icon="\w+"/
{% tabs %}
{% tabitem label="Étoiles" icon="star" %}
Sirius, Véga, Bételgeuse
{% /tabitem %}

{% tabitem label="Lunes" icon="moon" %}
Io, Europe, Ganymède
{% /tabitem %}
{% /tabs %}
```

</Fragment>

<Tabs slot="preview">
	<TabItem label="Étoiles" icon="star">
		Sirius, Véga, Bételgeuse
	</TabItem>
	<TabItem label="Lunes" icon="moon">
		Io, Europe, Ganymède
	</TabItem>
</Tabs>

</Preview>

## Props de `<Tabs>`

**Implémentation :** [`Tabs.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Tabs.astro)

Le composant `<Tabs>` regroupe plusieurs composants `<TabItem>` et accepte les props suivantes :

### `syncKey`

**Type :** `string`

Une clé utilisée pour conserver plusieurs groupes d'onglets synchronisés sur plusieurs pages.

## Props de `<TabItem>`

**Implémentation :** [`TabItem.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/TabItem.astro)

Un ensemble d'onglets est composé d'onglets, chacun avec les props suivantes :

### `label`

**Obligatoire**  
**Type :** `string`

Un onglet doit inclure un attribut `label` défini avec le texte qui sera affiché dans l'onglet.

### `icon`

**Type :** `string`

Chaque onglet peut inclure un attribut `icon` défini avec [une des icônes disponibles avec Starlight](/fr/reference/icons/#toutes-les-icônes) pour afficher une icône à côté du libellé.


================================================
FILE: docs/src/content/docs/fr/components/using-components.mdx
================================================
---
title: Utilisation des composants
description: Utilisation des composants avec MDX et Markdoc avec Starlight.
sidebar:
  order: 1
---

Les composants vous permettent de réutiliser facilement un élément d'interface utilisateur ou de style de manière cohérente.
Il peut s'agir par exemple d'une carte de liaison ou d'une intégration YouTube.
Starlight prend en charge l'utilisation de composants dans les fichiers [MDX](https://mdxjs.com/) et [Markdoc](https://markdoc.dev/) et fournit des composants courants que vous pouvez utiliser.

[Pour en savoir plus sur la création de composants, consultez la documentation d'Astro](https://docs.astro.build/fr/basics/astro-components/).

## Utilisation d'un composant avec MDX

Vous pouvez utiliser un composant en l'important dans votre fichier MDX et ensuite l'afficher en tant que balise JSX.
Ces balises ressemblent à des balises HTML, mais commencent par une lettre majuscule correspondant au nom utilisé dans votre instruction `import` :

```mdx
---
# src/content/docs/exemple.mdx
title: Bienvenue dans ma documentation
---

import { Icon } from '@astrojs/starlight/components';
import CustomCard from '../../components/CustomCard.astro';

<Icon name="open-book" />

<CustomCard>
	Les composants peuvent également contenir du **contenu imbriqué**.
</CustomCard>
```

Starlight étant basé sur Astro, vous pouvez ajouter la prise en charge de composants construits avec n'importe quel [framework d'interface utilisateur pris en charge (React, Preact, Svelte, Vue, Solid et Alpine)](https://docs.astro.build/fr/guides/framework-components/) dans vos fichiers MDX.
Pour en savoir plus sur [l'utilisation de composants avec MDX](https://docs.astro.build/fr/guides/integrations-guide/mdx/#utilisation-de-composants-dans-mdx), consultez la documentation d'Astro.

## Utilisation d'un composant avec Markdoc

Ajoutez la prise en charge de la rédaction de contenu avec Markdoc en suivant notre [guide de configuration Markdoc](/fr/guides/authoring-content/#markdoc).

En utilisant le préréglage Markdoc de Starlight, vous pouvez utiliser les composants intégrés à Starlight avec la syntaxe de balises `{% %}` de Markdoc.
À la différence du format MDX, les composants dans les fichiers Markdoc n'ont pas besoin d'être importés.
L'exemple suivant affiche le [composant de carte](/fr/components/cards/) de Starlight dans un fichier Markdoc :

```markdoc
---
# src/content/docs/exemple.mdoc
title: Bienvenue dans ma documentation
---

{% card title="Étoiles" icon="star" %}
Sirius, Véga, Bételgeuse
{% /card %}
```

Consultez la [documentation de l'intégration Markdoc d'Astro](https://docs.astro.build/fr/guides/integrations-guide/markdoc/#restituer-les-composants) pour plus d'informations sur l'utilisation des composants dans les fichiers Markdoc.

## Composants intégrés

Starlight fournit des composants intégrés par défaut pour des cas d'utilisation courants à une documentation.
Ces composants sont disponibles dans le paquet `@astrojs/starlight/components` dans les fichiers MDX et dans le [préréglage Markdoc de Starlight](/fr/guides/authoring-content/#markdoc) dans les fichiers Markdoc.

Utilisez la barre latérale pour obtenir une liste des composants disponibles et savoir comment les utiliser.

## Compatibilité avec les styles de Starlight

Starlight applique des styles par défaut à votre contenu Markdown, par exemple en ajoutant une marge entre les éléments.
Si ces styles entrent en conflit avec l'apparence de votre composant, utilisez la classe `not-content` sur votre composant pour les désactiver.

```astro 'class="not-content"'
---
// src/components/Exemple.astro
---

<div class="not-content">
	<p>Contenu non affecté par les styles par défaut de Starlight.</p>
</div>
```

## Props des composants

Utilisez le type [`ComponentProps`](https://docs.astro.build/fr/guides/typescript/#type-componentprops) depuis `astro/types` pour référencer les `Props` acceptées par un composant même si elles ne sont pas exportées par le composant lui-même.
Cela peut être utile lorsqu'il s'agit d'entourer ou d'étendre un composant existant.

L'exemple suivant utilise `ComponentProps` pour obtenir le type des props acceptées par le composant `Badge` intégré à Starlight :

```astro
---
// src/components/Exemple.astro
import type { ComponentProps } from 'astro/types';
import { Badge } from '@astrojs/starlight/components';

type BadgeProps = ComponentProps<typeof Badge>;
---
```


================================================
FILE: docs/src/content/docs/fr/environmental-impact.md
================================================
---
title: Documentations écologiques
description: Découvrez comment Starlight peut vous aider à créer des documentations plus écologiques et à réduire votre empreinte carbone.
---

Les estimations de l'impact climatique de l'industrie du web varient entre [2 %][sf] et [4 % des émissions mondiales de carbone][bbc], ce qui équivaut à peu près aux émissions de l'industrie du transport aérien.
Le calcul de l'impact écologique d'un site web repose sur de nombreux facteurs complexes, mais ce guide contient quelques conseils pour réduire l'empreinte écologique de votre site de documentation.

La bonne nouvelle, c'est que le choix de Starlight est un excellent début.
Selon le Website Carbon Calculator, ce site est [plus propre que 98 % des pages web testées][sl-carbon], produisant 0,01 g de CO₂ par page visitée.

## Poids de la page

Plus une page web transfère de données, plus elle nécessite de ressources énergétiques.
En avril 2023, la page web médiane demandait à l'utilisateur de télécharger plus de 2 000 Ko selon les [données de l'archive HTTP][http].

Starlight crée des pages aussi légères que possible.
Par exemple, lors de sa première visite, un utilisateur téléchargera moins de 50 Ko de données compressées, soit seulement 2,5 % de la médiane des archives HTTP.
Avec une bonne stratégie de mise en cache, les navigations suivantes peuvent télécharger jusqu'à 10 Ko.

### Images

Bien que Starlight fournisse une bonne base de référence, les images que vous ajoutez à vos pages de documentation peuvent rapidement augmenter le poids de vos pages.
Starlight utilise la [prise en charge des ressources optimisées][assets] d'Astro pour optimiser les images locales dans vos fichiers Markdown et MDX.

### Composants d'interface utilisateur

Les composants créés avec des frameworks d'interface utilisateur tels que React ou Vue peuvent facilement ajouter de grandes quantités de JavaScript à une page.
Starlight étant construit sur Astro, les composants de ce type chargent **zéro JavaScript côté client par défaut** grâce aux [îlots d'Astro][islands].

### Mise en cache

La mise en cache est utilisée pour contrôler la durée pendant laquelle un navigateur stocke et réutilise les données qu'il a déjà téléchargées.
Une bonne stratégie de mise en cache permet à l'utilisateur d'obtenir un nouveau contenu dès qu'il est modifié, tout en évitant de télécharger inutilement le même contenu à plusieurs reprises lorsqu'il n'a pas changé.

La façon la plus courante de configurer la mise en cache est d'utiliser l'en-tête HTTP [`Cache-Control`][cache].
Lorsque vous utilisez Starlight, vous pouvez définir une longue durée de mise en cache pour tout ce qui se trouve dans le répertoire `/_astro/`.
Ce répertoire contient des fichiers CSS, JavaScript, et d'autres ressources intégrées qui peuvent être mises en cache pour toujours, réduisant ainsi les téléchargements inutiles :

```
Cache-Control: public, max-age=604800, immutable
```

La configuration de la mise en cache dépend de votre hébergeur. Par exemple, Vercel applique cette stratégie de mise en cache pour vous sans configuration nécessaire, tandis que vous pouvez définir des [en-têtes personnalisés pour Netlify][ntl-headers] en ajoutant un fichier `public/_headers` à votre projet :

```
/_astro/*
  Cache-Control: public
  Cache-Control: max-age=604800
  Cache-Control: immutable
```

[cache]: https://csswizardry.com/2019/03/cache-control-for-civilians/
[ntl-headers]: https://docs.netlify.com/routing/headers/

## Consommation d'énergie

La façon dont une page web est construite peut avoir un impact sur la puissance nécessaire pour fonctionner sur l'appareil d'un utilisateur.
En utilisant un minimum de JavaScript, Starlight réduit la puissance de traitement dont le téléphone, la tablette ou l'ordinateur d'un utilisateur a besoin pour charger et afficher les pages.

Soyez vigilant lorsque vous ajoutez des fonctionnalités telles que des scripts de suivi analytique ou des contenus à forte teneur en JavaScript, comme des vidéos intégrées, car ils peuvent augmenter la consommation d'énergie de la page.
Si vous avez besoin de mesures d'audience, envisagez de choisir une option légère comme [Cabin][cabin], [Fathom][fathom], ou [Plausible][plausible].
Les vidéos intégrées comme celles de YouTube et de Vimeo peuvent être améliorées en attendant de [charger la vidéo lors de l'interaction avec l'utilisateur][lazy-video].
Des paquets comme [`astro-embed`][embed] peuvent aider pour les services communs.

:::tip[Le saviez-vous ?]
L'analyse et la compilation de JavaScript est l'une des tâches les plus coûteuses pour les navigateurs.
Par rapport au rendu d'une image JPEG de même taille, [le traitement de JavaScript peut prendre plus de 30 fois plus de temps][cost-of-js].
:::

[cabin]: https://withcabin.com/
[fathom]: https://usefathom.com/
[plausible]: https://plausible.io/
[lazy-video]: https://web.dev/iframe-lazy-loading/
[embed]: https://www.npmjs.com/package/astro-embed
[cost-of-js]: https://medium.com/dev-channel/the-cost-of-javascript-84009f51e99e

## Hébergement

Le lieu d'hébergement d'une page web peut avoir un impact important sur le degré de respect de l'environnement de votre site de documentation.
Les centres de données et les fermes de serveurs peuvent avoir un impact écologique important, notamment en raison de leur consommation élevée d'électricité et de leur utilisation intensive de l'eau.

Le choix d'un hébergeur utilisant des énergies renouvelables se traduira par une réduction des émissions de carbone pour votre site. Le [Green Web Directory][gwb] est un outil qui peut vous aider à trouver des hébergeurs.

[gwb]: https://www.thegreenwebfoundation.org/directory/

## Comparaisons

Curieux de savoir comment les autres frameworks de documentation se comparent ?
Ces tests avec le [Website Carbon Calculator][wcc] comparent des pages similaires construites avec différents outils.

| Framework                   | CO₂ par page visitée | Notation |
| --------------------------- | -------------------- | :------: |
| [Starlight][sl-carbon]      | 0.01g                |    A+    |
| [Sphinx][sx-carbon]         | 0.01g                |    A+    |
| [Read the Docs][rtd-carbon] | 0.03g                |    A+    |
| [VitePress][vp-carbon]      | 0.04g                |    A     |
| [docsify][dy-carbon]        | 0.05g                |    A     |
| [mdBook][md-carbon]         | 0.05g                |    A     |
| [Nextra][nx-carbon]         | 0.05g                |    A     |
| [MkDocs][mk-carbon]         | 0.07g                |    A     |
| [Fumadocs][fs-carbon]       | 0.07g                |    A     |
| [Docusaurus][ds-carbon]     | 0.10g                |    B     |
| [Docus][dc-carbon]          | 0.11g                |    B     |
| [GitBook][gb-carbon]        | 0.42g                |    F     |
| [Mintlify][mt-carbon]       | 0.48g                |    F     |

<small>Données collectées le 7 août 2025. Cliquez sur un lien pour voir les chiffres actualisés.</small>

[sl-carbon]: https://www.websitecarbon.com/website/starlight-astro-build-getting-started/
[vp-carbon]: https://www.websitecarbon.com/website/vitepress-dev-guide-what-is-vitepress/
[dc-carbon]: https://www.websitecarbon.com/website/docus-dev-en-getting-started-project-structure/
[sx-carbon]: https://www.websitecarbon.com/website/sphinx-doc-org-en-master-usage-quickstart-html/
[mk-carbon]: https://www.websitecarbon.com/website/mkdocs-org-getting-started/
[md-carbon]: https://www.websitecarbon.com/website/rust-lang-github-io-mdbook/
[nx-carbon]: https://www.websitecarbon.com/website/nextra-site-docs-docs-theme-start/
[fs-carbon]: https://www.websitecarbon.com/website/fumadocs-dev-docs-ui/
[dy-carbon]: https://www.websitecarbon.com/website/docsify-js-org/
[ds-carbon]: https://www.websitecarbon.com/website/docusaurus-io-docs/
[rtd-carbon]: https://www.websitecarbon.com/website/docs-readthedocs-io-en-stable-index-html/
[gb-carbon]: https://www.websitecarbon.com/website/gitbook-com-docs/
[mt-carbon]: https://www.websitecarbon.com/website/mintlify-com-docs-quickstart/

## Plus de ressources

### Outils

- [Website Carbon Calculator][wcc]
- [GreenFrame](https://greenframe.io/)
- [Ecograder](https://ecograder.com/)
- [WebPageTest Carbon Control](https://www.webpagetest.org/carbon-control/)
- [Ecoping](https://ecoping.earth/)

### Articles et discussions

- [“Building a greener web”](https://youtu.be/EfPoOt7T5lg), conférence de Michelle Barker
- [“Sustainable Web Development Strategies Within An Organization”](https://www.smashingmagazine.com/2022/10/sustainable-web-development-strategies-organization/), article par Michelle Barker
- [“A sustainable web for everyone”](https://2021.stateofthebrowser.com/speakers/tom-greenwood/), conférence de Tom Greenwood
- [“How Web Content Can Affect Power Usage”](https://webkit.org/blog/8970/how-web-content-can-affect-power-usage/), article de Benjamin Poulain et Simon Fraser

[sf]: https://www.sciencefocus.com/science/what-is-the-carbon-footprint-of-the-internet/
[bbc]: https://www.bbc.com/future/article/20200305-why-your-internet-habits-are-not-as-clean-as-you-think
[http]: https://httparchive.org/reports/state-of-the-web
[assets]: https://docs.astro.build/fr/guides/images/
[islands]: https://docs.astro.build/fr/concepts/islands/
[wcc]: https://www.websitecarbon.com/


================================================
FILE: docs/src/content/docs/fr/getting-started.mdx
================================================
---
title: Mise en route
description: Apprenez à créer votre prochain site de documentation avec Starlight by Astro.
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

Starlight est un thème de documentation complet construit sur la base du framework [Astro](https://astro.build).
Ce guide vous aidera à démarrer un nouveau projet.
Consultez les [instructions d'installation manuelle](/fr/manual-setup/) pour ajouter Starlight à un projet Astro existant.

## Démarrage rapide

### Créer un nouveau projet

Créez un nouveau projet Astro + Starlight en lançant la commande suivante dans votre terminal :

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight
```

</TabItem>
</Tabs>

Cela créera un nouveau [répertoire de projet](/fr/guides/project-structure/) avec tous les fichiers et configurations nécessaires pour votre site.

:::tip[Voir en action]
Essayez Starlight dans votre navigateur :
[ouvrir le modèle sur StackBlitz](https://stackblitz.com/github/withastro/starlight/tree/main/examples/basics).
:::

### Démarrer le serveur de développement

Lorsque vous travaillez localement, [le serveur de développement d'Astro](https://docs.astro.build/fr/reference/cli-reference/#astro-dev) vous permet de prévisualiser votre travail et actualise automatiquement votre navigateur lorsque vous apportez des modifications.

À l'intérieur du répertoire de votre projet, exécutez la commande suivante pour démarrer le serveur de développement :

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm run dev
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dev
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dev
```

</TabItem>
</Tabs>

Un message indiquant l'URL de votre aperçu local s'affichera dans votre terminal.
Ouvrez cette URL pour commencer à naviguer sur votre site.

### Ajouter du contenu

Starlight est prêt pour que vous puissiez ajouter du nouveau contenu, ou apporter vos fichiers existants !

Ajoutez de nouvelles pages à votre site en créant des fichiers Markdown dans le répertoire `src/content/docs/`.

Pour en savoir plus sur le routage par fichier et la prise en charge des fichiers MDX et Markdoc, consultez le guide [« Pages »](/fr/guides/pages/).

### Prochaines étapes

- **Configurer :** Découvrez les options courantes dans [« Personnaliser Starlight »](/fr/guides/customization/).
- **Naviguer :** Configurez votre barre latérale avec le guide [« Barre latérale de navigation »](/fr/guides/sidebar/).
- **Composants :** Découvrez les cartes, les onglets et d'autres composants intégrés dans le guide [« Composants »](/fr/components/using-components/).
- **Enrichir :** Explorez les modules complémentaires créés par la communauté dans nos galeries [« Modules d'extension »](/fr/resources/plugins/) et [« Thèmes »](/fr/resources/themes/).
- **Déployer :** Publiez votre travail avec le guide [« Déployer votre site »](https://docs.astro.build/fr/guides/deploy/) dans la documentation d'Astro.

## Mettre à jour Starlight

:::tip
Comme Starlight est un logiciel en version bêta, il y aura des mises à jour et des améliorations fréquentes.
Assurez-vous de mettre à jour Starlight régulièrement !
:::

Starlight est une intégration Astro. Vous pouvez la mettre à jour ainsi que tout autre paquet d'Astro en exécutant la commande suivante dans votre terminal :

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npx @astrojs/upgrade
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dlx @astrojs/upgrade
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dlx @astrojs/upgrade
```

</TabItem>
</Tabs>

Consultez le [journal des modifications de Starlight](https://github.com/withastro/starlight/blob/main/packages/starlight/CHANGELOG.md) pour une liste complète des modifications apportées à chaque version.

## Dépannage de Starlight

Utilisez les pages de référence de [configuration de projet](/fr/reference/configuration/) et de [configuration du frontmatter pour chaque page](/fr/reference/frontmatter/) pour vous assurer que votre site Starlight est configuré et fonctionne correctement.
Consultez les guides de la barre latérale pour vous aider à ajouter du contenu et à personnaliser votre site Starlight.

Si vous ne trouvez pas votre réponse dans cette documentation, merci de consulter la [documentation d'Astro](https://docs.astro.build/fr/) pour la documentation complète d'Astro.
Votre question peut être résolue en comprenant comment Astro fonctionne de manière générale, sous ce thème Starlight.

Vous pouvez également vérifier [tous les problèmes connus de Starlight sur GitHub](https://github.com/withastro/starlight/issues) et obtenir de l'aide auprès de notre communauté active et sympathique dans le [Discord d'Astro](https://astro.build/chat/) ! Publiez des questions dans notre forum `#support` avec le tag « starlight » ou visiter notre canal dédié `#starlight` pour discuter des développements en cours et plus encore !


================================================
FILE: docs/src/content/docs/fr/guides/authoring-content.mdx
================================================
---
title: Création de contenu en Markdown
description: Un aperçu de la syntaxe Markdown prise en charge par Starlight.
---

Starlight prend en charge l'ensemble de la syntaxe [Markdown](https://daringfireball.net/projects/markdown/) dans les fichiers `.md` ainsi que le frontmatter en [YAML](https://dev.to/paulasantamaria/introduction-to-yaml-125f) pour définir des métadonnées telles qu'un titre et une description.

Veillez à consulter la [documentation de MDX](https://mdxjs.com/docs/what-is-mdx/#markdown) ou la [documentation de Markdoc](https://markdoc.dev/docs/syntax) si vous utilisez ces formats de fichiers, car la prise en charge et l'utilisation de Markdown peuvent varier.

## Frontmatter

Vous pouvez personnaliser chaque page individuellement en définissant des valeurs dans leur frontmatter.
Le frontmatter se situe en haut de vos fichiers entre les séparateurs `---` :

```md title="src/content/docs/exemple.md"
---
title: Le titre de ma page
---

Le contenu de la page suit le second `---`.
```

Chaque page doit inclure au moins un titre (`title`).
Consultez la [référence du frontmatter](/fr/reference/frontmatter/) pour connaître tous les champs disponibles et comment ajouter des champs personnalisés.

## Styles incorporés au texte

Le texte peut être en **gras**, en _italique_, ou ~~barré~~.

```md
Le texte peut être en **gras**, en _italique_, ou ~~barré~~.
```

Vous pouvez [faire un lien vers une autre page](/fr/getting-started/).

```md
Vous pouvez [faire un lien vers une autre page](/fr/getting-started/).
```

Vous pouvez mettre en évidence le `code incorporé au texte` en utilisant des accents graves.

```md
Vous pouvez mettre en évidence le `code incorporé au texte` en utilisant des accents graves.
```

## Images

Les images dans Starlight utilisent [la prise en charge intégrée des ressources optimisées d'Astro](https://docs.astro.build/fr/guides/images/).

Markdown et MDX prennent en charge la syntaxe Markdown pour l'affichage d'images qui incluent du texte alternatif pour les lecteurs d'écran et les technologies d'assistance.

![Une illustration de planètes et d'étoiles avec le mot « astro »](https://raw.githubusercontent.com/withastro/docs/main/public/default-og-image.png)

```md
![Une illustration de planètes et d'étoiles avec le mot « astro »](https://raw.githubusercontent.com/withastro/docs/main/public/default-og-image.png)
```

Les chemins d'accès relatifs aux images sont également pris en charge pour les images stockées localement dans votre projet.

```md
// src/content/docs/page-1.md

![Une fusée dans l'espace](../../assets/images/rocket.svg)
```

## En-têtes

Vous pouvez structurer le contenu à l'aide d'en-têtes. En Markdown, les en-têtes sont indiqués par un certain nombre de `#` en début de ligne.

### Comment structurer le contenu d'une page dans Starlight

Starlight est configuré pour utiliser automatiquement le titre de votre page comme en-tête de premier niveau et inclura un en-tête « Aperçu » en haut de la table des matières de chaque page. Nous vous recommandons de commencer chaque page par un paragraphe de texte normal et d'utiliser des en-têtes de page à partir de `<h2>` :

```md
---
title: Guide Markdown
description: Comment utiliser Markdown dans Starlight
---

Cette page décrit comment utiliser Markdown dans Starlight.

## Styles incorporés au texte

## En-têtes
```

### Liens d'ancrage automatiques pour les en-têtes

L'utilisation d'en-têtes en Markdown vous donnera automatiquement des liens d'ancrage afin que vous puissiez accéder directement à certaines sections de votre page :

```md
---
title: Ma page de contenu
description: Comment utiliser les liens d'ancrage intégrés de Starlight
---

## Introduction

Je peux faire un lien vers [ma conclusion](#conclusion) plus bas sur la même page.

## Conclusion

`https://my-site.com/page1/#introduction` renvoie directement à mon Introduction.
```

Les en-têtes de niveau 2 (`<h2>`) et de niveau 3 (`<h3>`) apparaissent automatiquement dans la table des matières de la page.

Pour en apprendre davantage sur la façon dont Astro traite les attributs `id` des en-têtes de section, consultez la [documentation d'Astro](https://docs.astro.build/fr/guides/markdown-content/#id-des-titres).

## Encarts

Les encarts (également connus sous le nom de « admonitions » ou « asides » en anglais) sont utiles pour afficher des informations secondaires à côté du contenu principal d'une page.

Starlight fournit une syntaxe Markdown personnalisée pour le rendu des encarts. Les blocs d'encarts sont indiqués en utilisant une paire de triples points `:::` pour envelopper votre contenu, et peuvent être de type `note`, `tip`, `caution` ou `danger`.

Vous pouvez imbriquer n'importe quel autre type de contenu Markdown à l'intérieur d'un encart, mais les encarts sont mieux adaptés à des morceaux de contenu courts et concis.

### Encart de type note

:::note
Starlight est une boîte à outils pour sites web de documentation construite avec [Astro](https://astro.build/). Vous pouvez démarrer avec cette commande :

```sh
npm run create astro@latest --template starlight
```

:::

````md
:::note
Starlight est une boîte à outils pour sites web de documentation construite avec [Astro](https://astro.build/). Vous pouvez démarrer avec cette commande :

```sh
npm run create astro@latest --template starlight
```

:::
````

### Titres d'encarts personnalisés

Vous pouvez spécifier un titre personnalisé pour un encart entre crochets après le type d'encart, par exemple `:::tip[Le saviez-vous ?]`.

:::tip[Le saviez-vous ?]
Astro vous aide à construire des sites Web plus rapides grâce à [« l'Architecture en îlots »](https://docs.astro.build/fr/concepts/islands/).
:::

```md
:::tip[Le saviez-vous ?]
Astro vous aide à construire des sites Web plus rapides grâce à [« l'Architecture en îlots »](https://docs.astro.build/fr/concepts/islands/).
:::
```

### Icônes d'encarts personnalisées

Vous pouvez spécifier une icône personnalisée pour un encart en utilisant des accolades après le type d'encart ou le [titre personnalisé](#titres-dencarts-personnalisés), par exemple `:::tip{icon="heart"}` ou `:::tip[Le saviez-vous ?]{icon="heart"}` respectivement.
Le nom de l'icône doit être défini avec le nom de [l'une des icônes intégrées à Starlight](/fr/reference/icons/#toutes-les-icônes).

:::tip{icon="heart"}
Astro vous aide à construire des sites Web plus rapides grâce à [« l'Architecture en îlots »](https://docs.astro.build/fr/concepts/islands/).
:::

```md
:::tip{icon="heart"}
Astro vous aide à construire des sites Web plus rapides grâce à [« l'Architecture en îlots »](https://docs.astro.build/fr/concepts/islands/).
:::
```

### Plus de types d'encarts

Les encarts de type Attention et Danger sont utiles pour attirer l'attention de l'utilisateur sur des détails qui pourraient le perturber. Si vous vous retrouvez à utiliser ces derniers fréquemment, cela pourrait aussi être un signe que ce que vous documentez pourrait bénéficier d'une refonte.

:::caution
Si vous n'êtes pas sûr de vouloir un site de documentation génial, réfléchissez à deux fois avant d'utiliser [Starlight](/fr/).
:::

:::danger
Vos utilisateurs peuvent être plus productifs et trouver votre produit plus facile à utiliser grâce aux fonctionnalités utiles de Starlight.

- Navigation claire
- Thème de couleurs configurable par l'utilisateur
- [Prise en charge i18n](/fr/guides/i18n/)

:::

```md
:::caution
Si vous n'êtes pas sûr de vouloir un site de documentation génial, réfléchissez à deux fois avant d'utiliser [Starlight](/fr/).
:::

:::danger
Vos utilisateurs peuvent être plus productifs et trouver votre produit plus facile à utiliser grâce aux fonctionnalités utiles de Starlight.

- Navigation claire
- Thème de couleurs configurable par l'utilisateur
- [Prise en charge i18n](/fr/guides/i18n/)

:::
```

## Blocs de citation

> Il s'agit d'un bloc de citation, couramment utilisé pour citer une autre personne ou un document.
>
> Les blocs de citation sont indiqués par un `>` au début de chaque ligne.

```md
> Il s'agit d'un bloc de citation, couramment utilisé pour citer une autre personne ou un document.
>
> Les blocs de citation sont indiqués par un `>` au début de chaque ligne.
```

## Blocs de code

Un bloc de code est indiqué par un bloc avec trois accents graves <code>```</code> au début et à la fin. Vous pouvez indiquer le langage de programmation utilisé après les premiers accents graves.

```js
// Code Javascript avec coloration syntaxique.
var fun = function lang(l) {
	dateformat.i18n = require('./lang/' + l);
	return true;
};
```

````md
```js
// Code Javascript avec coloration syntaxique.
var fun = function lang(l) {
	dateformat.i18n = require('./lang/' + l);
	return true;
};
```
````

### Fonctionnalités d'Expressive Code

Starlight utilise [Expressive Code](https://expressive-code.com/) pour étendre les possibilités de formatage des blocs de code.
Les modules d'extension Expressive Code de marqueurs de texte et de cadres de fenêtre sont activés par défaut.
L'affichage des blocs de code peut être configuré à l'aide de [l'option de configuration `expressiveCode`](/fr/reference/configuration/#expressivecode) de Starlight.

#### Marqueurs de texte

Vous pouvez mettre en évidence des lignes ou des portions spécifiques de vos blocs de code à l'aide des [marqueurs de texte d'Expressive Code](https://expressive-code.com/key-features/text-markers/) sur la première ligne de votre bloc de code.
Utilisez des accolades (`{ }`) pour mettre en évidence des lignes entières, et des guillemets pour mettre en évidence des chaînes de texte.

Il existe trois styles de mise en évidence : neutre pour attirer l'attention sur le code, vert pour indiquer du code inséré, et rouge pour indiquer du code supprimé.
Du texte et des lignes entières peuvent être marqués à l'aide du marqueur par défaut, ou en combinaison avec `ins=` et `del=` pour produire la mise en évidence souhaitée.

Expressive Code fournit plusieurs options pour personnaliser l'apparence visuelle de vos exemples de code.
Beaucoup d'entre elles peuvent être combinées pour obtenir des exemples de code très illustratifs.
Veuillez explorer la [documentation d'Expressive Code](https://expressive-code.com/key-features/text-markers/#configuration) pour obtenir une liste complète des options disponibles.
Certaines des options les plus courantes sont présentées ci-dessous :

- [Marquer des lignes entières et des plages de lignes à l'aide du marqueur `{ }`](https://expressive-code.com/key-features/text-markers/#marking-full-lines--line-ranges) :

  ```js {2-3}
  function demo() {
  	// Cette ligne (#2) et la suivante sont mises en évidence
  	return 'Ceci est la ligne #3 de cet exemple';
  }
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```js {2-3}
  function demo() {
  	// Cette ligne (#2) et la suivante sont mises en évidence
  	return 'Ceci est la ligne #3 de cet exemple';
  }
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```js {% meta="{2-3}" %}
  function demo() {
  	// Cette ligne (#2) et la suivante sont mises en évidence
  	return 'Ceci est la ligne #3 de cet exemple';
  }
  ```
  ````

  </TabItem>

  </Tabs>

- [Marquer des sélections de texte à l'aide du marqueur `" "` ou d'expressions régulières](https://expressive-code.com/key-features/text-markers/#marking-individual-text-inside-lines) :

  ```js "termes individuels" /Même.*charge/
  // Des termes individuels peuvent également être mis en évidence
  function demo() {
  	return 'Même les expressions régulières sont prises en charge';
  }
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```js "termes individuels" /Même.*charge/
  // Des termes individuels peuvent également être mis en évidence
  function demo() {
  	return 'Même les expressions régulières sont prises en charge';
  }
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```js {% meta="'termes individuels' /Même.*charge/" %}
  // Des termes individuels peuvent également être mis en évidence
  function demo() {
  	return 'Même les expressions régulières sont prises en charge';
  }
  ```
  ````

  </TabItem>

  </Tabs>

- [Marquer du texte ou des lignes comme insérés ou supprimés avec `ins` ou `del`](https://expressive-code.com/key-features/text-markers/#selecting-inline-marker-types-mark-ins-del) :

  ```js "return true;" ins="insertion" del="suppression"
  function demo() {
  	console.log("Voici des marqueurs d'insertion et de suppression");
  	// La déclaration return utilise le type de marqueur par défaut
  	return true;
  }
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```js "return true;" ins="insertion" del="suppression"
  function demo() {
  	console.log("Voici des marqueurs d'insertion et de suppression");
  	// La déclaration return utilise le type de marqueur par défaut
  	return true;
  }
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```js {% meta="'return true;' ins='insertion' del='suppression'" %}
  function demo() {
  	console.log("Voici des marqueurs d'insertion et de suppression");
  	// La déclaration return utilise le type de marqueur par défaut
  	return true;
  }
  ```
  ````

  </TabItem>

  </Tabs>

- [Combiner coloration syntaxique et syntaxe de type `diff`](https://expressive-code.com/key-features/text-markers/#combining-syntax-highlighting-with-diff-like-syntax) :

  ```diff lang="js"
    function ceciEstDuJavaScript() {
      // Ce bloc entier utilise la coloration syntaxique JavaScript,
      // et nous pouvons toujours y ajouter des marqueurs de différence !
  -   console.log('Ancien code à supprimer')
  +   console.log('Nouveau code brillant !')
    }
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```diff lang="js"
    function ceciEstDuJavaScript() {
      // Ce bloc entier utilise la coloration syntaxique JavaScript,
      // et nous pouvons toujours y ajouter des marqueurs de différence !
  -   console.log('Ancien code à supprimer')
  +   console.log('Nouveau code brillant !')
    }
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```diff {% meta="lang='js'" %}
    function ceciEstDuJavaScript() {
      // Ce bloc entier utilise la coloration syntaxique JavaScript,
      // et nous pouvons toujours y ajouter des marqueurs de différence !
  -   console.log('Ancien code à supprimer')
  +   console.log('Nouveau code brillant !')
    }
  ```
  ````

  </TabItem>

  </Tabs>

#### Cadres et titres

Les blocs de code peuvent être affichés dans un cadre ressemblant à une fenêtre.
Un cadre ressemblant à une fenêtre de terminal sera utilisé pour les langages de script shell (par exemple `bash` ou `sh`).
Les autres langages s'affichent dans un cadre de style éditeur de code s'ils incluent un titre.

Le titre optionnel d'un bloc de code peut être défini soit avec un attribut `title="..."` après les accents graves d'ouverture et l'identifiant de langage, ou avec un nom de fichier en commentaire sur la première ligne du bloc de code.

- [Ajouter un nom de fichier avec un commentaire](https://expressive-code.com/key-features/frames/#code-editor-frames) :

  ```js
  // mon-fichier-de-test.js
  console.log('Hello World!');
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```js
  // mon-fichier-de-test.js
  console.log('Hello World!');
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````md
  ```js
  // mon-fichier-de-test.js
  console.log('Hello World!');
  ```
  ````

  </TabItem>

  </Tabs>

- [Ajouter un titre à une fenêtre de terminal](https://expressive-code.com/key-features/frames/#terminal-frames) :

  ```bash title="Installation des dépendances…"
  npm install
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```bash title="Installation des dépendances…"
  npm install
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```bash {% title="Installation des dépendances…" %}
  npm install
  ```
  ````

  </TabItem>

  </Tabs>

- [Désactiver les cadres de fenêtre avec `frame="none"`](https://expressive-code.com/key-features/frames/#overriding-frame-types) :

  ```bash frame="none"
  echo "Ceci n'est pas affiché comme un terminal malgré l'utilisation du langage bash"
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```bash frame="none"
  echo "Ceci n'est pas affiché comme un terminal malgré l'utilisation du langage bash"
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```bash {% frame="none" %}
  echo "Ceci n'est pas affiché comme un terminal malgré l'utilisation du langage bash"
  ```
  ````

  </TabItem>

  </Tabs>

## Détails

Détails (également connus comme « divulgations » ou « accordéons ») sont utiles pour masquer du contenu qui n'est pas immédiatement pertinent.
Les utilisateurs peuvent cliquer sur un court résumé pour développer et afficher le contenu complet.

Utilisez les éléments HTML standard [`<details>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/details) et [`<summary>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/summary) dans votre contenu Markdown pour créer un widget de divulgation.

Vous pouvez imbriquer n'importe quelle autre syntaxe Markdown à l'intérieur d'un élément `<details>`.

<details>
<summary>Où et quand la constellation d'Andromède est-elle la plus visible ?</summary>

La [constellation d'Andromède](<https://fr.wikipedia.org/wiki/Androm%C3%A8de_(constellation)>) est la plus visible dans le ciel nocturne pendant le mois de novembre aux latitudes comprises entre `+90°` et `−40°`.

</details>

```md
<details>
<summary>Où et quand la constellation d'Andromède est-elle la plus visible ?</summary>

La [constellation d'Andromède](<https://fr.wikipedia.org/wiki/Androm%C3%A8de_(constellation)>) est la plus visible dans le ciel nocturne pendant le mois de novembre aux latitudes comprises entre `+90°` et `−40°`.

</details>
```

## Notes de bas de page

Les [notes de bas de page](https://www.markdownguide.org/extended-syntax/#footnotes) sont utiles pour ajouter de brèves références ou des précisions sans interrompre la lecture. Elles se présentent sous forme de liens numérotés en exposant qui permettent d'accéder au texte référencé, regroupé en bas de page.

Définissez une note de bas de page à l'aide de crochets contenant un accent circonflexe et une référence numérotée :

```md
Voici une note de bas de page[^1] avec un texte complémentaire après.

[^1]: Ma référence.
```

## Autres fonctionnalités courantes de Markdown

Starlight prend en charge toutes les autres syntaxes de rédaction Markdown, telles que les listes et les tableaux. Voir [Markdown Cheat Sheet from The Markdown Guide](https://www.markdownguide.org/cheat-sheet/) pour un aperçu rapide de tous les éléments de la syntaxe Markdown.

## Configuration avancée de Markdown et MDX

Starlight utilise le moteur de rendu Markdown et MDX d'Astro basé sur remark et rehype. Vous pouvez ajouter la prise en charge de syntaxe et comportement personnalisés en ajoutant `remarkPlugins` ou `rehypePlugins` dans votre fichier de configuration Astro. Pour en savoir plus, consultez [« Modules d’extension Markdown »](https://docs.astro.build/fr/guides/markdown-content/#modules-dextension-markdown) dans la documentation d'Astro.

## Markdoc

Starlight prend en charge la création de contenu en Markdoc en utilisant l'intégration expérimentale [Astro Markdoc](https://docs.astro.build/fr/guides/integrations-guide/markdoc/) et le préréglage Markdoc de Starlight.

### Créer un nouveau projet avec Markdoc

Créez un nouveau projet Starlight avec Markdoc préconfiguré en utilisant `create astro` :

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight/markdoc
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight/markdoc
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight/markdoc
```

</TabItem>
</Tabs>

### Ajouter Markdoc à un projet existant

Si vous disposez déjà d'un site Starlight et que vous souhaitez ajouter Markdoc, suivez ces étapes.

<Steps>

1.  Ajoutez l'intégration Markdoc d'Astro :

    <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npx astro add markdoc
    ```

    </TabItem>

    <TabItem label="pnpm">

    ```sh
    pnpm astro add markdoc
    ```

    </TabItem>

    <TabItem label="Yarn">

    ```sh
    yarn astro add markdoc
    ```

    </TabItem>

    </Tabs>

2.  Installez le préréglage Markdoc de Starlight :

    <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npm install @astrojs/starlight-markdoc
    ```

    </TabItem>

    <TabItem label="pnpm">

    ```sh
    pnpm add @astrojs/starlight-markdoc
    ```

    </TabItem>

    <TabItem label="Yarn">

    ```sh
    yarn add @astrojs/starlight-markdoc
    ```

    </TabItem>

    </Tabs>

3.  Créez une configuration Markdoc dans le fichier `markdoc.config.mjs` et utilisez le préréglage Markdoc de Starlight :

    ```js
    import { defineMarkdocConfig } from '@astrojs/markdoc/config';
    import starlightMarkdoc from '@astrojs/starlight-markdoc';

    export default defineMarkdocConfig({
    	extends: [starlightMarkdoc()],
    });
    ```

</Steps>

Pour en savoir plus sur la syntaxe et les fonctionnalités de Markdoc, consultez la [documentation Markdoc](https://markdoc.dev/docs/syntax) ou le [guide de l'intégration Astro Markdoc](https://docs.astro.build/fr/guides/integrations-guide/markdoc/).

### Configuration du préréglage Markdoc

Le préréglage `starlightMarkdoc()` accepte les options de configuration suivantes :

#### `headingLinks`

**Type :** `boolean`  
**Par défaut :** `true`

Contrôle si les en-têtes sont affichés avec des liens d'ancrage cliquables ou non.
Équivaut à l'option [`markdown.headingLinks`](/fr/reference/configuration/#markdown) qui s'applique aux fichiers Markdown et MDX.

```js "headingLinks: false"
export default defineMarkdocConfig({
	// Désactive les liens d'ancrage par défaut pour les en-têtes
	extends: [starlightMarkdoc({ headingLinks: false })],
});
```


================================================
FILE: docs/src/content/docs/fr/guides/css-and-tailwind.mdx
================================================
---
title: CSS et mise en forme
description: Apprendre à mettre en forme votre site Starlight avec du CSS personnalisé ou l'intégrer avec Tailwind CSS.
---

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

Vous pouvez mettre en forme votre site Starlight avec du CSS personnalisé ou utiliser le module d'extension Tailwind de Starlight.

Pour changer rapidement l'apparence par défaut de votre site, consultez les [thèmes communautaires](/fr/resources/themes/).

## Styles CSS personnalisés

Personnalisez les styles appliqués à votre site Starlight en fournissant des fichiers CSS supplémentaires pour modifier ou étendre les styles par défaut de Starlight.

<Steps>

1. Ajoutez un fichier CSS à votre répertoire `src/`.
   Par exemple, vous pouvez définir une largeur de colonne par défaut plus large et une taille de texte plus grande pour les titres de page :

   ```css
   /* src/styles/custom.css */
   :root {
   	--sl-content-width: 50rem;
   	--sl-text-5xl: 3.5rem;
   }
   ```

2. Ajoutez le chemin vers votre fichier CSS au tableau `customCss` de Starlight dans votre configuration `astro.config.mjs` :

   ```diff lang="js"
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Documentation avec CSS personnalisé',
   			customCss: [
   +				// Chemin relatif vers votre fichier CSS personnalisé
   +				'./src/styles/custom.css',
   			],
   		}),
   	],
   });
   ```

</Steps>

Vous pouvez retrouver toutes les propriétés CSS personnalisées utilisées par Starlight que vous pouvez définir pour personnaliser votre site dans le fichier [`props.css` sur GitHub](https://github.com/withastro/starlight/blob/main/packages/starlight/style/props.css).

### Couche de cascade

Starlight utilise [les couches de cascade](https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Cascade_layers) en interne pour gérer l'ordre de ses styles.
Cela garantit un ordre CSS prévisible et permet des redéfinitions plus simples.
N'importe quel CSS personnalisé ne faisant pas partie d'une couche de cascade redéfinira les styles par défaut de Starlight.

Si vous utilisez des couches de cascade, vous pouvez utiliser [`@layer`](https://developer.mozilla.org/fr/docs/Web/CSS/@layer) dans votre CSS personnalisé pour définir l'ordre de priorité pour différentes couches par rapport aux styles de la couche `starlight` :

```css "starlight"
/* src/styles/custom.css */
@layer ma-reinitialisation, starlight, mes-redefinitions;
```

L'exemple ci-dessus définit une couche personnalisée nommée `ma-reinitialisation`, appliquée avant toutes les couches de Starlight, et une autre nommée `mes-redefinitions`, appliquée après toutes les couches de Starlight.
N'importe quel style dans la couche `mes-redefinitions` aurait priorité sur les styles de Starlight, mais Starlight pourrait toujours changer les styles définis dans la couche `ma-reinitialisation`.

## Tailwind CSS

La prise en charge de Tailwind CSS v4 dans les projets Astro est fourni par le [module d'extension Vite pour Tailwind](https://tailwindcss.com/docs/installation/using-vite).
Starlight fournit du CSS additionnel pour aider à configurer Tailwind pour une compatibilité avec les styles de Starlight.

Le CSS Tailwind de Starlight applique la configuration suivante :

- Configure les variantes `dark:` de Tailwind pour fonctionner avec le mode sombre de Starlight.
- Utilise les [couleurs et polices de thème](#mettre-en-forme-starlight-avec-tailwind) de Tailwind dans l'interface utilisateur de Starlight.
- Restaure des parties essentielles des styles de réinitialisation Preflight de Tailwind.

### Créer un nouveau projet avec Tailwind

Démarrez un nouveau projet Starlight avec Tailwind CSS préconfiguré en utilisant `create astro` :

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight/tailwind
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight/tailwind
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight/tailwind
```

</TabItem>
</Tabs>

### Ajouter Tailwind à un projet existant

Si vous avez déjà un site Starlight et que vous souhaitez ajouter Tailwind CSS, suivez ces étapes.

<Steps>

1.  Initialisez Tailwind dans votre projet en exécutant la commande suivante et en suivant les instructions dans votre terminal :

    <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npx astro add tailwind
    ```

    </TabItem>

    <TabItem label="pnpm">

    ```sh
    pnpm astro add tailwind
    ```

    </TabItem>

    <TabItem label="Yarn">

    ```sh
    yarn astro add tailwind
    ```

    </TabItem>

    </Tabs>

2.  Installez le paquet de compatibilité Tailwind de Starlight :

    <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npm install @astrojs/starlight-tailwind
    ```

    </TabItem>

    <TabItem label="pnpm">

    ```sh
    pnpm add @astrojs/starlight-tailwind
    ```

    </TabItem>

    <TabItem label="Yarn">

    ```sh
    yarn add @astrojs/starlight-tailwind
    ```

    </TabItem>

    </Tabs>

3.  Remplacez le contenu du fichier `src/styles/global.css` créé par Astro pour une compatibilité avec Starlight :

    ```css
    /* src/styles/global.css */
    @layer base, starlight, theme, components, utilities;

    @import '@astrojs/starlight-tailwind';
    @import 'tailwindcss/theme.css' layer(theme);
    @import 'tailwindcss/utilities.css' layer(utilities);
    ```

    Cette configuration de thème Tailwind définit l'ordre des [couches de cascade](#couche-de-cascade) de Starlight, importe le CSS complémentaire de Starlight pour Tailwind et importe les styles des thèmes et utilitaires de Tailwind.
    Si votre projet nécessite une configuration Tailwind supplémentaire, consultez la section [« Utiliser plusieurs configurations Tailwind »](#utiliser-plusieurs-configurations-tailwind).

4.  Mettez à jour la configuration de Starlight pour ajouter le fichier CSS Tailwind en tant que premier élément du tableau `customCss` :

    ```js ins={11-12}
    // astro.config.mjs
    import { defineConfig } from 'astro/config';
    import starlight from '@astrojs/starlight';
    import tailwindcss from '@tailwindcss/vite';

    export default defineConfig({
    	integrations: [
    		starlight({
    			title: 'Documentation avec Tailwind',
    			customCss: [
    				// Chemin vers vos style de base de Tailwind:
    				'./src/styles/global.css',
    			],
    		}),
    	],
    	vite: { plugins: [tailwindcss()] },
    });
    ```

</Steps>

### Mettre en forme Starlight avec Tailwind

Lors de la [création d'un nouveau projet Starlight avec Tailwind](#créer-un-nouveau-projet-avec-tailwind), ou lors de [l'ajout de Tailwind à un projet Starlight existant](#ajouter-tailwind-à-un-projet-existant), Starlight utilisera les valeurs de votre [configuration de thème Tailwind](https://tailwindcss.com/docs/theme) située dans le fichier `src/styles/global.css` pour mettre en forme son interface utilisateur.

Si définies, les propriétés personnalisées CSS suivantes remplaceront les styles par défaut de Starlight :

- `--color-accent-*` — utilisée pour les liens et la mise en évidence de l'élément courant
- `--color-gray-*` — utilisée pour les couleurs d'arrière-plan et les bordures
- `--font-sans` — utilisée pour le texte de l'interface utilisateur et du contenu
- `--font-mono` — utilisée pour les exemples de code

```css {9-12,14-17,19-22,34-37}
/* src/styles/global.css */
@layer base, starlight, theme, components, utilities;

@import '@astrojs/starlight-tailwind';
@import 'tailwindcss/theme.css' layer(theme);
@import 'tailwindcss/utilities.css' layer(utilities);

@theme {
	/*
	Votre police de texte préférée.
	Starlight utilise une pile de polices système par défaut.
	*/
	--font-sans: 'Atkinson Hyperlegible';
	/*
	Votre police de code préférée.
	Starlight utilise des polices système à chasse fixe par défaut.
	*/
	--font-mono: 'IBM Plex Mono';
	/*
	Votre couleur d'accentuation préférée.
	Indigo est la plus proche des valeurs par défaut de Starlight.
	*/
	--color-accent-50: var(--color-indigo-50);
	--color-accent-100: var(--color-indigo-100);
	--color-accent-200: var(--color-indigo-200);
	--color-accent-300: var(--color-indigo-300);
	--color-accent-400: var(--color-indigo-400);
	--color-accent-500: var(--color-indigo-500);
	--color-accent-600: var(--color-indigo-600);
	--color-accent-700: var(--color-indigo-700);
	--color-accent-800: var(--color-indigo-800);
	--color-accent-900: var(--color-indigo-900);
	--color-accent-950: var(--color-indigo-950);
	/*
	Votre échelle de gris préférée.
	Zinc est la plus proche des valeurs par défaut de Starlight.
	*/
	--color-gray-50: var(--color-zinc-50);
	--color-gray-100: var(--color-zinc-100);
	--color-gray-200: var(--color-zinc-200);
	--color-gray-300: var(--color-zinc-300);
	--color-gray-400: var(--color-zinc-400);
	--color-gray-500: var(--color-zinc-500);
	--color-gray-600: var(--color-zinc-600);
	--color-gray-700: var(--color-zinc-700);
	--color-gray-800: var(--color-zinc-800);
	--color-gray-900: var(--color-zinc-900);
	--color-gray-950: var(--color-zinc-950);
}
```

### Utiliser plusieurs configurations Tailwind

Plusieurs configurations Tailwind peuvent être utilisées pour appliquer différents styles à différentes parties de votre site, par exemple lorsque vous [utilisez Starlight dans un sous-chemin](/fr/manual-setup/#utiliser-starlight-dans-un-sous-chemin) ou lorsque vous ajoutez des [pages personnalisées](/fr/guides/pages/#pages-personnalisées) à votre site.
Par exemple, vous souhaiterez peut-être utiliser les styles de réinitialisation Preflight de Tailwind dans vos pages personnalisées, tout en appliquant la couche de compatibilité de Starlight aux pages Starlight.

La configuration Tailwind CSS suivante configure Tailwind sans aucun module d'extension ni configuration supplémentaire et peut être utilisée comme point de départ pour les pages non gérées par Starlight :

```css title="src/styles/custom-pages-tailwind.css"
/* Charge Tailwind sans aucun CSS complémentaire provenant de Starlight. */
@import 'tailwindcss';
```

<Steps>

1. Pour les pages Starlight, appliquez votre configuration Tailwind CSS préférée en suivant [« Ajouter Tailwind à un projet existant »](#ajouter-tailwind-à-un-projet-existant).

2. Pour les autres pages, appliquez votre configuration Tailwind CSS préférée en l'important dans ces pages. Cette opération est souvent effectuée dans un composant de mise en page afin que les styles de Tailwind puissent être utilisés sur toutes les pages partageant cette mise en page.
   ```astro
   ---
   // src/layouts/CustomPageLayout.astro
   import '../styles/custom-pages-tailwind.css';
   ---
   ```

</Steps>

Pour en savoir plus sur les configurations de thème Tailwind, consultez la [documentation de Tailwind CSS](https://tailwindcss.com/docs/theme).

## Personnalisation du thème

Le thème de couleur de Starlight peut être contrôlé en remplaçant ses propriétés personnalisées par défaut.
Ces variables sont utilisées dans toute l'interface utilisateur avec une gamme de nuances de gris utilisées pour les couleurs de texte et d'arrière-plan et une couleur d'accentuation utilisée pour les liens et pour mettre en évidence les éléments courants durant la navigation.

### Éditeur de thème de couleur

Utilisez les contrôles ci-dessous pour modifier les palettes de couleurs d'accentuation et de gris de Starlight.
Les zones d'aperçu sombre et clair afficheront les couleurs résultantes, et la page entière sera également mise à jour pour prévisualiser vos modifications.

Utilisez l'option Niveau de contraste pour spécifier lequel des [standards de contraste de couleur](https://developer.mozilla.org/fr/docs/Web/Accessibility/Understanding_WCAG/Perceivable/Color_contrast) des règles pour l’accessibilité des contenus Web à respecter.

Quand vous êtes satisfait de vos modifications, copiez le code CSS ou Tailwind ci-dessous et utilisez-le dans votre projet.

import ThemeDesigner from '~/components/theme-designer.astro';

<ThemeDesigner
	labels={{
		presets: {
			label: 'Préréglages',
			ocean: 'Océan',
			forest: 'Forêt',
			oxide: 'Oxyde',
			nebula: 'Nébuleuse',
			default: 'Par défaut',
			random: 'Aléatoire',
		},
		contrast: {
			label: 'Niveau de contraste',
		},
		editor: {
			accentColor: 'Accentuation',
			grayColor: 'Gris',
			hue: 'Teinte',
			chroma: 'Chroma',
			pickColor: 'Choisissez une couleur',
		},
		preview: {
			darkMode: 'Mode sombre',
			lightMode: 'Mode clair',
			bodyText:
				"Le corps du texte est affiché dans une teinte grise avec un contraste élevé avec l'arrière-plan.",
			linkText: 'Les liens sont colorés.',
			dimText:
				'Certains textes, comme la table des matières, ont un contraste plus faible.',
			inlineCode: 'Le code en ligne a un arrière-plan distinct.',
		},
	}}
>
	<Fragment slot="css-docs">
		Ajouter le code CSS suivant à votre projet dans un [fichier CSS
		personnalisé](#styles-css-personnalisés) pour appliquer ce thème à votre
		site.
	</Fragment>
	<Fragment slot="tailwind-docs">
		Ajouter les propriétés personnalisées CSS suivantes au bloc `@theme` dans
		votre [fichier CSS Tailwind](#mettre-en-forme-starlight-avec-tailwind) pour
		appliquer ce thème à votre site.
	</Fragment>
</ThemeDesigner>


================================================
FILE: docs/src/content/docs/fr/guides/customization.mdx
================================================
---
title: Personnaliser Starlight
description: Apprenez à vous approprier votre site Starlight avec votre logo, polices personnalisées et bien plus encore.
---

import { Tabs, TabItem, FileTree, Steps } from '@astrojs/starlight/components';

Starlight propose par défaut un style et des fonctionnalités pragmatiques, vous pouvez donc démarrer rapidement sans configuration nécessaire.
Lorsque vous souhaitez commencer à personnaliser l’apparence de votre site Starlight, ce guide vous accompagne.

## Ajouter votre logo

L’ajout d’un logo personnalisé à l’en-tête du site est un moyen rapide d’ajouter votre image de marque personnelle à un site Starlight.

<Steps>

1. Ajoutez votre fichier logo au répertoire `src/assets/` :

   <FileTree>

   - src/
     - assets/
       - **mon-logo.svg**
     - content/
   - astro.config.mjs

   </FileTree>

2. Ajoutez le chemin vers votre logo à votre option de configuration Starlight [`logo.src`](/fr/reference/configuration/#logo) dans `astro.config.mjs` :

   ```diff lang="js"
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Docs Avec Mon Logo',
   			logo: {
   +				src: './src/assets/mon-logo.svg',
   			},
   		}),
   	],
   });
   ```

</Steps>

Par défaut, le logo sera affiché à côté du nom de votre site (option `title` dans la configuration).
Si l’image de votre logo inclut déjà le titre du site, vous pouvez masquer visuellement le texte du titre en définissant l’option `replacesTitle` à `true`.
Le texte du titre (`title`) le texte sera toujours inclus pour les lecteurs d’écran afin que l’en-tête reste accessible.

```js {5}
starlight({
  title: 'Docs Avec Mon Logo',
  logo: {
    src: './src/assets/mon-logo.svg',
    replacesTitle: true,
  },
}),
```

### Variantes claires et sombres de votre logo

Vous pouvez afficher différentes versions de votre logo en modes clair et sombre.

<Steps>

1. Ajouter un fichier image pour chaque variante dans `src/assets/` :

   <FileTree>

   - src/
     - assets/
       - **logo-clair.svg**
       - **logo-sombre.svg**
     - content/
   - astro.config.mjs

   </FileTree>

2. Ajouter les chemins vers vos variantes de logo dans les options `light` (clair) et `dark` (sombre) en remplacement de l’option `src` dans `astro.config.mjs` :

   ```diff lang="js"
   starlight({
     title: 'Docs Avec Mon Logo',
     logo: {
   +    light: './src/assets/logo-clair.svg',
   +    dark: './src/assets/logo-sombre.svg',
     },
   }),
   ```

</Steps>

## Activer un plan de site

Starlight possède une prise en charge intégrée pour la génération d’un plan de site. Activez la génération du plan de site en définissant votre URL comme `site` dans `astro.config.mjs` :

```js {4}
// astro.config.mjs

export default defineConfig({
	site: 'https://stargazers.club',
	integrations: [starlight({ title: 'Site avec un plan de site' })],
});
```

Apprenez comment [ajouter un lien du plan de site au fichier `robots.txt`](https://docs.astro.build/fr/guides/integrations-guide/sitemap/#lien-vers-le-plan-du-site-dans-le-fichier-robotstxt) dans la documentation d'Astro.

## Mise en page

Par défaut, les pages Starlight utilisent une mise en page avec une barre latérale de navigation globale et une table des matières qui affiche les en-têtes de la page courante.

Vous pouvez appliquer une mise en page plus large sans barres latérales en définissant [`template: splash`](/fr/reference/frontmatter/#template) dans le frontmatter de votre page.
Cela fonctionne particulièrement bien pour les pages d’atterissage et vous pouvez le voir en action sur la [page d’accueil de ce site](/fr/).

```md {5}
---
# src/content/docs/index.md

title: Ma page d’atterissage
template: splash
---
```

## Table des matières

Starlight affiche une table des matières sur chaque page pour permettre aux lecteurs d’accéder plus facilement à la section qu’ils recherchent.
Vous pouvez personnaliser - ou même désactiver - la table des matières globalement dans l’intégration Starlight ou page par page dans votre frontmatter.

Par défaut, les en-têtes `<h2>` et `<h3>` sont inclus dans la table des matières. Modifiez les niveaux des en-têtes à inclure à l’échelle du site à l’aide des options `minHeadingLevel` et `maxHeadingLevel` dans votre option de configuration [globale `tableOfContents`](/fr/reference/configuration/#tableofcontents). Remplacez ces valeurs par défaut sur une page individuelle en ajoutant les propriétés [frontmatter `tableOfContents`](/fr/reference/frontmatter/#tableofcontents) correspondantes :

<Tabs syncKey="config-type">
  <TabItem label="Frontmatter">

```md {4-6}
---
# src/content/docs/exemple.md
title: Page avec seulement les H2s dans la table des matières
tableOfContents:
  minHeadingLevel: 2
  maxHeadingLevel: 2
---
```

  </TabItem>
  <TabItem label="Configuration globale">

```js {7}
// astro.config.mjs

defineConfig({
	integrations: [
		starlight({
			title: 'Site avec une configuration de table des matières personnalisée',
			tableOfContents: { minHeadingLevel: 2, maxHeadingLevel: 2 },
		}),
	],
});
```

  </TabItem>
</Tabs>

Désactivez la table des matières complètement en définissant l’option `tableOfContents` à `false` :

<Tabs syncKey="config-type">
  <TabItem label="Frontmatter">

```md {4}
---
# src/content/docs/exemple.md
title: Page sans table des matières
tableOfContents: false
---
```

  </TabItem>
  <TabItem label="Configuration globale">

```js {7}
// astro.config.mjs

defineConfig({
	integrations: [
		starlight({
			title: 'Site avec la table des matières désactivée globalement',
			tableOfContents: false,
		}),
	],
});
```

  </TabItem>
</Tabs>

## Liens sociaux

Starlight prend en charge par défaut l’ajout de liens vers vos comptes de médias sociaux dans l’en-tête du site via l’option [`social`](/fr/reference/configuration/#social) dans l’intégration Starlight.

Chaque entrée dans le tableau `social` doit être un objet avec trois propriétés :

- `icon` : une des [icônes intégrées à Starlight](/fr/reference/icons/), par exemple `"github"`.
- `label` : une étiquette utilisée pour l’accessibilité, par exemple `"GitHub"`.
- `href` : l'URL du lien, par exemple `"https://github.com/withastro/starlight"`.

L'exemple suivant ajoute des liens vers le Discord d'Astro et le dépôt GitHub de Starlight :

```js {9-16}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Site avec des liens sociaux',
			social: [
				{ icon: 'discord', label: 'Discord', href: 'https://astro.build/chat' },
				{
					icon: 'github',
					label: 'GitHub',
					href: 'https://github.com/withastro/starlight',
				},
			],
		}),
	],
});
```

## Liens d’édition de page

Starlight peut afficher un lien « Modifier cette page » dans le pied de page de chaque page.
Cela permet au lecteur de trouver facilement le fichier à modifier pour améliorer vos documents.
Pour les projets open source en particulier, cela peut aider à encourager les contributions de votre communauté.

Pour activer les liens de modification, définissez l’option de configuration [`editLink.baseUrl`](/fr/reference/configuration/#editlink) en lui assignant l’URL utilisée pour modifier votre dépôt dans la configuration de l’intégration Starlight.
La valeur de `editLink.baseUrl` sera automatiquement ajoutée au chemin d’accès vers la page actuelle pour former le lien d’édition complet.

Les formes d’URL les plus courantes incluent :

- GitHub : `https://github.com/NOM_UTILISATEUR/NOM_DU_DEPOT/edit/NOM_DE_LA_BRANCHE/`
- GitLab : `https://gitlab.com/NOM_UTILISATEUR/NOM_DU_DEPOT/-/edit/NOM_DE_LA_BRANCHE/`

Si votre projet Starlight ne se trouve pas à la racine de votre dépôt, incluez le chemin d’accès au projet à la fin de l’URL de base.

Cet exemple montre le lien d’édition configuré pour les documents Starlight, qui se trouvent dans le sous-répertoire `docs/` sur la branche `main` du dépôt `withastro/starlight` sur GitHub :

```js {9-11}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Sites avec liens d’édition de page',
			editLink: {
				baseUrl: 'https://github.com/withastro/starlight/edit/main/docs/',
			},
		}),
	],
});
```

## Page 404 personnalisée

Les sites Starlight affichent par défaut une simple page 404.
Vous pouvez personnaliser cela en ajoutant un fichier `404.md` (ou `404.mdx`) à votre répertoire `src/content/docs/` :

<FileTree>

- src/
  - content/
    - docs/
      - **404.md**
      - index.md
- astro.config.mjs

</FileTree>

Vous pouvez utiliser toutes les techniques de mise en page et de personnalisation de Starlight dans votre page 404. Par exemple, la page 404 par défaut utilise la [mise en page `splash`](#mise-en-page) et le composant [`hero`](/fr/reference/frontmatter/#hero) dans son frontmatter :

```md {4,6-8}
---
# src/content/docs/404.md
title: '404'
template: splash
editUrl: false
hero:
  title: '404'
  tagline: Page introuvable. Vérifiez l’URL ou essayez la barre de recherche.
---
```

### Désactiver la page 404 par défaut

Si votre projet nécessite une mise en page entièrement personnalisée pour votre page 404, vous pouvez créer une route `src/pages/404.astro` et définir l'option de configuration [`disable404Route`](/fr/reference/configuration/#disable404route) pour désactiver la route par défaut de Starlight :

```js {9}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Documentation avec 404 personnalisée',
			disable404Route: true,
		}),
	],
});
```

## Polices personnalisées

Par défaut, Starlight utilise des polices sans empattement disponibles en local sur la machine du visiteur pour tout les textes.
Cela garantit que la documentation se charge rapidement dans une police familière à chaque utilisateur, sans nécessiter de bande passante supplémentaire pour télécharger des fichiers de police volumineux.

Si vous souhaitez ajouter une police personnalisée à votre site Starlight, vous pouvez configurer les polices à utiliser dans des fichiers CSS personnalisés ou avec toute autre [technique de style Astro](https://docs.astro.build/fr/guides/styling/).

### Configurer les polices

Si vous avez déjà des fichiers de polices, suivez le [guide de configuration locale](#configurer-les-polices-localement).
Pour utiliser Google Fonts, suivez le [Guide de configuration de Fontsource](#configurer-les-polices-avec-fontsource).

#### Configurer les polices localement

<Steps>

1. Ajoutez vos fichiers de polices dans un répertoire `src/fonts/` et créez un fichier `font-face.css` vide :

   <FileTree>

   - src/
     - content/
     - fonts/
       - **PolicePersonnalisee.woff2**
       - **font-face.css**
   - astro.config.mjs

   </FileTree>

2. Ajoutez une [déclaration `@font-face`](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face) pour chacune de vos polices dans `src/fonts/font-face.css`.
   Utilisez le chemin relatif vers le fichier de police dans la fonction `url()`.

   ```css
   /* src/fonts/font-face.css */

   @font-face {
   	font-family: 'Police Personnalisee';
   	/* Utilisez le chemin relatif vers le fichier de police dans la fonction `url()`. */
   	src: url('./PolicePersonnalisee.woff2') format('woff2');
   	font-weight: normal;
   	font-style: normal;
   	font-display: swap;
   }
   ```

3. Ajoutez le chemin de votre fichier `font-face.css` au tableau `customCss` de Starlight dans `astro.config.mjs` :

   ```diff lang="js"
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Site avec polices personnalisées',
   			customCss: [
   +				// Chemin relatif vers votre fichier CSS @font-face.
   +				'/src/fonts/font-face.css',
   			],
   		}),
   	],
   });
   ```

</Steps>

#### Configurer les polices avec Fontsource

Le projet [Fontsource](https://fontsource.org/) simplifie l’utilisation des polices Google et d’autres polices open source.
Il fournit des modules npm que vous pouvez installer pour les polices que vous souhaitez utiliser et inclut des fichiers CSS prêts à l’emploi à ajouter à votre projet.

<Steps>

1.  Trouvez la police que vous souhaitez utiliser dans le [catalogue de Fontsource](https://fontsource.org/).
    Cet exemple utilisera [IBM Plex Serif](https://fontsource.org/fonts/ibm-plex-serif).

2.  Installez le paquet pour la police choisie.
    Vous pouvez trouver le nom du paquet en cliquant sur « Installer » sur la page de police Fontsource.

        <Tabs syncKey="pkg">

    <TabItem label="npm">

        ```sh
        npm install @fontsource/ibm-plex-serif
        ```

          </TabItem>

          <TabItem label="pnpm">

        ```sh
        pnpm add @fontsource/ibm-plex-serif
        ```

          </TabItem>

          <TabItem label="Yarn">

        ```sh
        yarn add @fontsource/ibm-plex-serif
        ```

        </TabItem>

      </Tabs>

3.  Ajoutez les fichiers CSS Fontsource au tableau `customCss` de Starlight dans `astro.config.mjs` :

        ```diff lang="js"
        // astro.config.mjs
        import { defineConfig } from "astro/config";
        import starlight from "@astrojs/starlight";

        export default defineConfig({
          integrations: [
            starlight({
              title: "Site avec polices personnalisées Fontsource",
              customCss: [
        +        // Fichiers Fontsource pour les graisses regular et semi-bold.
        +        "@fontsource/ibm-plex-serif/400.css",
        +        "@fontsource/ibm-plex-serif/600.css",
              ],
            }),
          ],
        });
        ```

    Fontsource fournit plusieurs fichiers CSS pour chaque police. Consultez la [documentation Fontsource](https://fontsource.org/docs/getting-started/install#4-weights-and-styles) sur l’inclusion de différentes graisses et styles pour comprendre lesquels utiliser.

</Steps>

### Utiliser vos polices personnalisées

Une fois configurée, pour appliquer votre police personnalisée à votre site, utilisez le nom de la police que vous avez choisie dans un [fichier CSS personnalisé](/fr/guides/css-and-tailwind/#styles-css-personnalisés).
Par exemple, pour remplacer la police par défaut de Starlight partout, définissez la propriété personnalisée `--sl-font` :

```css
/* src/styles/custom.css */

:root {
	--sl-font: 'IBM Plex Serif', serif;
}
```

Vous pouvez également écrire du CSS plus ciblé si vous souhaitez appliquer votre police de manière plus sélective.
Par exemple, pour définir uniquement une police sur le contenu principal, mais pas sur les barres latérales :

```css
/* src/styles/custom.css */

main {
	font-family: 'IBM Plex Serif', serif;
}
```

Suivez les [instructions de CSS personnalisé](/fr/guides/css-and-tailwind/#styles-css-personnalisés) pour ajouter vos styles à votre site.


================================================
FILE: docs/src/content/docs/fr/guides/i18n.mdx
================================================
---
title: Internationalisation (i18n)
description: Apprenez à configurer votre site Starlight pour qu'il prenne en charge plusieurs langues.
---

import { FileTree, Steps } from '@astrojs/starlight/components';

Starlight offre une prise en charge intégrée des sites multilingues, y compris le routage, le contenu de repli et la prise en charge complète des langues de droite à gauche (RTL).

## Configurer i18n

<Steps>

1. Indiquez à Starlight les langues que vous prenez en charge en passant [`locales`](/fr/reference/configuration/#locales) et [`defaultLocale`](/fr/reference/configuration/#defaultlocale) à l'intégration Starlight :

   ```js {9-26}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'My Docs',
   			// Définit l'anglais comme langue par défaut pour ce site.
   			defaultLocale: 'en',
   			locales: {
   				// Docs en anglais dans `src/content/docs/en/`
   				en: {
   					label: 'English',
   				},
   				// Docs en chinois simplifié dans `src/content/docs/zh-cn/`
   				'zh-cn': {
   					label: '简体中文',
   					lang: 'zh-CN',
   				},
   				// Docs en arabe dans `src/content/docs/ar/`
   				ar: {
   					label: 'العربية',
   					dir: 'rtl',
   				},
   			},
   		}),
   	],
   });
   ```

   Votre `defaultLocale` sera utilisé pour le contenu de repli et les étiquettes de l'interface utilisateur, donc choisissez la langue dans laquelle vous êtes le plus susceptible de commencer à écrire du contenu, ou pour laquelle vous avez déjà du contenu.

2. Créez un répertoire pour chaque langue dans `src/content/docs/`.
   Par exemple, pour la configuration montrée ci-dessus, créez les dossiers suivants :

   <FileTree>

   - src/
     - content/
       - docs/
         - ar/
         - en/
         - zh-cn/

   </FileTree>

3. Vous pouvez maintenant ajouter des fichiers de contenu dans vos répertoires de langues. Utilisez le même nom de fichier pour associer les pages d'une langue à l'autre et profiter de l'ensemble des fonctionnalités i18n de Starlight, y compris le contenu de repli, les avis de traduction, etc.

   Par exemple, créez `ar/index.md` et `en/index.md` pour représenter la page d'accueil en arabe et en anglais respectivement.

</Steps>

Pour les scénarios i18n plus avancés, Starlight prend également en compte la configuration de l'internationalisation à l'aide de l'option de [configuration `i18n` d'Astro](https://docs.astro.build/fr/guides/internationalization/#configurer-le-routage-i18n).

### Utiliser une locale racine

Vous pouvez utiliser une locale « racine » pour servir une langue sans aucun préfixe i18n dans son chemin. Par exemple, si l'anglais est votre locale racine, le chemin d'une page en anglais ressemblera à `/about` au lieu de `/en/about`.

Pour définir une locale racine, utilisez la clé `root` dans votre configuration `locales`. Si la locale racine est aussi la locale par défaut de votre contenu, supprimez `defaultLocale` ou donnez-lui la valeur `'root'`.

```js {9,11-14}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'My Docs',
			defaultLocale: 'root', // optionnel
			locales: {
				root: {
					label: 'English',
					lang: 'en', // lang est nécessaire pour les locales racine
				},
				'zh-cn': {
					label: '简体中文',
					lang: 'zh-CN',
				},
			},
		}),
	],
});
```

Lorsque vous utilisez une locale racine avec la clé `root`, conservez les pages de cette langue directement dans `src/content/docs/` au lieu d'un dossier dédié à cette langue. Par exemple, voici les fichiers de la page d'accueil pour l'anglais et le chinois en utilisant la configuration ci-dessus :

<FileTree>

- src/
  - content/
    - docs/
      - **index.md**
      - zh-cn/
        - **index.md**

</FileTree>

#### Sites monolingues

Par défaut, Starlight est un site monolingue (anglais). Pour créer un site monolingue dans une autre langue, définissez-la comme `root` dans votre configuration `locales` :

```diff lang="js" {10-13}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'My Docs',
			locales: {
				root: {
					label: '简体中文',
					lang: 'zh-CN',
				},
			},
		}),
	],
});
```

Cela vous permet de remplacer la langue par défaut de Starlight sans activer d'autres fonctions d'internationalisation pour les sites multilingues, telles que le sélecteur de langue.

## Contenu de repli

Starlight s'attend à ce que vous créiez des pages équivalentes dans toutes vos langues. Par exemple, si vous avez un fichier `en/about.md`, créez un `about.md` pour chaque autre langue que vous prenez en charge. Cela permet à Starlight de fournir un contenu de repli automatique pour les pages qui n'ont pas encore été traduites.

Si une traduction n'est pas encore disponible pour une langue, Starlight affichera aux lecteurs le contenu de cette page dans la langue par défaut (définie via `defaultLocale`). Par exemple, si vous n'avez pas encore créé de version française de votre page À propos et que votre langue par défaut est l'anglais, les visiteurs de `/fr/about` verront le contenu anglais de `/en/about` avec un avis indiquant que cette page n'a pas encore été traduite. Cela vous permet d'ajouter du contenu dans votre langue par défaut et de le traduire progressivement lorsque vos traducteurs en ont le temps.

## Traduire le titre du site

Par défaut, Starlight utilisera le même titre de site pour toutes les langues.
Si vous avez besoin de personnaliser le titre pour chaque langue, vous pouvez passer un objet à [`title`](/fr/reference/configuration/#title-obligatoire) dans les options de Starlight :

```diff lang="js"
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
-			title: 'Ma documentation',
+			title: {
+				fr: 'Ma documentation',
+				'zh-CN': '我的文档',
+			},
			defaultLocale: 'fr',
			locales: {
				fr: { label: 'Français' },
				'zh-cn': { label: '简体中文', lang: 'zh-CN' },
			},
		}),
	],
});
```

## Traduire l'interface utilisateur de Starlight

import LanguagesList from '~/components/languages-list.astro';
import UIStringsList from '~/components/ui-strings-list.astro';

En plus d'héberger des fichiers de contenu traduits, Starlight vous permet de traduire les chaînes de l'interface utilisateur par défaut (par exemple, l'en-tête « Sur cette page » dans la table des matières) afin que vos lecteurs puissent découvrir votre site entièrement dans la langue sélectionnée.

Les textes de l'interface utilisateur traduits en <LanguagesList />
sont disponibles prêts à l'emploi, et nous acceptons les
[contributions pour ajouter d'autres langues par défaut](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md).

Vous pouvez fournir des traductions pour les langues supplémentaires que vous prenez en charge — ou remplacer nos étiquettes par défaut — via la collection de contenus `i18n`.

<Steps>

1. Configurez la collection de contenus `i18n` dans `src/content.config.ts` si elle n'est pas déjà configurée :

   ```diff lang="js" ins=/, (i18nLoader|i18nSchema)/
   // src/content.config.ts
   import { defineCollection } from 'astro:content';
   import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
   import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';

   export const collections = {
   	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
   +	i18n: defineCollection({ loader: i18nLoader(), schema: i18nSchema() }),
   };
   ```

2. Créez un fichier JSON dans `src/content/i18n/` pour chaque locale supplémentaire pour laquelle vous voulez fournir des chaînes de traduction pour l'interface utilisateur.
   Par exemple, cela ajouterait des fichiers de traduction pour l'arabe et le chinois simplifié :

   <FileTree>

   - src/
     - content/
       - i18n/
         - ar.json
         - zh-CN.json

   </FileTree>

3. Ajoutez des traductions pour les clés que vous souhaitez traduire dans les fichiers JSON. Traduire uniquement les valeurs, en laissant les clés en anglais (e.g. `"search.label": "Buscar"`).

   Voici les valeurs anglaises par défaut des chaînes de caractères existantes avec lesquelles Starlight est livré :

   <UIStringsList />

   Les blocs de code de Starlight fonctionnent grâce à la librairie [Expressive Code](https://expressive-code.com/).
   Vous pouvez définir des traductions pour les textes de l'interface utilisateur utilisés dans le même fichier JSON en utilisant les clés `expressiveCode` :

   ```json
   {
   	"expressiveCode.copyButtonCopied": "Copied!",
   	"expressiveCode.copyButtonTooltip": "Copy to clipboard",
   	"expressiveCode.terminalWindowFallbackTitle": "Terminal window"
   }
   ```

   Le module de recherche de Starlight s’appuie sur la librairie [Pagefind](https://pagefind.app/).
   Vous pouvez définir des traductions pour l’interface utilisateur de Pagefind dans le même fichier JSON en utilisant les clés `pagefind` :

   ```json
   {
   	"pagefind.clear_search": "Clear",
   	"pagefind.load_more": "Load more results",
   	"pagefind.search_label": "Search this site",
   	"pagefind.filters_label": "Filters",
   	"pagefind.zero_results": "No results for [SEARCH_TERM]",
   	"pagefind.many_results": "[COUNT] results for [SEARCH_TERM]",
   	"pagefind.one_result": "[COUNT] result for [SEARCH_TERM]",
   	"pagefind.alt_search": "No results for [SEARCH_TERM]. Showing results for [DIFFERENT_TERM] instead",
   	"pagefind.search_suggestion": "No results for [SEARCH_TERM]. Try one of the following searches:",
   	"pagefind.searching": "Searching for [SEARCH_TERM]..."
   }
   ```

 </Steps>

### Étendre le schéma de traduction

Ajoutez des clés personnalisées aux dictionnaires de traduction de votre site en définissant `extend` dans les options de `i18nSchema()`.
Dans l'exemple suivant, une nouvelle clé optionnelle `custom.label` est ajoutée aux clés par défaut :

```diff lang="js"
// src/content.config.ts
import { defineCollection, z } from 'astro:content';
import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';

export const collections = {
	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
	i18n: defineCollection({
		loader: i18nLoader(),
		schema: i18nSchema({
+			extend: z.object({
+				'custom.label': z.string().optional(),
+			}),
		}),
	}),
};
```

Consultez [« Définir un schéma de collection de contenus »](https://docs.astro.build/fr/guides/content-collections/#définition-dun-schéma-de-collection) dans la documentation d'Astro pour en savoir plus sur les schémas de collection de contenus.

## Utiliser les traductions de l'interface utilisateur

Vous pouvez accéder aux [chaînes de l'interface utilisateur intégrées](/fr/guides/i18n/#traduire-linterface-utilisateur-de-starlight) à Starlight ainsi qu'aux chaînes de l'interface utilisateur [définies par l'utilisateur](/fr/guides/i18n/#étendre-le-schéma-de-traduction), et celles [fournies par les modules d'extension](/fr/reference/plugins/#injecttranslations) via une API unifiée utilisant [i18next](https://www.i18next.com/).
Cela inclut la prise en charge de fonctionnalités telles que [l'interpolation](https://www.i18next.com/translation-function/interpolation) et [la pluralisation](https://www.i18next.com/translation-function/plurals).

Dans les composants Astro, cette API est disponible via l'[objet global `Astro`](https://docs.astro.build/fr/reference/api-reference/#astrolocals) sous le nom `Astro.locals.t` :

```astro title="exemple.astro"
<p dir={Astro.locals.t.dir()}>
	{Astro.locals.t('404.text')}
</p>
```

Vous pouvez également utiliser l'API dans les [points de terminaison](https://docs.astro.build/fr/guides/endpoints/), où l'objet `locals` est disponible dans le cadre du [contexte du point de terminaison](https://docs.astro.build/fr/reference/api-reference/#contextlocals) :

```ts title="src/pages/404.ts"
export const GET = (context) => {
	return new Response(context.locals.t('404.text'));
};
```

Dans le contexte d'un module d'extension Starlight, vous pouvez utiliser l'utilitaire [`useTranslations()`](/fr/reference/plugins/#usetranslations) pour accéder à cette API pour une langue spécifique.
Consultez la [référence des modules d'extension](/fr/reference/plugins/) pour plus d'informations.

### Afficher une chaîne de l'interface utilisateur

Affichez une chaîne de l'interface utilisateur en utilisant la fonction `locals.t()`.
C'est une instance de la fonction `t()` d'i18next, qui prend une clé de chaîne d'interface utilisateur en premier argument et renvoie la traduction correspondante pour la langue actuelle.

Par exemple, étant donné un fichier de traduction personnalisé avec le contenu suivant :

```json title="src/content/i18n/fr.json"
{
	"link.astro": "Documentation d'Astro",
	"link.astro.custom": "Documentation d'Astro pour {{feature}}"
}
```

La première chaîne d'interface utilisateur peut être affichée en passant `'link.astro'` à la fonction `t()` :

```astro {3}
<!-- src/components/Exemple.astro -->
<a href="https://docs.astro.build/">
	{Astro.locals.t('link.astro')}
</a>
<!-- Affiche: <a href="...">Documentation d'Astro</a> -->
```

La deuxième chaîne d'interface utilisateur utilise la [syntaxe d'interpolation](https://www.i18next.com/translation-function/interpolation) d'i18next pour le paramètre `{{feature}}`.
La valeur de `feature` doit être définie dans un objet d'options passé en tant que deuxième argument à `t()` :

```astro {3}
<!-- src/components/Exemple.astro -->
<a href="https://docs.astro.build/en/guides/astro-db/">
	{Astro.locals.t('link.astro.custom', { feature: 'Astro DB' })}
</a>
<!-- Affiche: <a href="...">Documentation d'Astro pour Astro DB</a> -->
```

Consultez la [documentation d'i18next](https://www.i18next.com/overview/api#t) pour plus d'informations sur l'utilisation de la fonction `t()` avec l'interpolation, le formatage, et plus encore.

### APIs avancées

#### `t.all()`

La fonction `locals.t.all()` renvoie un objet contenant toutes les chaînes d'interface utilisateur disponibles pour la langue actuelle.

```astro
---
// src/components/Exemple.astro
const allStrings = Astro.locals.t.all();
//    ^
//    {
//      "skipLink.label": "Aller au contenu",
//      "search.label": "Rechercher",
//      …
//    }
---
```

#### `t.exists()`

Pour vérifier si une clé de traduction existe, utilisez la fonction `locals.t.exists()` avec la clé de traduction comme premier argument.
Passez un deuxième argument facultatif si vous avez besoin de vérifier qu'une traduction existe pour une langue spécifique.

```astro
---
// src/components/Exemple.astro
const keyExists = Astro.locals.t.exists('a.key');
//    ^ true
const keyExistsInFrench = Astro.locals.t.exists('other.key', { lngs: ['fr'] });
//    ^ false
---
```

Consultez la [référence pour `exists()` dans la documentation d'i18next](https://www.i18next.com/overview/api#exists) pour plus d'informations.

#### `t.dir()`

La fonction `locals.t.dir()` renvoie la direction du texte de la langue actuelle ou d'une langue spécifique.

```astro
---
// src/components/Exemple.astro
const currentDirection = Astro.locals.t.dir();
//    ^
//    'ltr'
const arabicDirection = Astro.locals.t.dir('ar');
//    ^
//    'rtl'
---
```

Consultez la [référence pour `dir()` dans la documentation d'i18next](https://www.i18next.com/overview/api#dir) pour plus d'informations.

## Accès aux paramètres régionaux

Vous pouvez utiliser [`Astro.currentLocale`](https://docs.astro.build/fr/reference/api-reference/#astrocurrentlocale) pour lire les paramètres régionaux et linguistiques actuels dans les composants `.astro`.

L'exemple suivant lit les paramètres régionaux actuels et les utilise avec la fonction [`getRelativeLocaleUrl()`](https://docs.astro.build/fr/reference/modules/astro-i18n/#getrelativelocaleurl) pour générer un lien vers une page d'information dans la langue actuelle :

```astro
---
// src/components/AboutLink.astro
import { getRelativeLocaleUrl } from 'astro:i18n';
---

<a href={getRelativeLocaleUrl(Astro.currentLocale ?? 'en', 'about')}>À propos</a
>
```


================================================
FILE: docs/src/content/docs/fr/guides/overriding-components.mdx
================================================
---
title: Redéfinition de composants
description: Apprenez à redéfinir les composants intégrés à Starlight pour ajouter des éléments personnalisés à l’interface utilisateur de votre site de documentation.
---

import { Steps } from '@astrojs/starlight/components';

L'interface utilisateur et les options de configuration par défaut de Starlight sont conçues pour être flexibles et fonctionner pour une variété de contenus. Une grande partie de l'apparence par défaut de Starlight peut être personnalisée grâce au [CSS](/fr/guides/css-and-tailwind/) et aux [options de configuration](/fr/guides/customization/).

Quand vos besoins dépassent ce qui est possible de base, Starlight prend en charge la création de vos propres composants personnalisés pour étendre ou redéfinir (remplacer complètement) ses composants par défaut.

## Quand redéfinir

Redéfinir les composants par défaut de Starlight peut être utile lorsque :

- Vous souhaitez modifier l'apparence d'une partie de l'interface utilisateur de Starlight d'une manière qui n'est pas possible avec du [CSS personnalisé](/fr/guides/css-and-tailwind/).
- Vous souhaitez modifier le comportement d'une partie de l'interface utilisateur de Starlight.
- Vous souhaitez ajouter certains éléments supplémentaires à l'interface utilisateur existante de Starlight.

## Comment redéfinir

<Steps>

1. Choisissez le composant de Starlight que vous souhaitez redéfinir.
   Vous pouvez trouver une liste complète des composants dans la [référence des redéfinitions](/fr/reference/overrides/).

   :::tip
   Vous ne savez pas quel composant vous devez redéfinir ? Utilisez la [carte interactive des redéfinitions de Starlight](https://starlight-overrides-map.netlify.app/) pour découvrir les noms des composants de l'interface utilisateur de Starlight.
   :::

   Cet exemple va redéfinir le composant [`SocialIcons`](/fr/reference/overrides/#socialicons) de Starlight dans la barre de navigation de la page.

2. Créez un composant Astro pour remplacer le composant de Starlight.
   Cet exemple affiche un lien de contact.

   ```astro
   ---
   // src/components/EmailLink.astro

   const email = 'houston@example.com';
   ---

   <a href=`mailto:${email}`>Me contacter par courriel</a>
   ```

3. Configurez Starlight pour utiliser votre composant personnalisé avec l'option de configuration [`components`](/fr/reference/configuration/#components) dans le fichier `astro.config.mjs` :

   ```js {9-12}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Ma documentation avec redéfinitions',
   			components: {
   				// Redéfinit le composant par défaut `SocialIcons`.
   				SocialIcons: './src/components/EmailLink.astro',
   			},
   		}),
   	],
   });
   ```

</Steps>

## Réutiliser un composant intégré

Vous pouvez utiliser les composants par défaut de Starlight de la même manière que les vôtres : en les important et en les affichant dans vos propres composants personnalisés. Cela vous permet de conserver toute l'interface utilisateur de base de Starlight dans votre design, tout en ajoutant des éléments supplémentaires à côté.

L'exemple ci-dessous montre un composant personnalisé qui affiche un lien de courriel suivi du composant `SocialIcons` par défaut :

```astro {3,7}
---
// src/components/EmailLink.astro
import Default from '@astrojs/starlight/components/SocialIcons.astro';
---

<a href="mailto:houston@example.com">Me contacter par courriel</a>
<Default><slot /></Default>
```

Lorsque vous affichez un composant intégré dans un composant personnalisé, ajoutez un élément [`<slot />`](https://docs.astro.build/fr/basics/astro-components/#les-slots) à l'intérieur du composant par défaut. Cela permet de s'assurer que si le composant reçoit des éléments enfants, Astro sait où les afficher.

Si vous réutilisez les composants [`PageFrame`](/fr/reference/overrides/#pageframe) ou [`TwoColumnContent`](/fr/reference/overrides/#twocolumncontent) qui contiennent des [slots nommés](https://docs.astro.build/fr/basics/astro-components/#les-slots-nomm%C3%A9s), vous devez également [transférer](https://docs.astro.build/fr/basics/astro-components/#transf%C3%A9rer-des-slots) ces slots.

L'exemple ci-dessous montre un composant personnalisé qui réutilise le composant `TwoColumnContent` qui contient un slot supplémentaire nommé `right-sidebar` qui doit être transféré :

```astro {8}
---
// src/components/CustomContent.astro
import Default from '@astrojs/starlight/components/TwoColumnContent.astro';
---

<Default>
	<slot />
	<slot name="right-sidebar" slot="right-sidebar" />
</Default>
```

## Utiliser les données de la page

Lorsque vous redéfinissez un composant de Starlight, vous pouvez accéder à l'objet global [`starlightRoute`](/fr/guides/route-data/) contenant toutes les données de la page courante.
Cela vous permet d'utiliser ces valeurs pour contrôler la manière dont votre composant est affiché.

Dans l'exemple suivant, un composant de remplacement [`PageTitle`](/fr/reference/overrides/#pagetitle) affiche le titre de la page actuelle tel qu'il est défini dans le frontmatter du contenu :

```astro {4} "{title}"
---
// src/components/Title.astro

const { title } = Astro.locals.starlightRoute.entry.data;
---

<h1 id="_top">{title}</h1>

<style>
	h1 {
		font-family: 'Comic Sans';
	}
</style>
```

Pour en savoir plus sur les propriétés disponibles, consultez la [référence des données de route](/fr/reference/route-data/).

### Redéfinir uniquement sur des pages spécifiques

Les redéfinitions de composants s'appliquent à toutes les pages. Cependant, vous pouvez les utiliser conditionnellement grâce aux valeurs de `starlightRoute` pour déterminer quand afficher votre interface utilisateur personnalisée, quand afficher l'interface utilisateur par défaut de Starlight, ou même quand afficher quelque chose de complètement différent.

Dans l'exemple suivant, un composant redéfinissant le composant [`Footer`](/fr/reference/overrides/#footer) de Starlight affiche « Construit avec Starlight 🌟 » sur la page d'accueil uniquement, et affiche sinon le pied de page par défaut sur toutes les autres pages :

```astro
---
// src/components/ConditionalFooter.astro
import Default from '@astrojs/starlight/components/Footer.astro';

const isHomepage = Astro.locals.starlightRoute.id === '';
---

{
	isHomepage ? (
		<footer>Construit avec Starlight 🌟</footer>
	) : (
		<Default>
			<slot />
		</Default>
	)
}
```

Pour en savoir plus sur le rendu conditionnel, consultez le [guide de syntaxe d'Astro](https://docs.astro.build/fr/basics/astro-syntax/#html-dynamique).


================================================
FILE: docs/src/content/docs/fr/guides/pages.mdx
================================================
---
title: Pages
description: Apprenez à créer et à gérer les pages de votre site de documentation avec Starlight.
sidebar:
  order: 1
tableOfContents:
  maxHeadingLevel: 4
---

Starlight génère les pages HTML de votre site en fonction de votre contenu, avec des options flexibles fournies via le frontmatter du fichier Markdown.
En outre, les projets Starlight bénéficient d'un accès complet aux [puissants outils de génération de pages d'Astro](https://docs.astro.build/fr/basics/astro-pages/).
Ce guide montre comment fonctionne la génération de pages dans Starlight.

## Pages de contenu

### Formats de fichiers

Starlight prend en charge la création de contenu en Markdown et MDX sans aucune configuration requise.
Vous pouvez ajouter la prise en charge de Markdoc en suivant le [guide « Markdoc »](/fr/guides/authoring-content/#markdoc).

### Ajouter des pages

Ajoutez de nouvelles pages à votre site en créant des fichiers `.md` ou `.mdx` dans `src/content/docs/`.
Utilisez des sous-dossiers pour organiser vos fichiers et pour créer plusieurs segments de chemin.

Par exemple, la structure de fichier suivante générera des pages à `exemple.com/hello-world` et `exemple.com/reference/faq` :

import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src/
  - content/
    - docs/
      - hello-world.md
      - reference/
        - faq.md

</FileTree>

### Frontmatter avec sûreté du typage

Toutes les pages Starlight partagent un [ensemble commun de propriétés de frontmatter](/fr/reference/frontmatter/) personnalisable pour contrôler l'apparence de la page :

```md
---
title: Bonjour tout le monde !
description: Voici une page de mon site propulsé par Starlight
---
```

Si vous oubliez quelque chose d'important, Starlight vous le fera savoir.

## Pages personnalisées

Pour les cas d'utilisation avancés, vous pouvez ajouter des pages personnalisées en créant un répertoire `src/pages/`.
Le répertoire `src/pages/` utilise le [routage basé sur les fichiers d'Astro](https://docs.astro.build/fr/basics/astro-pages/#routage-basé-sur-les-fichiers) et inclut la prise en charge des fichiers `.astro` parmi d'autres formats de pages.
Ceci est utile si vous avez besoin de créer des pages avec une mise en page complètement personnalisée ou de générer une page à partir d'une source de données alternative.

Par exemple, ce projet mélange du contenu Markdown dans `src/content/docs/` avec des routes Astro et HTML dans `src/pages/` :

<FileTree>

- src/
  - content/
    - docs/
      - hello-world.md
  - pages/
    - custom.astro
    - archived.html

</FileTree>

Pour en savoir plus, consultez le guide [« Pages » dans la documentation d'Astro](https://docs.astro.build/fr/basics/astro-pages/).

### Utiliser le design de Starlight dans des pages personnalisées

Pour utiliser la mise en page de Starlight dans des pages personnalisées, englobez le contenu de votre page avec le [composant `<StarlightPage />`](#composant-starlightpage).
Cela peut s'avérer utile si vous générez du contenu de manière dynamique, mais que vous souhaitez tout de même utiliser le design de Starlight.

Pour ajouter des liens d'ancrage vers des en-têtes avec une apparence équivalente aux liens d'ancrage Markdown de Starlight, vous pouvez utiliser le [composant `<AnchorHeading>`](#composant-anchorheading) dans vos pages personnalisées.

```astro
---
// src/pages/page-perso/exemple.astro
import StarlightPage from '@astrojs/starlight/components/StarlightPage.astro';
import AnchorHeading from '@astrojs/starlight/components/AnchorHeading.astro';
import CustomComponent from './CustomComponent.astro';
---

<StarlightPage frontmatter={{ title: 'Ma page personnalisée' }}>
	<p>Il s'agit d'une page personnalisée avec un composant personnalisé :</p>
	<CustomComponent />

	<AnchorHeading level="2" id="en-savoir-plus">En savoir plus</AnchorHeading>
	<p>
		<a href="https://starlight.astro.build/">
			Consulter la documentation de Starlight
		</a>
	</p>
</StarlightPage>
```

#### Composant `<StarlightPage>`

Le composant `<StarlightPage />` affiche une page complète de contenu en utilisant la mise en page et les styles de Starlight.

```astro
---
import StarlightPage from '@astrojs/starlight/components/StarlightPage.astro';
---

<StarlightPage frontmatter={{ title: 'Ma page personnalisée' }}>
	<!-- Contenu de la page personnalisée -->
</StarlightPage>
```

Le composant `<StarlightPage />` accepte les props suivantes.

##### `frontmatter`

**Obligatoire**  
**Type :** `StarlightPageFrontmatter`

Définit les [propriétés du frontmatter](/fr/reference/frontmatter/) pour cette page, similaire au frontmatter dans les pages Markdown.
La propriété [`title`](/fr/reference/frontmatter/#title-obligatoire) est obligatoire et toutes les autres propriétés sont optionnelles.

Les propriétés suivantes diffèrent du frontmatter des fichiers Markdown :

- La propriété [`slug`](/fr/reference/frontmatter/#slug) n'est pas prise en charge et est automatiquement définie en fonction de l'URL de la page personnalisée.
- L'option [`editUrl`](/fr/reference/frontmatter/#editurl) nécessite une URL pour afficher un lien d'édition.
- La propriété [`sidebar`](/fr/reference/frontmatter/#sidebar) du frontmatter permettant de personnaliser l'affichage de la page dans les [groupes de liens autogénérés](/fr/reference/configuration/#sidebar) n'est pas disponible. Les pages utilisant le composant `<StarlightPage />` ne font pas partie d'une collection et ne peuvent pas être ajoutées à un groupe de liens autogénérés.
- L'option [`draft`](/fr/reference/frontmatter/#draft) affiche uniquement une [note](/fr/reference/overrides/#draftcontentnotice) indiquant que la page est une ébauche, mais ne l'exclut pas automatiquement des déploiements en production.

##### `sidebar`

**Type :** [`SidebarItem[]`](/fr/reference/configuration/#sidebaritem)  
**Par défaut :** la barre latérale générée en fonction de la [configuration globale `sidebar`](/fr/reference/configuration/#sidebar)

Fournit une barre latérale de navigation personnalisée pour cette page.
Si elle n'est pas définie, la page utilisera la barre latérale globale par défaut.

Par exemple, la page suivante remplace la barre latérale par défaut par un lien vers la page d'accueil et un groupe de liens vers diverses autres pages personnalisées.

```astro {3-17}
<StarlightPage
	frontmatter={{ title: 'Orion' }}
	sidebar={[
		{ label: 'Accueil', link: '/' },
		{
			label: 'Constellations',
			items: [
				{ label: 'Andromède', link: '/andromède/' },
				{ label: 'Orion', link: '/orion/' },
				{
					label: 'La Petite Ourse',
					link: '/la-petite-ourse/',
					badge: 'Ébauche',
				},
			],
		},
	]}
>
	Exemple de contenu.
</StarlightPage>
```

Consultez le guide [« Barre latérale de navigation »](/fr/guides/sidebar/) pour en savoir plus sur les options disponibles pour personnaliser la barre latérale.

##### `hasSidebar`

**Type :** `boolean`  
**Par défaut :** `false` si [`frontmatter.template`](/fr/reference/frontmatter/#template) utilise `'splash'`, autrement `true`

Contrôle l'affichage ou non de la barre latérale sur cette page.

##### `headings`

**Type :** `{ depth: number; slug: string; text: string }[]`  
**Par défaut :** `[]`

Fournit un tableau de tous les en-têtes de cette page.
Starlight générera la table des matières de la page à partir de ces en-têtes s'ils sont fournis.

##### `dir`

**Type :** `'ltr' | 'rtl'`  
**Par défaut :** le sens d'écriture pour la locale actuelle

Définit le sens d’écriture pour le contenu de la page.

##### `lang`

**Type :** `string`  
**Par défaut :** la langue de la locale actuelle

Définit l'étiquette d’identification BCP-47 pour le contenu de cette page, par exemple `en`, `zh-CN`, ou `pt-BR`.

##### `isFallback`

**Type :** `boolean`  
**Par défaut :** `false`

Indique si cette page utilise un [contenu de repli](/fr/guides/i18n/#contenu-de-repli) parce qu'il n'y a pas de traduction pour la langue actuelle.

#### Composant `<AnchorHeading>`

Le composant `<AnchorHeading>` affiche un élément d'en-tête HTML avec un lien d'ancrage cliquable avec une apparence équivalente aux styles Markdown de Starlight.

```astro
---
import AnchorHeading from '@astrojs/starlight/components/AnchorHeading.astro';
---

<AnchorHeading level="2" id="sous-rubrique">Sous rubrique</AnchorHeading>
```

Il accepte les props suivantes ainsi que n'importe quel autre [attribut HTML universel valide](https://developer.mozilla.org/fr/docs/Web/HTML/Reference/Global_attributes).

##### `level`

**Obligatoire**  
**Type :** `1 | 2 | 3 | 4 | 5 | 6`

Le niveau d'en-tête à afficher.
Par exemple, `level="1"` afficherait un élément `<h1>`.

##### `id`

**Obligatoire**  
**Type :** `string`

Un identifiant unique pour cet en-tête.
Celui-ci sera utilisé comme attribut `id` de l'en-tête affiché et l'icône d'ancrage rendirigera vers celui-ci.


================================================
FILE: docs/src/content/docs/fr/guides/project-structure.mdx
================================================
---
title: Structure du projet
description: Apprenez à organiser les fichiers dans votre projet Starlight.
---

Ce guide vous montrera comment un projet Starlight est organisé et ce que font les différents fichiers de votre projet.

Les projets Starlight suivent généralement la même structure de fichiers et de répertoires que les autres projets Astro. Voir [la documentation sur la structure des projets Astro](https://docs.astro.build/fr/basics/project-structure/) pour plus de détails.

## Fichiers et répertoires

- `astro.config.mjs` — Le fichier de configuration d'Astro ; inclut l'intégration et la configuration de Starlight.
- `src/content.config.ts` — Fichier de configuration des collections de contenu ; ajoute les schémas du frontmatter de Starlight à votre projet.
- `src/content/docs/` — Fichiers de contenu. Starlight transforme chaque fichier `.md`, `.mdx` ou `.mdoc` de ce répertoire en une page de votre site.
- `src/content/i18n/` (optionnel) — Données de traduction pour prendre en charge l'[internationalisation](/fr/guides/i18n/).
- `src/` — Autre code source et fichiers (composants, styles, images, etc.) pour votre projet.
- `public/` — Ressources statiques (polices, favicon, PDF, etc.) qui ne seront pas traités par Astro.

## Exemple de contenu de projet

Un répertoire de projet Starlight peut ressembler à ceci :

import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- public/
  - favicon.svg
- src/
  - assets/
    - logo.svg
    - screenshot.jpg
  - components/
    - CustomButton.astro
    - InteractiveWidget.jsx
  - content/
    - docs/
      - guides/
        - 01-getting-started.md
        - 02-advanced.md
      - index.mdx
  - content.config.ts
- astro.config.mjs
- package.json
- tsconfig.json

</FileTree>


================================================
FILE: docs/src/content/docs/fr/guides/route-data.mdx
================================================
---
title: Données de route
description: Apprenez comment le modèle de données de page de Starlight est utilisé pour afficher vos pages et comment vous pouvez le personnaliser.
---

import { Steps } from '@astrojs/starlight/components';

Lorsque Starlight affiche une page dans votre documentation, un objet de données de route est d'abord créé pour représenter ce qui se trouve sur cette page.
Ce guide explique comment les données de route sont générées, comment les utiliser et comment vous pouvez les personnaliser pour modifier le comportement par défaut de Starlight.

Consultez la [« Référence des données de route »](/fr/reference/route-data/) pour une liste complète des propriétés disponibles.

## Qu'est-ce que les données de route?

Les données de route de Starlight sont un objet contenant toutes les informations nécessaires pour afficher une seule page.
Il inclut des informations pour la page courante ainsi que des données générées à partir de votre configuration de Starlight.

## Utilisation des données de route

Tous les composants de Starlight utilisent les données de route pour décider de ce qui doit être affiché pour chaque page.
Par exemple, la chaîne de caractères [`siteTitle`](/fr/reference/route-data/#sitetitle) est utilisée pour afficher le titre du site et le tableau [`sidebar`](/fr/reference/route-data/#sidebar) est utilisé pour afficher la barre latérale de navigation.

Vous pouvez accéder à ces données à partir de la variable globale `Astro.locals.starlightRoute` dans les composants Astro :

```astro title="exemple.astro" {2}
---
const { siteTitle } = Astro.locals.starlightRoute;
---

<p>Le titre de ce site est « {siteTitle} »</p>
```

Cela peut être utile, par exemple, lors de la mise en place de redéfinitions de composants pour personnaliser ce que vous affichez.

## Personnalisation des données de route

Les données de route de Starlight sont prêtes à l'emploi et ne nécessitent aucune configuration.
Cependant, pour des cas d'utilisation avancés, vous pourriez vouloir personnaliser les données de route pour certaines ou toutes les pages afin de modifier le rendu de votre site.

Il s'agit d'un concept similaire aux [redéfinitions de composants](/fr/guides/overriding-components/), mais au lieu de modifier la façon dont Starlight affiche vos données, vous modifiez les données que Starlight affiche.

### Quand personnaliser les données de route

Personnaliser les données de route peut être utile lorsque vous souhaitez modifier la façon dont Starlight traite vos données d'une manière qui n'est pas possible avec les options de configuration existantes.

Par exemple, vous pourriez vouloir filtrer les éléments de la barre latérale de navigation ou personnaliser les titres de certaines pages.
Ce type de modification ne nécessite pas de modifier les composants par défaut de Starlight, seulement les données transmises à ces composants.

### Comment personnaliser les données de route

Vous pouvez personnaliser les données de route en utilisant une forme spéciale de « middleware ».
C'est une fonction qui est appelée à chaque fois que Starlight affiche une page et peut modifier les valeurs contenues dans l'objet de données de route.

<Steps>

1. Créez un nouveau fichier exportant une fonction `onRequest` en utilisant l'utilitaire `defineRouteMiddleware()` de Starlight :

   ```ts
   // src/routeData.ts
   import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

   export const onRequest = defineRouteMiddleware(() => {});
   ```

2. Indiquez à Starlight où se trouve le fichier contenant votre middleware de données de route dans `astro.config.mjs` :

   ```js ins={9}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Mon ravissant site de documentation',
   			routeMiddleware: './src/routeData.ts',
   		}),
   	],
   });
   ```

3. Mettez à jour votre fonction `onRequest` pour modifier les données de route.

   Le premier argument que votre middleware recevra est [l'objet `context` d'Astro](https://docs.astro.build/fr/reference/api-reference/).
   Celui-ci contient toutes les informations concernant le rendu de la page courante, y compris l'URL actuelle et les `locals`.

   Dans cet exemple, nous allons rendre notre documentation plus passionnante en ajoutant un point d'exclamation à la fin du titre de chaque page.

   ```ts
   // src/routeData.ts
   import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

   export const onRequest = defineRouteMiddleware((context) => {
   	// Récupérer l'entrée de la collection de contenus pour cette page.
   	const { entry } = context.locals.starlightRoute;
   	// Mettre à jour le titre pour ajouter un point d'exclamation.
   	entry.data.title = entry.data.title + ' !';
   });
   ```

</Steps>

#### Plusieurs middleware de route

Starlight accepte également d'utiliser plusieurs middlewares.
Définissez `routeMiddleware` comme un tableau de chemins pour ajouter plus d'un middleware :

```js {9}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Mon site avec plusieurs middlewares',
			routeMiddleware: ['./src/middleware-un.ts', './src/middleware-deux.ts'],
		}),
	],
});
```

#### Attendre des middlewares de route ultérieurs

Pour attendre que des middlewares ultérieurs s'exécutent avant d'exécuter votre code, vous pouvez attendre la fin de l'appel à `next()` passé en deuxième argument à votre fonction middleware.
Cela peut être utile pour attendre que le middleware d'un module d'extension s'exécute avant de faire des modifications par exemple.

```ts "next" "await next();"
// src/routeData.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

export const onRequest = defineRouteMiddleware(async (context, next) => {
	// Attendre que des middlewares ultérieurs s'exécutent.
	await next();
	// Modifier les données de route.
	const { entry } = context.locals.starlightRoute;
	entry.data.title = entry.data.title + ' !';
});
```


================================================
FILE: docs/src/content/docs/fr/guides/sidebar.mdx
================================================
---
title: Barre latérale de navigation
description: Apprendre à configurer et personnaliser les liens de la barre latérale de navigation de votre site Starlight.
---

import { FileTree } from '@astrojs/starlight/components';
import SidebarPreview from '~/components/sidebar-preview.astro';

Une barre latérale bien organisée est une des clés d'une bonne documentation, car c'est l'une des principales méthodes de navigation qui sera utilisée par les utilisateurs de votre site. Starlight fournit un ensemble complet d'options pour personnaliser la structure et le contenu de votre barre latérale.

## Barre latérale par défaut

Par défaut, Starlight générera automatiquement une barre latérale basée sur la structure du système de fichiers de votre documentation, en utilisant la propriété `title` de chaque fichier comme entrée de la barre latérale.

Par exemple, pour la structure de fichiers suivante :

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - andromede.md
        - orion.md
      - etoiles/
        - betelgeuse.md

</FileTree>

La barre latérale suivante sera automatiquement générée :

<SidebarPreview
	config={[
		{
			label: 'constellations',
			items: [
				{ label: 'Andromède', link: '' },
				{ label: 'Orion', link: '' },
			],
		},
		{
			label: 'etoiles',
			items: [{ label: 'Bételgeuse', link: '' }],
		},
	]}
/>

Pour en savoir plus sur les barres latérales générées automatiquement, consultez la section sur les [groupes générés automatiquement](#groupes-générés-automatiquement).

## Ajouter des liens et des groupes de liens

Pour configurer les liens et groupes de liens (dans un en-tête rétractable) de votre barre latérale, utilisez la propriété [`starlight.sidebar`](/fr/reference/configuration/#sidebar) dans le fichier `astro.config.mjs`.

En combinant les liens et les groupes, vous pouvez créer une grande variété de structures de barre latérale.

### Liens internes

Ajoutez un lien vers une page située dans `src/content/docs/` en utilisant un objet avec la propriété `slug`.
Le titre de la page liée sera utilisé comme étiquette par défaut.

Par exemple, avec la configuration suivante :

```js "slug:"
starlight({
	sidebar: [
		{ slug: 'constellations/andromede' },
		{ slug: 'constellations/orion' },
	],
});
```

Et la structure de fichiers suivante :

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - andromede.md
        - orion.md

</FileTree>

La barre latérale suivante sera générée :

<SidebarPreview
	config={[
		{ label: 'Andromède', link: '' },
		{ label: 'Orion', link: '' },
	]}
/>

Pour personnaliser les valeurs inférées du frontmatter de la page liée, vous pouvez ajouter les propriétés `label`, [`translations`](#internationalisation) et [`attrs`](#attributs-html-personnalisés).

Consultez la section [« Personnaliser les liens générés automatiquement dans le frontmatter »](#personnaliser-les-liens-générés-automatiquement-dans-le-frontmatter) pour plus de détails sur comment contrôler l'apparence de la barre latérale à partir du frontmatter de la page.

#### Syntaxe simplifiée pour les liens internes

Les liens internes peuvent également être spécifiés en utilisant uniquement une chaîne de caractères comme raccourci pour le slug de la page.

Par exemple, la configuration suivante est équivalente à la configuration ci-dessus, qui utilisait `slug` :

```js "slug:"
starlight({
	sidebar: ['constellations/andromede', 'constellations/orion'],
});
```

### Autres liens

Ajoutez un lien vers une page externe ou ne faisant pas partie de votre documentation en utilisant un objet avec les propriétés `label` et `link`.

```js "label:" "link:"
starlight({
	sidebar: [
		// Un lien vers une page ne faisant pas partie de la documentation.
		{ label: 'Boutique de météores', link: '/boutique/' },
		// Un lien externe vers le site de la NASA.
		{ label: 'NASA', link: 'https://www.nasa.gov/' },
	],
});
```

La configuration ci-dessus génère la barre latérale suivante :

<SidebarPreview
	config={[
		{ label: 'Boutique de météores', link: '' },
		{ label: 'NASA', link: 'https://www.nasa.gov/' },
	]}
/>

### Groupes

Vous pouvez donner de la structure à votre barre latérale en regroupant des liens connexes sous un en-tête rétractable.
Les groupes peuvent contenir à la fois des liens et d'autres sous-groupes.

Ajoutez un groupe en utilisant un objet avec les propriétés `label` et `items`.
Le `label` sera utilisé comme en-tête pour le groupe.
Ajoutez des liens ou des sous-groupes au tableau `items`.

```js /^\s*(label:|items:)/
starlight({
	sidebar: [
		// Un groupe de liens avec le label "Constellations".
		{
			label: 'Constellations',
			items: [
				'constellations/carene',
				'constellations/centaure',
				// Un groupe de liens imbriqué pour les constellations saisonnières.
				{
					label: 'Saisonnières',
					items: [
						'constellations/andromede',
						'constellations/orion',
						'constellations/petite-ourse',
					],
				},
			],
		},
	],
});
```

La configuration ci-dessus génère la barre latérale suivante :

<SidebarPreview
	config={[
		{
			label: 'Constellations',
			items: [
				{ label: 'Carène', link: '' },
				{ label: 'Centaure', link: '' },
				{
					label: 'Saisonnières',
					items: [
						{ label: 'Andromède', link: '' },
						{ label: 'Orion', link: '' },
						{ label: 'Petite Ourse', link: '' },
					],
				},
			],
		},
	]}
/>

### Groupes générés automatiquement

Starlight peut générer automatiquement un groupe dans votre barre latérale en fonction d'un répertoire de votre documentation.
Cela est utile lorsque vous ne souhaitez pas entrer manuellement chaque élément de la barre latérale dans un groupe.

Par défaut, les pages sont triées par ordre alphabétique selon le [`slug`](/fr/reference/route-data/#slug) du fichier.

Ajoutez un groupe généré automatiquement en utilisant un objet avec les propriétés `label` et `autogenerate`. La configuration de `autogenerate` doit spécifier le répertoire à utiliser pour les entrées de la barre latérale avec la propriété `directory`. Par exemple, avec la configuration suivante :

```js "label:" "autogenerate:"
starlight({
	sidebar: [
		{
			label: 'Constellations',
			// Génère automatiquement un groupe de liens pour le répertoire "constellations".
			autogenerate: { directory: 'constellations' },
		},
	],
});
```

Et la structure de fichiers suivante :

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - carene.md
        - centaure.md
        - saisonnieres/
          - andromede.md

</FileTree>

La barre latérale suivante sera générée :

<SidebarPreview
	config={[
		{
			label: 'Constellations',
			items: [
				{ label: 'Carène', link: '' },
				{ label: 'Centaure', link: '' },
				{
					label: 'saisonnieres',
					items: [{ label: 'Andromède', link: '' }],
				},
			],
		},
	]}
/>

## Personnaliser les liens générés automatiquement dans le frontmatter

Utilisez le [champ `sidebar` du frontmatter](/fr/reference/frontmatter/#sidebar) dans différentes pages pour personnaliser les liens générés automatiquement.

Les options du frontmatter pour la barre latérale vous permettent de définir une [étiquette personnalisée](/fr/reference/frontmatter/#label), d'utiliser des [attributs personnalisés](/fr/reference/frontmatter/#attrs), d'ajouter un [badge](/fr/reference/frontmatter/#badge) à un lien, de [masquer](/fr/reference/frontmatter/#hidden) un lien de la barre latérale, ou de définir une [pondération de tri personnalisée](/fr/reference/frontmatter/#order).

```md "sidebar:"
---
# src/content/docs/exemple.md
title: Ma page
sidebar:
  # Définit une étiquette personnalisée pour le lien dans la barre latérale
  label: Étiquette personnalisée
  # Définit un ordre personnalisé pour le lien
  # (les nombres plus petits sont affichés plus haut)
  order: 2
  # Ajoute un badge au lien
  badge:
    text: Nouveau
    variant: tip
---
```

Un groupe généré automatiquement incluant une page avec le frontmatter ci-dessus générera la barre latérale suivante :

<SidebarPreview
	config={[
		{
			label: 'Guides',
			items: [
				{ label: 'Une page', link: '' },
				{
					label: 'Étiquette personnalisée',
					link: '',
					badge: { text: 'Nouveau', variant: 'tip' },
				},
				{ label: 'Une autre page', link: '' },
			],
		},
	]}
/>

:::note
La configuration du frontmatter `sidebar` est seulement utilisée pour les liens dans des groupes générés automatiquement et les liens de documentation définis avec la propriété `slug`.
Elle ne s'applique pas aux liens définis avec la propriété `link`.
:::

## Badges

Les liens, groupes et groupes générés automatiquement peuvent inclure une propriété `badge` pour afficher un badge à côté de leurs étiquettes.

```js {9,16}
starlight({
	sidebar: [
		{
			label: 'Étoiles',
			items: [
				// Un lien avec un badge "Supergéante".
				{
					slug: 'etoiles/persei',
					badge: 'Supergéante',
				},
			],
		},
		// Un groupe généré automatiquement avec un badge "Obsolète".
		{
			label: 'Lunes',
			badge: 'Obsolète',
			autogenerate: { directory: 'lunes' },
		},
	],
});
```

La configuration ci-dessus génère la barre latérale suivante :

<SidebarPreview
	config={[
		{
			label: 'Étoiles',
			items: [
				{
					label: 'Persei',
					link: '',
					badge: { text: 'Supergéante', variant: 'default' },
				},
			],
		},
		{
			label: 'Lunes',
			badge: { text: 'Obsolète', variant: 'default' },
			items: [
				{
					label: 'Io',
					link: '',
				},
				{
					label: 'Europe',
					link: '',
				},
				{
					label: 'Ganymède',
					link: '',
				},
			],
		},
	]}
/>

### Variantes de badges et style personnalisé

Personnalisez le style du badge en utilisant un objet avec les propriétés `text`, `variant`, et `class`.

La propriété `text` représente le contenu à afficher (par exemple, "Nouveau").
Par défaut, le badge utilise la couleur d'accentuation de votre site. Pour utiliser un style de badge intégré, définissez la propriété `variant` à l'une des valeurs suivantes : `note`, `tip`, `danger`, `caution` ou `success`.

Facultativement, vous pouvez créer un style de badge personnalisé en définissant la propriété `class` à un nom de classe CSS.

```js {9}
starlight({
	sidebar: [
		{
			label: 'Étoiles',
			items: [
				// Un lien avec un badge "Ébauche" jaune.
				{
					slug: 'etoiles/sirius',
					badge: { text: 'Ébauche', variant: 'caution' },
				},
			],
		},
	],
});
```

La configuration ci-dessus génère la barre latérale suivante :

<SidebarPreview
	config={[
		{
			label: 'Étoiles',
			items: [
				{
					label: 'Sirius',
					link: '',
					badge: { text: 'Ébauche', variant: 'caution' },
				},
			],
		},
	]}
/>

En savoir plus sur [l'utilisation et la personnalisation des badges](/fr/components/badges/#utilisation).

## Attributs HTML personnalisés

Les liens peuvent aussi inclure une propriété `attrs` pour ajouter des attributs HTML personnalisés à l'élément du lien.

Dans l'exemple suivant, `attrs` est utilisé pour ajouter un attribut `target="_blank"`, afin que le lien s'ouvre dans un nouvel onglet, et pour appliquer un attribut `style` personnalisé pour mettre en italique l'étiquette du lien :

```js {10}
starlight({
	sidebar: [
		{
			label: 'Ressources',
			items: [
				// Un lien externe vers le site de la NASA s'ouvrant dans un nouvel onglet.
				{
					label: 'NASA',
					link: 'https://www.nasa.gov/',
					attrs: { target: '_blank', style: 'font-style: italic' },
				},
			],
		},
	],
});
```

La configuration ci-dessus génère la barre latérale suivante :

<SidebarPreview
	config={[
		{
			label: 'Ressources',
			items: [
				{
					label: 'NASA',
					link: 'https://www.nasa.gov/',
					attrs: {
						target: '_blank',
						style: 'font-style: italic',
					},
				},
			],
		},
	]}
/>

### Attributs HTML personnalisés pour les liens générés automatiquement

Personnalisez les attributs HTML de tous les liens dans des [groupes générés automatiquement](#groupes-générés-automatiquement) en définissant la propriété `attrs` dans la configuration `autogenerate`.
Différentes pages peuvent individuellement spécifier des attributs personnalisés en utilisant le [champ `sidebar.attrs` du frontmatter](/fr/reference/frontmatter/#attrs) qui sera fusionné avec la configuration `autogenerate.attrs`.

Par exemple, avec la configuration suivante :

```js {9}
starlight({
	sidebar: [
		{
			label: 'Constellations',
			autogenerate: {
				// Génère automatiquement un groupe de liens pour le répertoire "constellations".
				directory: 'constellations',
				// Met en italique tous les labels de liens dans ce groupe.
				attrs: { style: 'font-style: italic' },
			},
		},
	],
});
```

Et la structure de fichiers suivante :

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - carene.md
        - centaure.md
        - saisonnieres/
          - andromede.md

</FileTree>

La barre latérale suivante sera générée avec tous les liens générés automatiquement en italique :

<SidebarPreview
	config={[
		{
			label: 'Constellations',
			items: [
				{ label: 'Carène', link: '', attrs: { style: 'font-style: italic' } },
				{
					label: 'Centaure',
					link: '',
					attrs: { style: 'font-style: italic' },
				},
				{
					label: 'saisonnieres',
					items: [
						{
							label: 'Andromède',
							link: '',
							attrs: { style: 'font-style: italic' },
						},
					],
				},
			],
		},
	]}
/>

## Internationalisation

Utilisez la propriété `translations` sur les liens et les groupes pour traduire l'étiquette du lien ou du groupe pour chaque langue prise en charge en spécifiant une étiquette d'identification de langue [BCP-47](https://www.w3.org/International/questions/qa-choosing-language-tags), par exemple `"en"`, `"ar"` ou `"zh-CN"`, comme clé et l'étiquette traduite comme valeur.
La propriété `label` sera utilisée pour la langue par défaut et pour les langues sans traduction.

```js {5-7,11-13,18-20}
starlight({
	sidebar: [
		{
			label: 'Constellations',
			translations: {
				'pt-BR': 'Constelações',
			},
			items: [
				{
					label: 'Andromède',
					translations: {
						'pt-BR': 'Andrômeda',
					},
					slug: 'constellations/andromede',
				},
				{
					label: 'Scorpion',
					translations: {
						'pt-BR': 'Escorpião',
					},
					slug: 'constellations/scorpion',
				},
			],
		},
	],
});
```

Parcourir la documentation en portugais brésilien générera la barre latérale suivante :

<SidebarPreview
	config={[
		{
			label: 'Constelação',
			items: [
				{ label: 'Andrômeda', link: '' },
				{ label: 'Escorpião', link: '' },
			],
		},
	]}
/>

### Internationalisation avec des liens internes

Les [liens internes](#liens-internes) utiliseront automatiquement les titres de page traduits depuis le frontmatter du contenu par défaut :

```js {9-10}
starlight({
	sidebar: [
		{
			label: 'Constellations',
			translations: {
				'pt-BR': 'Constelações',
			},
			items: [
				{ slug: 'constellations/andromede' },
				{ slug: 'constellations/scorpion' },
			],
		},
	],
});
```

Parcourir la documentation en portugais brésilien générera la barre latérale suivante :

<SidebarPreview
	config={[
		{
			label: 'Constelações',
			items: [
				{ label: 'Andrômeda', link: '' },
				{ label: 'Escorpião', link: '' },
			],
		},
	]}
/>

Pour les sites multilingues, la valeur de la propriété `slug` n'inclut pas la portion de langue dans l'URL.
Par exemple, si vous avez des pages à `en/intro` et `pt-br/intro`, le slug est `intro` lors de la configuration de la barre latérale.

### Internationalisation avec des badges

Pour les [badges](#badges), la propriété `text` peut être une chaîne de caractères, ou pour les sites multilingues, un objet avec des valeurs pour chaque langue différente.
Lors de l'utilisation de la forme d'objet, les clés doivent être des étiquettes d'identification de langue [BCP-47](https://www.w3.org/International/questions/qa-choosing-language-tags) (par exemple, `en`, `ar` ou `zh-CN`) :

```js {11-16}
starlight({
	sidebar: [
		{
			label: 'Constellations',
			translations: {
				'pt-BR': 'Constelações',
			},
			items: [
				{
					slug: 'constellations/andromeda',
					badge: {
						text: {
							fr: 'Nouveau',
							'pt-BR': 'Novo',
						},
					},
				},
			],
		},
	],
});
```

Parcourir la documentation en portugais brésilien générera la barre latérale suivante :

<SidebarPreview
	config={[
		{
			label: 'Constelações',
			items: [
				{
					label: 'Andrômeda',
					link: '',
					badge: { text: 'Novo', variant: 'default' },
				},
			],
		},
	]}
/>

## Groupes rétractables

Les groupes de liens peuvent être rétractés par défaut en définissant la propriété `collapsed` à `true`.

```js {5-6}
starlight({
	sidebar: [
		{
			label: 'Constellations',
			// Rétracte le groupe par défaut.
			collapsed: true,
			items: ['constellations/andromede', 'constellations/orion'],
		},
	],
});
```

La configuration ci-dessus génère la barre latérale suivante :

<SidebarPreview
	config={[
		{
			label: 'Constellations',
			collapsed: true,
			items: [
				{ label: 'Andromède', link: '' },
				{ label: 'Orion', link: '' },
			],
		},
	]}
/>

Les [groupes générés automatiquement](#groupes-générés-automatiquement) respectent la valeur `collapsed` de leur groupe parent :

```js {5-7}
starlight({
	sidebar: [
		{
			label: 'Constellations',
			// Rétracte le groupe et ses sous-groupes générés automatiquement
			// par défaut.
			collapsed: true,
			autogenerate: { directory: 'constellations' },
		},
	],
});
```

La configuration ci-dessus génère la barre latérale suivante :

<SidebarPreview
	config={[
		{
			label: 'Constellations',
			collapsed: true,
			items: [
				{ label: 'Carène', link: '' },
				{ label: 'Centaure', link: '' },
				{
					label: 'saisonnieres',
					collapsed: true,
					items: [{ label: 'Andromède', link: '' }],
				},
			],
		},
	]}
/>

Ce comportement peut être remplacé en définissant la propriété `autogenerate.collapsed`.

```js {5-7} "collapsed: true"
starlight({
	sidebar: [
		{
			label: 'Constellations',
			// Ne rétracte pas le groupe "Constellations" mais rétracte ses
			// sous-groupes générés automatiquement.
			collapsed: false,
			autogenerate: { directory: 'constellations', collapsed: true },
		},
	],
});
```

La configuration ci-dessus génère la barre latérale suivante :

<SidebarPreview
	config={[
		{
			label: 'Constellations',
			items: [
				{ label: 'Carène', link: '' },
				{ label: 'Centaure', link: '' },
				{
					label: 'saisonnieres',
					collapsed: true,
					items: [{ label: 'Andromède', link: '' }],
				},
			],
		},
	]}
/>


================================================
FILE: docs/src/content/docs/fr/guides/site-search.mdx
================================================
---
title: Recherche
description: Découvrez les fonctionnalités de recherche intégrées à Starlight et comment les personnaliser.
tableOfContents:
  maxHeadingLevel: 4
---

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

Par défaut, les sites utilisant Starlight incluent une recherche plein texte utilisant [Pagefind](https://pagefind.app/), un outil de recherche rapide et à faible bande passante pour sites statiques.

Aucune configuration n'est requise pour activer la recherche. Créez et déployez votre site, puis utilisez la barre de recherche dans l'en-tête du site pour trouver du contenu.

## Cacher du contenu dans les résultats de recherche

### Exclure une page

Pour exclure une page de votre index de recherche, ajoutez [`pagefind: false`](/fr/reference/frontmatter/#pagefind) au frontmatter de la page :

```md title="src/content/docs/sans-recherche.md" ins={3}
---
title: Contenu à cacher de la recherche
pagefind: false
---
```

### Exclure une partie d'une page

Pagefind ignorera le contenu à l'intérieur d'un élément avec l'attribut [`data-pagefind-ignore`](https://pagefind.app/docs/indexing/#removing-individual-elements-from-the-index).

Dans l'exemple suivant, le premier paragraphe s'affichera dans les résultats de recherche, mais le contenu de la `<div>` ne s'affichera pas :

```md title="src/content/docs/resultats-partiels.md" ins="data-pagefind-ignore"
---
title: Page partiellement indexée
---

Ce texte sera trouvable via la recherche.

<div data-pagefind-ignore>

Ce texte sera caché de la recherche.

</div>
```

## Système de recherche alternatif

### Algolia DocSearch

Si vous avez accès au [programme DocSearch d'Algolia](https://docsearch.algolia.com/) et que vous souhaitez l'utiliser à la place de Pagefind, vous pouvez utiliser le module d'extension officiel DocSearch de Starlight.

<Steps>

1. Installez `@astrojs/starlight-docsearch` :

   <Tabs syncKey="pkg">

   <TabItem label="npm">

   ```sh
   npm install @astrojs/starlight-docsearch
   ```

   </TabItem>

   <TabItem label="pnpm">

   ```sh
   pnpm add @astrojs/starlight-docsearch
   ```

   </TabItem>

   <TabItem label="Yarn">

   ```sh
   yarn add @astrojs/starlight-docsearch
   ```

   </TabItem>

   </Tabs>

2. Ajouter DocSearch à votre configuration [`plugins`](/fr/reference/configuration/#plugins) de Starlight dans le fichier `astro.config.mjs` et spécifiez vos `appId`, `apiKey` et `indexName` d'Algolia :

   ```js ins={4,10-16}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';
   import starlightDocSearch from '@astrojs/starlight-docsearch';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Site avec DocSearch',
   			plugins: [
   				starlightDocSearch({
   					appId: 'VOTRE_APP_ID',
   					apiKey: 'VOTRE_CLE_API_DE_RECHERCHE',
   					indexName: 'VOTRE_NOM_D_INDEX',
   				}),
   			],
   		}),
   	],
   });
   ```

</Steps>

Avec cette configuration mise à jour, la barre de recherche de votre site ouvrira désormais une modale Algolia au lieu de celle par défaut.

#### Configuration de DocSearch

Le module d’extension DocSearch de Starlight prend en charge la personnalisation du composant DocSearch avec les options supplémentaires suivantes spécifiées dans la configuration du module d’extension :

- `maxRecentSearches`: Limite le nombre de résultats affichés pour chaque groupe de recherche. La valeur par défaut est `5`.
- `disableUserPersonalization`: Empêche DocSearch de sauvegarder les recherches récentes et favorites d'un utilisateur localement. La valeur par défaut est `false`.
- `insights`: Active le module d'extension Algolia Insights et envoie les événements liés à toute recherche à votre index DocSearch. La valeur par défaut est `false`.
- `searchParameters`: Un objet personnalisant les [paramètres de recherche Algolia](https://www.algolia.com/doc/api-reference/search-api-parameters/).

##### Options supplémentaires de DocSearch

Un fichier de configuration distinct est requis pour passer des options de type fonction comme `transformItems()` ou `resultsFooterComponent()` au composant DocSearch.

<Steps>

1. Créez un fichier TypeScript exportant votre configuration DocSearch.

   ```ts
   // src/config/docsearch.ts
   import type { DocSearchClientOptions } from '@astrojs/starlight-docsearch';

   export default {
   	appId: 'VOTRE_APP_ID',
   	apiKey: 'VOTRE_CLE_API_DE_RECHERCHE',
   	indexName: 'VOTRE_NOM_D_INDEX',
   	getMissingResultsUrl({ query }) {
   		return `https://github.com/algolia/docsearch/issues/new?title=${query}`;
   	},
   	// ...
   } satisfies DocSearchClientOptions;
   ```

2. Utilisez le chemin vers votre fichier de configuration avec le module d’extension DocSearch de Starlight dans `astro.config.mjs`.

   ```js {11-13}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';
   import starlightDocSearch from '@astrojs/starlight-docsearch';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Site avec DocSearch',
   			plugins: [
   				starlightDocSearch({
   					clientOptionsModule: './src/config/docsearch.ts',
   				}),
   			],
   		}),
   	],
   });
   ```

</Steps>

Consultez la [référence de l'API JavaScript client de DocSearch](https://docsearch.algolia.com/docs/api/) pour obtenir toutes les options prises en charge.

#### Traduire l'interface utilisateur de DocSearch

DocSearch fournit seulement des chaînes de l'interface utilisateur en anglais par défaut.
Ajoutez des traductions de l'interface utilisateur de la modale pour votre langue en utilisant le [système d'internationalisation](/fr/guides/i18n/#traduire-linterface-utilisateur-de-starlight) intégré à Starlight.

<Steps>

1. Étendez la définition de la collection de contenus `i18n` de Starlight avec le schéma DocSearch dans `src/content/config.ts` :

   ```js ins={5} ins=/{ extend: .+ }/
   // src/content.config.ts
   import { defineCollection } from 'astro:content';
   import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
   import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';
   import { docSearchI18nSchema } from '@astrojs/starlight-docsearch/schema';

   export const collections = {
   	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
   	i18n: defineCollection({
   		loader: i18nLoader(),
   		schema: i18nSchema({ extend: docSearchI18nSchema() }),
   	}),
   };
   ```

2. Ajoutez des traductions à vos fichiers JSON dans `src/content/i18n/`.

   Voici les valeurs par défaut en anglais utilisées par DocSearch :

   ```json title="src/content/i18n/en.json"
   {
   	"docsearch.searchBox.resetButtonTitle": "Clear the query",
   	"docsearch.searchBox.resetButtonAriaLabel": "Clear the query",
   	"docsearch.searchBox.cancelButtonText": "Cancel",
   	"docsearch.searchBox.cancelButtonAriaLabel": "Cancel",
   	"docsearch.searchBox.searchInputLabel": "Search",

   	"docsearch.startScreen.recentSearchesTitle": "Recent",
   	"docsearch.startScreen.noRecentSearchesText": "No recent searches",
   	"docsearch.startScreen.saveRecentSearchButtonTitle": "Save this search",
   	"docsearch.startScreen.removeRecentSearchButtonTitle": "Remove this search from history",
   	"docsearch.startScreen.favoriteSearchesTitle": "Favorite",
   	"docsearch.startScreen.removeFavoriteSearchButtonTitle": "Remove this search from favorites",

   	"docsearch.errorScreen.titleText": "Unable to fetch results",
   	"docsearch.errorScreen.helpText": "You might want to check your network connection.",

   	"docsearch.footer.selectText": "to select",
   	"docsearch.footer.selectKeyAriaLabel": "Enter key",
   	"docsearch.footer.navigateText": "to navigate",
   	"docsearch.footer.navigateUpKeyAriaLabel": "Arrow up",
   	"docsearch.footer.navigateDownKeyAriaLabel": "Arrow down",
   	"docsearch.footer.closeText": "to close",
   	"docsearch.footer.closeKeyAriaLabel": "Escape key",
   	"docsearch.footer.searchByText": "Search by",

   	"docsearch.noResultsScreen.noResultsText": "No results for",
   	"docsearch.noResultsScreen.suggestedQueryText": "Try searching for",
   	"docsearch.noResultsScreen.reportMissingResultsText": "Believe this query should return results?",
   	"docsearch.noResultsScreen.reportMissingResultsLinkText": "Let us know."
   }
   ```

</Steps>

### Systèmes de recherche communautaires

Les [modules d'extension communautaires](/fr/resources/plugins/#modules-dextension-communautaires) peuvent également fournir des alternatives au système de recherche Pagefind intégré à Starlight.

#### Typesense DocSearch

Le module d'extension communautaire [Starlight DocSearch Typesense](https://starlight-docsearch.typesense.org/) fournit une alternative open-source et auto-hébergeable qui intègre l'interface [DocSearch](https://github.com/typesense/typesense-docsearch.js) avec un backend [Typesense](https://typesense.org/).

Consultez le [guide de démarrage](https://starlight-docsearch.typesense.org/getting-started/) dans la documentation de Starlight DocSearch Typesense pour apprendre comment l’utiliser dans votre projet.


================================================
FILE: docs/src/content/docs/fr/index.mdx
================================================
---
title: Starlight 🌟 Construire des sites de documentation avec Astro
head:
  - tag: title
    content: Starlight 🌟 Construire des sites de documentation avec Astro
description: Starlight vous aide à créer de magnifiques sites web de documentation très performants avec Astro.
template: splash
editUrl: false
lastUpdated: false
hero:
  title: Faites briller vos documentations avec Starlight
  tagline: Tout ce dont vous avez besoin pour créer un excellent site web de documentation. Rapide, accessible et facile à utiliser.
  image:
    file: ~/assets/hero-star.webp
  actions:
    - text: Mise en route
      icon: right-arrow
      link: /fr/getting-started/
    - text: Voir sur GitHub
      icon: external
      variant: minimal
      link: https://github.com/withastro/starlight
---

import { CardGrid, Card } from '@astrojs/starlight/components';
import AboutAstro from '~/components/about-astro.astro';
import TestimonialGrid from '~/components/testimonial-grid.astro';
import Testimonial from '~/components/testimonial.astro';

<CardGrid stagger>
	<Card title="Une documentation qui enchante" icon="open-book">
		Comprend : Navigation dans le site, recherche, internationalisation,
		référencement naturel, typographie facile à lire, coloration syntaxique,
		mode sombre, etc.
	</Card>
	<Card title="Propulsé par Astro" icon="rocket">
		Exploitez toute la puissance et les performances d'Astro. Étendez Starlight
		avec vos intégrations et bibliothèques Astro préférées.
	</Card>
	<Card title="Markdown, Markdoc et MDX" icon="document">
		Utilisez votre langage de balisage préféré. Starlight vous offre une
		validation du frontmatter intégrée avec la sûreté du typage TypeScript.
	</Card>
	<Card
		title="Utilisez vos propres composants d'interface utilisateur"
		icon="puzzle"
	>
		Starlight est une solution de documentation complète et indépendante du
		framework utilisé. Étendez-la avec React, Vue, Svelte, Solid et plus encore.
	</Card>
</CardGrid>

<TestimonialGrid title="Ce que disent les gens">
	<Testimonial
		name="Rachel"
		handle="rachelnabors"
		cite="https://twitter.com/astrodotbuild/status/1724934718745915558"
	>
		L'équipe d'Astro a fait ÉVOLUER la façon dont les documentations peuvent être réalisées et vous pouvez tout obtenir immédiatement avec leur projet Starlight.
	</Testimonial>
	<Testimonial
		name="Flavio"
		handle="flaviocopes"
		cite="https://twitter.com/flaviocopes/status/1738237658717905108"
	>
		Le kit de démarrage officiel d'Astro Starlight est un outil vraiment incroyable pour créer un site web de documentation
	</Testimonial>
	<Testimonial
		name="Tomek"
		handle="sulco"
		cite="https://twitter.com/sulco/status/1735610348730802342"
	>
		Starlight est notre meilleur exemple d'une bonne expérience de développement (DX) : la rapidité, la facilité et l'attention portée aux détails sont une source d'inspiration.
		Il s'occupe de la partie technique et de l'apparence,
		pour que vous puissiez vous concentrer sur votre contenu 👏

    	L'équipe de StackBlitz l'adore !
    </Testimonial>
    <Testimonial
    	name="Roberto"
    	handle="RmeetsH"
    	cite="https://twitter.com/RmeetsH/status/1735783992018760090"
    >
    	Starlight a changé la donne pour moi, me permettant de me concentrer sur la création de contenu.

    	Sa conception intuitive permet non seulement de simplifier ma manière de travailler, mais aussi de réduire le temps d'intégration pour les développeurs de logiciels libres.

    </Testimonial>
    <Testimonial
    	name="Joel"
    	handle="jhooks"
    	cite="https://twitter.com/jhooks/status/1727405160547418405"
    >
    	J'ai passé un peu plus de temps avec Starlight pour la documentation de Course Builder et cela s'est très bien passé jusqu'à présent. Il y a beaucoup de détails agréables et je peux me concentrer sur l'écriture en Markdown et non sur l'architecture du site.
    </Testimonial>
    <Testimonial
    	name="Rick"
    	handle="rick_viscomi"
    	cite="https://twitter.com/rick_viscomi/status/1665867447910510593"
    >
    	J'ai commencé à jouer avec Starlight. Je dois dire que je suis très impressionné par ses performances.

    	💯💯💯💯

    </Testimonial>
    <Testimonial
    	name="Nicolas"
    	handle="beaussan"
    	cite="https://twitter.com/beaussan/status/1735625189583466893"
    >
    	Starlight est la meilleure façon de démarrer une documentation, entre la puissance et la rapidité d'Astro et les outils de Starlight, c'est une combinaison parfaite.

    	C'est mon outil de prédilection depuis un certain temps, et je continue à l'aimer !

    </Testimonial>
    <Testimonial
    	name="Sylwia"
    	handle="SylwiaVargas"
    	cite="https://x.com/SylwiaVargas/status/1726556825741578286"
    >
    	J'ai utilisé Starlight à mon dernier emploi et je l'ai adoré. Excellents composants, conception intuitive
    	et une communauté super réactive (chaque fois que quelqu'un avait besoin de quelque chose, ils le publiaient rapidement ou proposaient une alternative).
    	Une expérience très agréable.
    </Testimonial>
    <Testimonial
    	name="Lou Cyx"
    	handle="loucyx"
    	cite="https://elk.zone/m.webtoo.ls/@loucyx@mastodon.social/111587380021362284"
    >
    	La documentation de mon site monorepo est plus belle que jamais grâce à Starlight. C'est extrêmement facile à utiliser sans perdre toute la puissance d'Astro. Merci d'y avoir travaillé !
    </Testimonial>
    <Testimonial
    	name="BowTiedWebReaper"
    	handle="BowTiedWebReapr"
    	cite="https://twitter.com/BowTiedWebReapr/status/1735633399501697517"
    >
    	Starlight est mon outil de référence pour la documentation. Il m'a permis d'ajouter facilement une documentation à mon site web Astro existant, au lieu d'avoir besoin d'un sous-domaine pour utiliser un autre outil.
    </Testimonial>
    <Testimonial
    	name="Jeff"
    	handle="J_Everhart383"
    	cite="https://twitter.com/J_Everhart383/status/1691900590048292908"
    >
    	J'ai reconstruit la documentation de la plateforme WPEngine Atlas. Croyez-moi quand je dis que Starlight a tout ce qu'il faut pour faire une plateforme de documentation 3 étoiles 🙌
    </Testimonial>
    <Testimonial
    	name="Chloe"
    	handle="solelychloe"
    	cite="https://twitter.com/solelychloe/status/1695115277602628082"
    >
    	Essayez Starlight !

    	Je l'utilise pour quelques-uns de mes sites et il est excellent.

    </Testimonial>

</TestimonialGrid>

<AboutAstro title="Proposé par">
	Astro est un framework web tout-en-un conçu pour la rapidité.
	Extrayez votre contenu de n'importe où et déployez-le partout, le tout alimenté par vos composants et bibliothèques d'interface utilisateur préférés.

[Découvrez Astro](https://astro.build/)

</AboutAstro>


================================================
FILE: docs/src/content/docs/fr/manual-setup.mdx
================================================
---
title: Installation manuelle
description: Apprendre à configurer Starlight manuellement pour l'ajouter à un projet Astro existant.
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

La façon la plus rapide de créer un nouveau site Starlight est d'utiliser `create astro` comme indiqué dans le [guide de démarrage](/fr/getting-started/#créer-un-nouveau-projet).
Si vous voulez ajouter Starlight à un projet Astro existant, ce guide vous expliquera comment faire.

## Configurer Starlight

Pour suivre ce guide, vous aurez besoin d'un projet Astro existant.

### Ajouter l'intégration Starlight

Starlight est une [intégration Astro](https://docs.astro.build/fr/guides/integrations-guide/). Ajoutez-la à votre site en exécutant la commande `astro add` dans le répertoire racine de votre projet :

<Tabs syncKey="pkg">
    <TabItem label="npm">
        ```sh
        npx astro add starlight
        ```

    </TabItem>
    <TabItem label="pnpm">
        ```sh
        pnpm astro add starlight
        ```
    </TabItem>
    <TabItem label="Yarn">
        ```sh
        yarn astro add starlight
        ```
    </TabItem>

</Tabs>

Cela installera les dépendances requises et ajoutera Starlight au tableau `integrations` dans votre fichier des configuration Astro.

### Configurer l'intégration

L'intégration Starlight est configurée dans votre fichier `astro.config.mjs`.

Ajoutez un titre avec la propriété `title` pour commencer :

```js ins={8}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Mon ravissant site de documentation',
		}),
	],
});
```

Retrouvez toutes les options disponibles dans la [référence de configuration Starlight](/fr/reference/configuration/).

### Configurer les collections de contenu

Starlight s'appuie sur les [collections de contenu d'Astro](https://docs.astro.build/fr/guides/content-collections/), qui sont configurées dans le fichier `src/content.config.ts`.

Créez ou mettez à jour le fichier de configuration du contenu, en ajoutant une collection `docs` qui utilise [`docsLoader`](/fr/reference/configuration/#docsloader) et [`docsSchema`](/fr/reference/configuration/#docsschema) de Starlight :

```js ins={3-4,7}
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
};
```

Starlight est également compatible avec [l'option `legacy.collections`](https://docs.astro.build/fr/reference/legacy-flags/) où les collections sont gérées en utilisant l'implémentation de collections de contenu héritée.
Celà est utile si vous avez un projet Astro existant et que vous ne pouvez pas apporter de modifications aux collections pour utiliser un chargeur.

### Ajouter du contenu

Starlight est maintenant configuré et il est temps d'ajouter du contenu !

Créez un repetoire `src/content/docs/` et commencez par ajouter un fichier `index.md`.
Ce sera la page d'accueil de votre nouveau site :

```md
---
# src/content/docs/index.md
title: Ma documentation
description: En savoir plus sur mon projet dans ce site de documentation construit avec Starlight.
---

Bienvenue dans mon projet !
```

Starlight utilise une stratégie de routage basée sur les fichiers, ce qui signifie que chaque fichier Markdown, MDX ou Markdoc dans `src/content/docs/` deviendra une page de votre site. Les métadonnées du frontmatter (les champs `title` et `description` dans l'exemple ci-dessus) peuvent modifier la façon dont chaque page est affichée.
Retrouvez toutes les options disponibles dans la [référence du frontmatter](/fr/reference/frontmatter/).

## Astuce pour les sites existants

Si vous avez un projet d'Astro existant, vous pouvez utiliser Starlight pour ajouter rapidement une section de documentation à votre site.

### Utiliser Starlight dans un sous-chemin

Pour ajouter toutes les pages Starlight dans un sous-chemin, placez tout votre contenu de documentation dans un sous-répertoire de `src/content/docs/`.

Par exemple, si les pages de Starlight doivent toutes commencer par `/guides/`, ajoutez votre contenu dans le répertoire `src/content/docs/guides/` :

import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src/
  - content/
    - docs/
      - **guides/**
        - guide.md
        - index.md
  - pages/
- astro.config.mjs

</FileTree>

À l'avenir, nous prévoyons de mieux prendre en charge ce cas d'utilisation pour éviter le besoin du répertoire supplémentaire dans `src/content/docs/`.

### Utiliser Starlight avec SSR

Pour activer le SSR, suivez le guide [« Adaptateurs de rendu à la demande »](https://docs.astro.build/fr/guides/on-demand-rendering/) dans la documentation d'Astro pour ajouter un adaptateur serveur à votre projet Starlight.

Les pages de documentation générées par Starlight sont pré-rendues par défaut, quel que soit le mode de rendu de votre projet. Pour désactiver le pré-rendu de vos pages Starlight, définissez [l'option de configuration `prerender`](/fr/reference/configuration/#prerender) à `false`.


================================================
FILE: docs/src/content/docs/fr/reference/configuration.mdx
================================================
---
title: Référence de configuration
description: Une vue d'ensemble de toutes les options de configuration prises en charge par Starlight.
---

## Configuration de l'intégration `starlight`

Starlight est une intégration basée sur le framework web [Astro](https://astro.build). Vous pouvez configurer votre projet dans le fichier de configuration `astro.config.mjs` :

```js
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Mon ravissant site de docs',
		}),
	],
});
```

Vous pouvez passer les options suivantes à l'intégration `starlight`.

### `title` (obligatoire)

**Type :** `string | Record<string, string>`

Définissez le titre de votre site web. Il sera utilisé dans les métadonnées et dans le titre de l'onglet du navigateur.

La valeur peut être une chaîne de caractères, ou pour les sites multilingues, un objet avec des valeurs pour chacune des différentes locales.
Lorsque vous utilisez la forme objet, les clés doivent être des étiquettes d'identification BCP-47 (par exemple `fr`, `ar`, ou `zh-CN`) :

```ts
starlight({
	title: {
		fr: 'Mon ravissant site de docs',
		de: 'Meine bezaubernde Dokumentationsseite',
	},
});
```

### `description`

**Type :** `string`

Définissez la description de votre site web. Utilisée dans les métadonnées partagées avec les moteurs de recherche dans la balise `<meta name="description">` si `description` n'est pas définie dans le frontmatter d'une page.

### `logo`

**Type :** [`LogoConfig`](#logoconfig)

Définit une image de logo à afficher dans la barre de navigation à côté ou à la place du titre du site. Vous pouvez soit définir une seule propriété `src`, soit définir des sources d'images séparées pour `light` et `dark`.

```js
starlight({
	logo: {
		src: './src/assets/my-logo.svg',
	},
});
```

#### `LogoConfig`

```ts
type LogoConfig = { alt?: string; replacesTitle?: boolean } & (
	| { src: string }
	| { light: string; dark: string }
);
```

### `tableOfContents`

**Type :** `false | { minHeadingLevel?: number; maxHeadingLevel?: number }`  
**Par défaut :** `{ minHeadingLevel: 2, maxHeadingLevel: 3 }`

Configurez la table des matières affichée à droite de chaque page. Par défaut, les en-têtes `<h2>` et `<h3>` seront inclus dans cette table des matières.

### `editLink`

**Type :** `{ baseUrl: string }`

Active les liens « Modifier cette page » en définissant l'URL de base qu'ils doivent utiliser. Le lien final sera `editLink.baseUrl` + le chemin de la page actuelle. Par exemple, pour permettre l'édition de pages dans le dépôt `withastro/starlight` sur GitHub :

```js
starlight({
	editLink: {
		baseUrl: 'https://github.com/withastro/starlight/edit/main/',
	},
});
```

Avec cette configuration, une page `/introduction` aurait un lien d'édition pointant vers `https://github.com/withastro/starlight/edit/main/src/content/docs/introduction.md`.

### `sidebar`

**Type :** [`SidebarItem[]`](#sidebaritem)

Configure les éléments de navigation de la barre latérale de votre site.

Une barre latérale est un tableau de liens et de groupes de liens.
À l'exception des éléments utilisant `slug`, chaque élément doit comporter un `label` et l'une des propriétés suivantes :

- `link` — un lien vers une URL spécifique, comme `'/home'` ou `'https://example.com'`.

- `slug` — une référence à une page interne, par exemple `'guides/getting-started'`.

- `items` — un tableau contenant plus de liens et des sous-groupes.

- `autogenerate` — un objet spécifiant un répertoire de votre documentation à partir duquel générer automatiquement un groupe de liens.

Les liens internes peuvent également être spécifiés sous forme de chaîne de caractères au lieu d'un objet avec une propriété `slug`.

```js
starlight({
	sidebar: [
		// Un lien unique étiqueté « Accueil ».
		{ label: 'Accueil', link: '/' },
		// Un groupe étiqueté « Débuter ici » contenant quatre liens.
		{
			label: 'Débuter ici',
			items: [
				// Utilisation de `slug` pour les liens internes.
				{ slug: 'intro' },
				{ slug: 'installation' },
				// Ou la forme simplifiée pour les liens internes.
				'tutorial',
				'next-steps',
			],
		},
		// Un groupe liant toutes les pages présentes dans le répertoire reference.
		{
			label: 'Référence',
			autogenerate: { directory: 'reference' },
		},
	],
});
```

#### Tri

Les groupes de barres latérales générées automatiquement sont triés par nom de fichier et par ordre alphabétique.
Par exemple, une page générée à partir de `astro.md` apparaîtrait au-dessus de la page de `starlight.md`.

#### Groupes rétractables

Les groupes de liens sont développés par défaut. Vous pouvez modifier ce comportement en définissant la propriété `collapsed` d'un groupe sur `true`.

Les sous-groupes générés automatiquement respectent la propriété `collapsed` de leur groupe parent par défaut. Définissez la propriété `autogenerate.collapsed` pour remplacer ce comportement.

```js {5,13}
sidebar: [
  // Un groupe rétractable de liens.
  {
    label: 'Liens rétractés',
    collapsed: true,
    items: ['intro', 'next-steps'],
  },
  // Un groupe développé contenant des sous-groupes générés automatiquement rétractés.
  {
    label: 'Référence',
    autogenerate: {
      directory: 'reference',
      collapsed: true,
    },
  },
],
```

#### Traduire les étiquettes

Si votre site est multilingue, le `label` de chaque élément est considéré comme étant dans la locale par défaut. Vous pouvez définir une propriété `translations` pour fournir des étiquettes pour les autres langues prises en charge :

```js {5,9,14}
sidebar: [
	// Un exemple de barre latérale avec des étiquettes traduites en portugais brésilien.
	{
		label: 'Commencer ici',
		translations: { 'pt-BR': 'Comece Aqui' },
		items: [
			{
				label: 'Bien démarrer',
				translations: { 'pt-BR': 'Introdução' },
				link: '/getting-started',
			},
			{
				label: 'Structure du projet',
				translations: { 'pt-BR': 'Estrutura de Projetos' },
				link: '/structure',
			},
		],
	},
];
```

#### `SidebarItem`

```ts
type SidebarItem =
	| string
	| ({
			translations?: Record<string, string>;
			badge?: string | BadgeConfig;
	  } & (
			| {
					// Lien
					link: string;
					label: string;
					attrs?: Record<string, string | number | boolean | undefined>;
			  }
			| {
					// Lien interne
					slug: string;
					label?: string;
					attrs?: Record<string, string | number | boolean | undefined>;
			  }
			| {
					// Groupe de liens
					label: string;
					items: SidebarItem[];
					collapsed?: boolean;
			  }
			| {
					// Groupe de liens généré automatiquement
					label: string;
					autogenerate: {
						directory: string;
						collapsed?: boolean;
						attrs?: Record<string, string | number | boolean | undefined>;
					};
					collapsed?: boolean;
			  }
	  ));
```

#### `BadgeConfig`

```ts
interface BadgeConfig {
	text: string;
	variant?: 'note' | 'tip' | 'caution' | 'danger' | 'success' | 'default';
	class?: string;
}
```

### `locales`

**Type :** <code>\{ \[dir: string\]: [LocaleConfig](#localeconfig) \}</code>

[Configurez l'internationalisation (i18n)](/fr/guides/i18n/) de votre site en définissant les `locales` prises en charge.

Chaque entrée doit utiliser comme clé le répertoire dans lequel les fichiers de cette langue sont sauvegardés.

```js
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'My Site',
			// Définit l'anglais comme langue par défaut pour ce site.
			defaultLocale: 'en',
			locales: {
				// Documentation en anglais située dans `src/content/docs/en/`
				en: {
					label: 'English',
				},
				// Documentation en Chinois simplifié située dans `src/content/docs/zh-cn/`
				'zh-cn': {
					label: '简体中文',
					lang: 'zh-CN',
				},
				// Documentation en Arabe située dans `src/content/docs/ar/`
				ar: {
					label: 'العربية',
					dir: 'rtl',
				},
			},
		}),
	],
});
```

#### `LocaleConfig`

```ts
interface LocaleConfig {
	label: string;
	lang?: string;
	dir?: 'ltr' | 'rtl';
}
```

Vous pouvez définir les options suivantes pour chaque locale :

##### `label` (obligatoire)

**Type :** `string`

L'étiquette de cette langue à afficher aux utilisateurs, par exemple dans le sélecteur de langue. Le plus souvent, il s'agit du nom de la langue tel qu'un utilisateur de cette langue s'attendrait à le lire, par exemple `"English"`, `"العربية"`, ou `"简体中文"`.

##### `lang`

**Type :** `string`

L'étiquette d’identification BCP-47 pour cette langue, par exemple `"en"`, `"ar"`, ou `"zh-CN"`. Si elle n'est pas définie, le nom du répertoire de la langue sera utilisé par défaut. Les étiquettes de langue avec des sous-étiquettes régionales (par exemple `"pt-BR"` ou `"en-US"`) utiliseront les traductions de l'interface utilisateur intégrées pour leur langue de base si aucune traduction spécifique à la région n'est trouvée.

##### `dir`

**Type :** `'ltr' | 'rtl'`

Le sens d'écriture de cette langue ; `"ltr"` pour gauche à droite (par défaut) ou `"rtl"` pour droite à gauche.

#### Locale racine

Vous pouvez servir la langue par défaut sans répertoire `/lang/` en définissant une locale avec la clé `root` :

```js {3-6}
starlight({
	locales: {
		root: {
			label: 'English',
			lang: 'en',
		},
		fr: {
			label: 'Français',
		},
	},
});
```

Par exemple, cela vous permet de servir `/getting-started/` comme une route anglaise et d'utiliser `/fr/getting-started/` comme la page française équivalente.

### `defaultLocale`

**Type :** `string`

Définit la langue par défaut pour ce site.
La valeur doit correspondre à l'une des clés de votre objet [`locales`](#locales).
(Si votre langue par défaut est votre [locale racine](#locale-racine), vous pouvez sauter cette étape).

La locale par défaut sera utilisée pour fournir un contenu de remplacement lorsque les traductions sont manquantes.

### `social`

**Type :** <code>{`Array<{ label: string; icon: `}[StarlightIcon](/fr/reference/icons/){`; href: string }>`}</code>

Détails optionnels sur les comptes de médias sociaux pour ce site.
Chaque entrée sera affichée sous forme de lien iconisé dans l'en-tête du site.

```js
starlight({
	social: [
		{ icon: 'codeberg', label: 'Codeberg', href: 'https://codeberg.org/knut' },
		{ icon: 'discord', label: 'Discord', href: 'https://astro.build/chat' },
		{ icon: 'github', label: 'GitHub', href: 'https://github.com/withastro' },
		{ icon: 'gitlab', label: 'GitLab', href: 'https://gitlab.com/delucis' },
		{ icon: 'mastodon', label: 'Mastodon', href: 'https://m.webtoo.ls/@astro' },
	],
}),
```

### `customCss`

**Type :** `string[]`

Fournit des fichiers CSS pour personnaliser l'aspect et la convivialité de votre site Starlight.

Prend en charge les fichiers CSS locaux relatifs à la racine de votre projet, par exemple `'./src/custom.css'`, et les CSS que vous avez installés en tant que module npm, par exemple `'@fontsource/roboto'`.

```js
starlight({
	customCss: ['./src/custom-styles.css', '@fontsource/roboto'],
});
```

### `markdown`

**Type :** `{ headingLinks?: boolean; processedDirs?: string[] }`  
**Par défaut :** `{ headingLinks: true, processedDirs: [] }`

Configure le traitement de contenu Markdown par Starlight.

#### `headingLinks`

**Type :** `boolean`  
**Par défaut :** `true`

Définit si les en-têtes sont affichés avec des liens d'ancrage cliquables ou non.

```js
starlight({
	markdown: {
		// Désactive les liens d'ancrage cliquables pour les en-têtes.
		headingLinks: false,
	},
}),
```

#### `processedDirs`

**Type :** `string[]`  
**Par défaut :** `[]`

Définit les répertoires supplémentaires contenant les fichiers qui doivent être ajoutés à la chaîne de traitement Markdown de Starlight.
Par défaut, seuls les contenus Markdown et MDX chargés à l'aide de [`docsLoader()`](/fr/reference/configuration/#docsloader) de Starlight sont traités.
Prend en charge les répertoires locaux relatifs à la racine de votre projet, par exemple `'./src/data/comments/'`.

Le traitement de Starlight inclut la prise en charge des [liens d'ancrage cliquables des en-têtes](#headinglinks), de la [syntaxe de directive Markdown pour les encarts](/fr/guides/authoring-content/#encarts) et du sens d'écriture RTL dans les blocs de code.
Cette option peut être utile si vous affichez du contenu provenant d'une collection de contenu personnalisée dans une [page personnalisée](/fr/guides/pages/#pages-personnalisées) à l'aide du composant `<StarlightPage>` et que vous vous attendez à ce que le traitement Markdown de Starlight soit également appliqué à ce contenu.

```js
starlight({
	markdown: {
		// Traiter les fichiers Markdown de la collection de contenu `reviews` située dans le
		// répertoire `src/data/reviews/`.
		processedDirs: ['./src/data/reviews/'],
	},
}),
```

### `expressiveCode`

**Type :** `StarlightExpressiveCodeOptions | boolean`  
**Par défaut :** `true`

Starlight utilise [Expressive Code](https://expressive-code.com) pour afficher les blocs de code et ajouter la prise en charge de la mise en évidence des portions d'exemples de code, de l'ajout de noms de fichiers aux blocs de code, et plus encore.
Consultez le [guide « Blocs de code »](/fr/guides/authoring-content/#blocs-de-code) pour apprendre à utiliser la syntaxe d'Expressive Code dans votre contenu Markdown et MDX.

Vous pouvez utiliser n'importe laquelle des [options de configuration standard d'Expressive Code](https://expressive-code.com/reference/configuration/) ainsi que certaines propriétés spécifiques à Starlight, en les définissant dans l'option `expressiveCode` de Starlight.
Par exemple, définissez l'option `styleOverrides` d'Expressive Code pour remplacer le CSS par défaut. Cela permet des personnalisations comme donner à vos blocs de code des coins arrondis :

```js ins={2-4}
starlight({
	expressiveCode: {
		styleOverrides: { borderRadius: '0.5rem' },
	},
});
```

Si vous souhaitez désactiver Expressive Code, définissez `expressiveCode: false` dans votre configuration de Starlight :

```js ins={2}
starlight({
	expressiveCode: false,
});
```

En plus des options standard d'Expressive Code, vous pouvez également définir les propriétés suivantes spécifiques à Starlight dans votre configuration `expressiveCode` pour personnaliser davantage le comportement du thème pour vos blocs de code :

#### `themes`

**Type :** `Array<string | ThemeObject | ExpressiveCodeTheme>`  
**Par défaut :** `['starlight-dark', 'starlight-light']`

Définit les thèmes utilisés pour mettre en forme les blocs de code.
Consultez la [documentation des `themes` d'Expressive Code](https://expressive-code.com/guides/themes/) pour plus de détails sur les formats de thème pris en charge.

Starlight utilise les variantes claires et sombres du [thème Night Owl](https://github.com/sdras/night-owl-vscode-theme) de Sarah Drasner par défaut.

Si vous définissez au moins un thème clair et un thème sombre, Starlight gardera automatiquement le thème de bloc de code actif en phase avec le thème actuel du site.
Configurez ce comportement avec l'option [`useStarlightDarkModeSwitch`](#usestarlightdarkmodeswitch).

#### `useStarlightDarkModeSwitch`

**Type :** `boolean`  
**Par défaut :** `true`

Lorsque la valeur est `true`, les blocs de code basculent automatiquement entre les thèmes clairs et sombres lorsque le thème du site change.
Lorsque la valeur est `false`, vous devez ajouter manuellement du CSS pour gérer le basculement entre plusieurs thèmes.

:::note
Quand `themes` est défini, vous devez fournir au moins un thème sombre et un thème clair pour que le changement en mode sombre de Starlight fonctionne.
:::

#### `useStarlightUiThemeColors`

**Type :** `boolean`  
**Par défaut :** `true` si `themes` n'est pas défini, sinon `false`

Lorsque la valeur est `true`, les variables CSS de Starlight sont utilisées pour les couleurs des éléments d'interface utilisateur des blocs de code (arrière-plans, boutons, ombres, etc.), uniformément avec le [thème de couleur du site](/fr/guides/css-and-tailwind/#personnalisation-du-thème).
Lorsque la valeur est `false`, les couleurs fournies par le thème de coloration syntaxique actif sont utilisées pour ces éléments.

:::note
Lorsque des thèmes personnalisés sont utilisés et que cette option est définie à `true`, vous devez fournir au moins un thème sombre et un thème clair pour assurer un contraste de couleur approprié.
:::

### `pagefind`

**Type :** <code>boolean | <a href="#pagefindoptions">PagefindOptions</a></code>  
**Par défaut :** `false`

Configure le système de recherche du site par défaut de Starlight, [Pagefind](https://pagefind.app/).

Utilisez la valeur `false` pour désactiver l'indexation de votre site avec Pagefind.
Cela désactivera également l'interface de recherche par défaut de Starlight si utilisée.

Pagefind ne peut pas être activé lorsque l'option [`prerender`](#prerender) est définie à `false`.

Définissez `pagefind` avec un objet pour configurer le client de recherche Pagefind :

- Consultez [« Personnaliser le classement des résultats de Pagefind »](https://pagefind.app/docs/ranking/) dans la documentation de Pagefind pour plus de détails sur l'utilisation de l'option `pagefind.ranking` pour contrôler comment le classement des résultats de recherche est calculé
- Consultez [« Recherche sur plusieurs sites »](https://pagefind.app/docs/multisite/) dans la documentation de Pagefind pour plus de détails sur l'utilisation de l'option `pagefind.mergeIndex` pour contrôler comment rechercher sur plusieurs sites

#### `PagefindOptions`

```ts
interface PagefindOptions {
	ranking?: {
		pageLength?: number;
		termFrequency?: number;
		termSaturation?: number;
		termSimilarity?: number;
	};
	indexWeight?: number;
	mergeIndex?: Array<{
		bundlePath: string;
		indexWeight?: number;
		basePath?: string;
		baseUrl?: string;
		mergeFilter?: Record<string, string | string[]>;
		language?: string;
		ranking?: {
			pageLength?: number;
			termFrequency?: number;
			termSaturation?: number;
			termSimilarity?: number;
		};
	}>;
}
```

### `prerender`

**Type :** `boolean`  
**Par défaut :** `true`

Définit si les pages générées par Starlight doivent être pré-rendues en HTML statique ou rendues à la demande par un [adaptateur SSR](https://docs.astro.build/fr/guides/on-demand-rendering/).

Les pages Starlight sont pré-rendues par défaut.
Si vous utilisez un adaptateur SSR et que vous souhaitez générer les pages Starlight à la demande, définissez `prerender: false`.

### `head`

**Type :** [`HeadConfig[]`](#headconfig)

Ajoute des balises personnalisées au `<head>` de votre site Starlight.
Cela peut être utile pour ajouter une solution de mesure d'audience ou d'autres ressources et scripts tiers.

```js
starlight({
	head: [
		// Exemple : ajouter une balise pour le script de suivi de Fathom
		{
			tag: 'script',
			attrs: {
				src: 'https://cdn.usefathom.com/script.js',
				'data-site': 'MON-ID-FATHOM',
				defer: true,
			},
		},
	],
});
```

Les entrées dans `head` sont converties directement en éléments HTML et ne passent pas par le traitement de [script](https://docs.astro.build/fr/guides/client-side-scripts/#traitement-des-scripts) ou de [style](https://docs.astro.build/fr/guides/styling/#mettre-en-forme-avec-astro) d'Astro.
Si vous avez besoin d'importer des ressources locales comme des scripts, des styles ou des images, [redéfinissez le composant Head](/fr/guides/overriding-components/#réutiliser-un-composant-intégré).

#### `HeadConfig`

```ts
interface HeadConfig {
	tag: string;
	attrs?: Record<string, string | boolean | undefined>;
	content?: string;
}
```

### `lastUpdated`

**Type :** `boolean`  
**Par défaut :** `false`

Contrôlez si le pied de page affiche la date de la dernière mise à jour de la page.

Par défaut, cette fonctionnalité s'appuie sur l'historique Git de votre dépôt et peut ne pas être précise sur certaines plateformes de déploiement effectuant des [clonages superficiels](https://git-scm.com/docs/git-clone#Documentation/git-clone.txt---depthltdepthgt). Une page peut remplacer ce paramètre ou la date basée sur Git en utilisant [le champ `lastUpdated` du frontmatter](/fr/reference/frontmatter/#lastupdated).

### `pagination`

**Type :** `boolean`  
**Par défaut :** `true`

Définissez si le pied de page doit inclure des liens vers les pages précédentes et suivantes.

Une page peut remplacer ce paramètre ou le texte du lien et/ou l'URL en utilisant les champs de frontmatter [`prev`](/fr/reference/frontmatter/#prev) et [`next`](/fr/reference/frontmatter/#next).

### `favicon`

**Type :** `string`  
**Par défaut :** `'/favicon.svg'`

Définissez le chemin de l'icône par défaut pour votre site Web qui doit être situé dans le répertoire `public/` et être un fichier d'icône valide (`.ico`, `.gif`, `.jpg`, `.png` ou `.svg`).

```js
starlight({
  favicon: '/images/favicon.svg',
}),
```

Si vous avez besoin de définir des variantes supplémentaires ou des icônes de secours, vous pouvez ajouter des balises en utilisant l'option [`head`](#head) :

```js
starlight({
	favicon: '/images/favicon.svg',
	head: [
		// Ajouter une icône ICO de secours pour Safari.
		{
			tag: 'link',
			attrs: {
				rel: 'icon',
				href: '/images/favicon.ico',
				sizes: '32x32',
			},
		},
	],
});
```

### `titleDelimiter`

**Type :** `string`  
**Par défaut :** `'|'`

Définit le délimiteur entre le titre de la page et le titre du site dans la balise `<title>` de la page, qui s'affiche dans les onglets du navigateur.

Par défaut, chaque page a une balise `<title>` contenant `Titre de la page | Titre du site`.
Par example, cette page a pour titre « Référence de configuration » et ce site a pour titre « Starlight », donc la balise `<title>` de cette page contient « Référence de configuration | Starlight ».

### `disable404Route`

**Type :** `boolean`  
**Par défaut :** `false`

Désactive l'injection de la [page 404](https://docs.astro.build/fr/basics/astro-pages/#page-derreur-404-personnalis%C3%A9e) par défaut de Starlight. Pour utiliser une route personnalisée `src/pages/404.astro` dans votre projet, définissez cette option à `true`.

### `routeMiddleware`

**Type :** `string | string[]`

Fournit les chemins vers les middlewares de route qui peuvent modifier la manière dont Starlight transforme vos données.
Ces chemins de fichiers ne doivent pas entrer en conflit avec les [middlewares d'Astro](https://docs.astro.build/fr/guides/middleware/).

Consultez le [guide des données de route](/fr/guides/route-data/#personnalisation-des-données-de-route) pour plus de détails sur la création de middlewares de route.

### `components`

**Type :** `Record<string, string>`

Fournit les chemins vers les composants pour redéfinir les implémentations par défaut de Starlight.

```js
starlight({
	components: {
		SocialLinks: './src/components/MySocialLinks.astro',
	},
});
```

Consultez la [référence des redéfinitions](/fr/reference/overrides/) pour plus de détails sur tous les composants que vous pouvez redéfinir.

### `plugins`

**Type :** [`StarlightPlugin[]`](/fr/reference/plugins/#référence-rapide-de-lapi)

Étendez Starlight avec des modules d'extension personnalisés.
Les modules d'extension appliquent des changements à votre projet pour modifier ou ajouter des fonctionnalités à Starlight.

Visitez la [vitrine des modules d'extension](/fr/resources/plugins/#modules-dextension) pour voir une liste des modules d'extension disponibles.

```js
starlight({
	plugins: [starlightPlugin()],
});
```

Consultez la [référence des modules d'extension](/fr/reference/plugins/) pour plus de détails pour créer vos propres modules d'extension.

### `credits`

**Type :** `boolean`  
**Par défaut :** `false`

Permet l'affichage d'un lien « Créé avec Starlight » dans le pied de page de votre site.

```js
starlight({
	credits: true,
});
```

## Configuration des collections de contenu

Starlight utilise les [collections de contenu d'Astro](https://docs.astro.build/fr/guides/content-collections/) pour charger votre contenu.
Les chargeurs (également connus sous le nom de « loaders » en anglais) et schémas de collection de Starlight aident à configurer les collections comme nécessaire.

```js
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';

export const collections = {
	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
	// Optionnel : la collection i18n est utilisée pour traduire l'interface
	// utilisateur dans les sites multilingues
	i18n: defineCollection({ loader: i18nLoader(), schema: i18nSchema() }),
};
```

### Chargeurs

Starlight exporte les [chargeurs Astro](https://docs.astro.build/fr/reference/content-loader-reference/) suivants depuis le module `@astrojs/starlight/loaders` pour simplifier la configuration des collections de contenu.

#### `docsLoader()`

Le chargeur `docsLoader()` charge les fichiers Markdown, MDX et Markdoc locaux du répertoire `src/content/docs/`.
Les fichiers commençant par un tiret bas (`_`) sont ignorés.

##### Importation

```js
import { docsLoader } from '@astrojs/starlight/loaders';
```

##### Options

###### `generateId()`

**Type :** `({ entry: string; base: URL; data: Record<string, unknown> }) => string`

Par défaut, les pages générées en utilisant `docsLoader()` transforment les noms de fichiers en utilisant un générateur de slug qui supprime les caractères spéciaux et met le nom de fichier en minuscules.
Si vous souhaitez remplacer ce comportement par défaut, spécifiez votre propre fonction `generateId()`.

Par exemple, cela peut être utile pour préserver des caractères spéciaux qui seraient supprimés.
Par défaut, `Exemple.Fichier.md` serait diponible à l'URL `/exemplefichier`.
Si vous souhaitez le rendre disponible à l'URL `/Exemple.Fichier`, vous pouvez le faire en définissant une fonction `generateId()` personnalisée :

```js
docsLoader({
	// Supprime les extension `.md` ou `.mdx` sans modifier les noms de fichiers.
	generateId: ({ entry }) => entry.split('.').slice(0, -1).join('.'),
}),
```

Consultez [`generateId()` dans la documentation d'Astro](https://docs.astro.build/fr/reference/content-loader-reference/#generateid) pour plus de détails.

#### `i18nLoader()`

Le chargeur `i18nLoader()` charge les fichiers JSON et YAML locaux du répertoire `src/content/i18n/`.
Les fichiers commençant par un tiret bas (`_`) sont ignorés.

##### Importation

```js
import { i18nLoader } from '@astrojs/starlight/loaders';
```

##### Options

Il n'y a pour le moment aucune option pour configurer `i18nLoader()`.

### Schémas

Starlight fournit les [schémas de collection de contenu](https://docs.astro.build/fr/guides/content-collections/#d%C3%A9finition-dun-sch%C3%A9ma-de-collection) suivants depuis le module `@astrojs/starlight/schema`.
Ces schémas doivent être utilisés pour les collections `docs` et `i18n` dont Starlight dépend.

#### `docsSchema()`

Le chargeur `docsSchema()` analyse (opération également appelée « parse » en anglais) le frontmatter de tout le contenu de la collection `docs`.

##### Importation

```js
import { docsSchema } from '@astrojs/starlight/schema';
```

##### Options

###### `extend`

**Type :** Schéma Zod ou fonction qui retourne un schéma Zod  
**Par défaut :** `z.object({})`

Étendez le schéma du frontmatter de Starlight avec des champs supplémentaires.
Consultez [« Personnaliser le schéma du frontmatter »](/fr/reference/frontmatter/#personnaliser-le-schéma-du-frontmatter) pour plus de détails sur l'utilisation de l'option `extend`.

#### `i18nSchema()`

Le chargeur `i18nSchema()` analyse tous les fichiers de données dans la collection `i18n`.

##### Importation

```js
import { i18nSchema } from '@astrojs/starlight/schema';
```

##### Options

###### `extend`

**Type :** Objet Zod  
**Par défaut :** `z.object({})`

Étendez le schéma de traduction de Starlight avec des champs supplémentaires.
Consultez [« Étendre le schéma de traduction »](/fr/guides/i18n/#étendre-le-schéma-de-traduction) pour plus de détails sur l'utilisation de l'option `extend`.


================================================
FILE: docs/src/content/docs/fr/reference/frontmatter.md
================================================
---
title: Référence du frontmatter
description: Une vue d'ensemble des champs du frontmatter par défaut pris en charge par Starlight.
---

Vous pouvez personnaliser des pages Markdown et MDX individuelles dans Starlight en définissant des valeurs dans leur frontmatter. Par exemple, une page normale peut définir les champs `title` et `description` :

```md {3-4}
---
# src/content/docs/exemple.md
title: A propos de ce projet
description: En savoir plus sur le projet sur lequel je travaille.
---

Bienvenue sur la page "à propos" !
```

## Champs du frontmatter

### `title` (obligatoire)

**Type :** `string`

Vous devez fournir un titre pour chaque page. Il sera affiché en haut de la page, dans les onglets du navigateur et dans les métadonnées de la page.

### `description`

**Type :** `string`

La description de la page est utilisée pour les métadonnées de la page et sera reprise par les moteurs de recherche et dans les aperçus des médias sociaux.

### `slug`

**type**: `string`

Remplace le slug de la page. Consultez [« Définition d’identifiants personnalisés »](https://docs.astro.build/fr/guides/content-collections/#définition-didentifiants-personnalisés) dans la documentation d'Astro pour plus de détails.

### `editUrl`

**Type :** `string | boolean`

Remplace la [configuration globale `editLink`](/fr/reference/configuration/#editlink). Mettez `false` pour désactiver le lien « Modifier cette page » pour une page spécifique ou pour fournir une URL alternative où le contenu de cette page est éditable.

### `head`

**Type :** [`HeadConfig[]`](/fr/reference/configuration/#headconfig)

Vous pouvez ajouter des balises supplémentaires au champ `<head>` de votre page en utilisant le champ `head` frontmatter. Cela signifie que vous pouvez ajouter des styles personnalisés, des métadonnées ou d'autres balises à une seule page. Similaire à [l'option globale `head`](/fr/reference/configuration/#head).

```md
---
# src/content/docs/exemple.md
title: A propos de nous
head:
  # Utiliser une balise <title> personnalisée
  - tag: title
    content: Titre personnalisé à propos de nous
---
```

### `tableOfContents`

**Type :** `false | { minHeadingLevel?: number; maxHeadingLevel?: number; }`

Remplace la [configuration globale `tableOfContents`](/fr/reference/configuration/#tableofcontents).
Personnalisez les niveaux d'en-tête à inclure ou mettez `false` pour cacher la table des matières sur cette page.

```md
---
# src/content/docs/exemple.md
title: Page avec seulement des H2 dans la table des matières
tableOfContents:
  minHeadingLevel: 2
  maxHeadingLevel: 2
---
```

```md
---
# src/content/docs/exemple.md
title: Page sans table des matières
tableOfContents: false
---
```

### `template`

**Type :** `'doc' | 'splash'`  
**Par défaut :** `'doc'`

Définit le modèle de mise en page pour cette page.
Les pages utilisent la mise en page `'doc'`' par défaut.
La valeur `'splash'` permet d'utiliser une mise en page plus large, sans barres latérales, conçue pour les pages d'atterrissage.

### `hero`

**Type :** [`HeroConfig`](#heroconfig)

Ajoute un composant héros en haut de la page. Fonctionne bien avec `template : splash`.

Par exemple, cette configuration montre quelques options communes, y compris le chargement d'une image depuis votre dépôt.

```md
---
# src/content/docs/exemple.md
title: Ma page d'accueil
template: splash
hero:
  title: 'Mon projet : Stellar Stuffer Sooner'
  tagline: Emmenez vos affaires sur la lune et revenez-y en un clin d'œil.
  image:
    alt: Un logo aux couleurs vives et scintillantes
    file: ../../assets/logo.png
  actions:
    - text: En savoir plus
      link: /getting-started/
      icon: right-arrow
    - text: Voir sur GitHub
      link: https://github.com/astronaut/my-project
      icon: external
      variant: minimal
      attrs:
        rel: me
---
```

Vous pouvez afficher différentes versions de l'image de premier plan en mode clair et sombre.

```md
---
# src/content/docs/exemple.md
hero:
  image:
    alt: Un logo scintillant aux couleurs vives
    dark: ../../assets/logo-dark.png
    light: ../../assets/logo-light.png
---
```

#### `HeroConfig`

```ts
interface HeroConfig {
  title?: string;
  tagline?: string;
  image?:
    | {
        // Chemin relatif vers une image dans votre dépôt.
        file: string;
        // Alternative textuelle pour rendre l'image accessible aux technologies d'assistance.
        alt?: string;
      }
    | {
        // Chemin relatif vers une image dans votre dépôt à utiliser pour le mode sombre.
        dark: string;
        // Chemin relatif vers une image dans votre dépôt à utiliser pour le mode clair.
        light: string;
        // Alternative textuelle pour rendre l'image accessible aux technologies d'assistance.
        alt?: string;
      }
    | {
        // HTML brut à utiliser dans le slot de l'image.
        // Peut être une balise `<img>` personnalisée ou une balise `<svg>` en ligne.
        html: string;
      };
  actions?: Array<{
    text: string;
    link: string;
    variant?: 'primary' | 'secondary' | 'minimal';
    icon?: string;
    attrs?: Record<string, string | number | boolean>;
  }>;
}
```

### `banner`

**Type :** `{ content: string }`

Montrera une bannière d'annonce en haut de cette page.

La valeur `content` peut inclure du HTML pour les liens ou d'autres contenus.
Par exemple, cette page affiche une bannière comprenant un lien vers `example.com`.

```md
---
# src/content/docs/exemple.md
title: Page avec une bannière
banner:
  content: |
    On a lancé quelque chose de cool !
    <a href="https://example.com">Allez-y</a>
---
```

### `lastUpdated`

**Type :** `Date | boolean`

Remplace la [configuration globale `lastUpdated`](/fr/reference/configuration/#lastupdated). Si une date est spécifiée, elle doit être un [horodatage YAML](https://yaml.org/type/timestamp.html) valide et remplacera la date stockée dans l'historique Git pour cette page.

```md
---
# src/content/docs/exemple.md
title: Page avec une date de dernière mise à jour personnalisée
lastUpdated: 2022-08-09
---
```

### `prev`

**Type :** `boolean | string | { link?: string; label?: string }`

Remplace la [configuration globale `pagination`](/fr/reference/configuration/#pagination). Si une chaîne de caractères est spécifiée, le texte du lien généré sera remplacé et si un objet est spécifié, le lien et le texte seront remplacés.

```md
---
# src/content/docs/exemple.md
# Masquer le lien de la page précédente
prev: false
---
```

```md
---
# src/content/docs/exemple.md
# Remplacer le texte du lien de la page
prev: Poursuivre le tutoriel
---
```

```md
---
# src/content/docs/exemple.md
# Remplacer le lien et le texte de la page
prev:
  link: /unrelated-page/
  label: Consultez cette autre page
---
```

### `next`

**Type :** `boolean | string | { link?: string; label?: string }`

La même chose que [`prev`](#prev) mais pour le lien de la page suivante.

```md
---
# src/content/docs/exemple.md
# Masquer le lien de la page suivante
next: false
---
```

### `pagefind`

**Type :** `boolean`  
**Par défaut :** `true`

Définit si cette page doit être incluse dans l'index de recherche de [Pagefind](https://pagefind.app/). Définissez la valeur à `false` pour exclure une page des résultats de recherche :

```md
---
# src/content/docs/exemple.md
# Exclut cette page de l'index de recherche
pagefind: false
---
```

### `draft`

**Type :** `boolean`  
**Par défaut :** `false`

Définit si cette page doit être considérée comme une ébauche et ne pas être incluse dans les [déploiements en production](https://docs.astro.build/fr/reference/cli-reference/#astro-build). Définissez la valeur à `true` pour marquer une page comme une ébauche et la rendre visible uniquement pendant le développement.

```md
---
# src/content/docs/exemple.md
# Exclure cette page des déploiements en production
draft: true
---
```

Puisque les ébauches ne sont pas incluses lors d'un déploiement, vous ne pouvez pas ajouter des ébauches directement à la configuration de la barre latérale de navigation de votre site en utilisant des [slugs](/fr/guides/sidebar/#liens-internes).
Les ébauches situées dans des répertoires utilisés dans des [groupes de barre latérale générés automatiquement](/fr/guides/sidebar/#groupes-générés-automatiquement) sont automatiquement exclues des déploiements en production.

### `sidebar`

**Type :** [`SidebarConfig`](#sidebarconfig)

Contrôler l'affichage de cette page dans la [barre latérale](/fr/reference/configuration/#sidebar), lors de l'utilisation d'un groupe de liens généré automatiquement.

#### `SidebarConfig`

```ts
interface SidebarConfig {
  label?: string;
  order?: number;
  hidden?: boolean;
  badge?: string | BadgeConfig;
  attrs?: Record<string, string | number | boolean | undefined>;
}
```

#### `label`

**Type :** `string`  
**Par défaut :** [`title`](#title-obligatoire) de la page

Définir l'étiquette de cette page dans la barre latérale lorsqu'elle est affichée dans un groupe de liens généré automatiquement.

```md
---
# src/content/docs/exemple.md
title: À propos de ce projet
sidebar:
  label: À propos
---
```

#### `order`

**Type :** `number`

Contrôler l'ordre de cette page lors du tri d'un groupe de liens généré automatiquement.
Les numéros inférieurs sont affichés plus haut dans le groupe de liens.

```md
---
# src/content/docs/exemple.md
title: Page à afficher en premier
sidebar:
  order: 1
---
```

#### `hidden`

**Type :** `boolean`  
**Par défaut :** `false`

Empêche cette page d'être incluse dans un groupe de liens généré automatiquement.

```md
---
# src/content/docs/exemple.md
title: Page à masquer de la barre latérale générée automatiquement
sidebar:
  hidden: true
---
```

#### `badge`

**Type :** <code>string | <a href="/fr/reference/configuration/#badgeconfig">BadgeConfig</a></code>

Ajoute un badge à la page dans la barre latérale lorsqu'elle est affichée dans un groupe de liens généré automatiquement.
Lors de l'utilisation d'une chaîne de caractères, le badge sera affiché avec une couleur d'accentuation par défaut.
Passez éventuellement un [objet `BadgeConfig`](/fr/reference/configuration/#badgeconfig) avec les propriétés `text`, `variant`, et `class` pour personnaliser le badge.

```md
---
# src/content/docs/exemple.md
title: Page avec un badge
sidebar:
  # Utilise la variante par défaut correspondant à la couleur d'accentuation de votre site
  badge: Nouveau
---
```

```md
---
# src/content/docs/exemple.md
title: Page avec un badge
sidebar:
  badge:
    text: Expérimental
    variant: caution
---
```

#### `attrs`

**Type :** `Record<string, string | number | boolean | undefined>`

Attributs HTML à ajouter au lien de la page dans la barre latérale lorsqu'il est affiché dans un groupe de liens généré automatiquement.
Si [`autogenerate.attrs`](/fr/guides/sidebar/#attributs-html-personnalisés-pour-les-liens-générés-automatiquement) est défini pour le groupe généré automatiquement auquel cette page appartient, les attributs du frontmatter seront fusionnés avec les attributs du groupe.

```md
---
# src/content/docs/exemple.md
title: Page s'ouvrant dans un nouvel onglet
sidebar:
  # Ouvre la page dans un nouvel onglet
  attrs:
    target: _blank
---
```

## Personnaliser le schéma du frontmatter

Le schéma du frontmatter de la collection de contenus `docs` de Starlight est configuré dans `src/content.config.ts` en utilisant l'utilitaire `docsSchema()` :

```ts {4,7}
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
  docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
};
```

Consultez [« Définir un schéma de collection de contenus »](https://docs.astro.build/fr/guides/content-collections/#définition-dun-schéma-de-collection) dans la documentation d'Astro pour en savoir plus sur les schémas de collection de contenus.

`docsSchema()` accepte les options suivantes :

### `extend`

**Type :** Schéma Zod ou fonction qui retourne un schéma Zod  
**Par défaut :** `z.object({})`

Étendez le schéma de Starlight avec des champs supplémentaires en définissant `extend` dans les options de `docsSchema()`.
La valeur doit être un [schéma Zod](https://docs.astro.build/fr/guides/content-collections/#définition-des-types-de-données-avec-zod).

Dans l'exemple suivant, nous définissons un type plus strict pour `description` pour le rendre obligatoire et ajouter un nouveau champ `category` facultatif :

```ts {10-15}
// src/content.config.ts
import { defineCollection, z } from 'astro:content';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
  docs: defineCollection({
    loader: docsLoader(),
    schema: docsSchema({
      extend: z.object({
        // Rend un champ de base obligatoire au lieu de facultatif.
        description: z.string(),
        // Ajoute un nouveau champ au schéma.
        category: z.enum(['tutoriel', 'guide', 'référence']).optional(),
      }),
    }),
  }),
};
```

Pour tirer parti de l'[utilitaire `image()` d'Astro](https://docs.astro.build/fr/guides/images/#images-dans-les-collections-de-contenu), utilisez une fonction qui retourne votre extension de schéma :

```ts {10-15}
// src/content.config.ts
import { defineCollection, z } from 'astro:content';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
  docs: defineCollection({
    loader: docsLoader(),
    schema: docsSchema({
      extend: ({ image }) => {
        return z.object({
          // Ajoute un champ qui doit être résolu par une image locale.
          cover: image(),
        });
      },
    }),
  }),
};
```


================================================
FILE: docs/src/content/docs/fr/reference/icons.mdx
================================================
---
title: Référence des icônes
description: Une vue d'ensemble de tous les icônes disponibles dans Starlight.
---

Starlight fournit un ensemble d'icônes intégrées que vous pouvez afficher dans votre contenu en utilisant le composant `<Icon>`.

## Utiliser les icônes

Les icônes peuvent être affichées en utilisant le composant [`<Icon>`](/fr/components/icons/).
Elles sont également souvent utilisées dans d'autres composants, comme les [cartes](/fr/components/cards/) ou des paramètres comme les [actions de la section d'en-tête](/fr/reference/frontmatter/#hero).

## Type `StarlightIcon`

Utilisez le type TypeScript `StarlightIcon` pour référencer les noms des [icônes disponibles avec Starlight](#toutes-les-icônes).

```ts {2} /icon: (StarlightIcon)/
// src/icon.ts
import type { StarlightIcon } from '@astrojs/starlight/types';

function getIconLabel(icon: StarlightIcon) {
	// …
}
```

## Toutes les icônes

Une liste de toutes les icônes disponibles est affichée ci-dessous avec leurs noms associés. Cliquez sur une icône pour copier son nom dans votre presse-papiers.

import IconsList from '~/components/icons-list.astro';

<IconsList labels={{ copied: 'Copié !' }} />


================================================
FILE: docs/src/content/docs/fr/reference/overrides.md
================================================
---
title: Référence des redéfinitions
description: Une vue d'ensemble de tous les composants et les props des composants compatibles avec les redéfinitions de Starlight.
tableOfContents:
  maxHeadingLevel: 4
---

Vous pouvez redéfinir les composants intégrés à Starlight en spécifiant des chemins vers des composants de remplacement avec l'option de configuration [`components`](/fr/reference/configuration/#components) de Starlight.
Cette page répertorie tous les composants disponibles qui peuvent être redéfinis et fournit des liens vers leurs implémentations par défaut sur GitHub.

Pour en savoir plus, consultez le [guide des redéfinitions de composants](/fr/guides/overriding-components/).

## Composants

### Métadonnées

Ces composants sont utilisés dans l'élément `<head>` de chaque page.
Ils ne doivent inclure que des [éléments autorisés à l'intérieur de `<head>`](https://developer.mozilla.org/fr/docs/Web/HTML/Element/head).

#### `Head`

**Composant par défaut :** [`Head.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Head.astro)

Composant utilisé à l'intérieur de l'élément `<head>` de chaque page.

Redéfinissez ce composant en dernier recours.
Préférez [l'option de configuration `head`](/fr/reference/configuration/#head), le [champ `head` du frontmatter](/fr/reference/frontmatter/#head), ou un [middleware de données de route](/fr/guides/route-data/#personnalisation-des-données-de-route) pour personnaliser les données de route affichées par le composant par défaut si possible.

#### `ThemeProvider`

**Composant par défaut :** [`ThemeProvider.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/ThemeProvider.astro)

Composant utilisé à l'intérieur de l'élément `<head>` qui configure la prise en charge du thème sombre/clair.
L'implémentation par défaut inclut un script en ligne et un élément `<template>` utilisé par le script situé dans [`<ThemeSelect />`](#themeselect).

---

### Accessibilité

#### `SkipLink`

**Composant par défaut :** [`SkipLink.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/SkipLink.astro)

Composant utilisé comme premier élément à l'intérieur du `<body>` qui relie au contenu principal de la page pour des raisons d'accessibilité.
L'implémentation par défaut est masquée jusqu'à ce qu'il reçoive le focus d'un utilisateur utilisant la navigation au clavier.

---

### Mise en page

Ces composants sont responsables de la mise en page des composants de Starlight et de la gestion des vues pour différents points d'arrêt.
Redéfinir ceux-ci implique une complexité significative.
Lorsque cela est possible, préférez redéfinir un composant de plus bas niveau.

#### `PageFrame`

**Composant par défaut :** [`PageFrame.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/PageFrame.astro)  
**Slots nommés :** `header`, `sidebar`

Composant de mise en page contenant la plupart du contenu de la page.
L'implémentation par défaut configure la mise en page de l'en-tête, de la barre latérale et du contenu principal et inclut des slots nommés `header` et `sidebar` en plus du slot par défaut pour le contenu principal.
Il affiche également [`<MobileMenuToggle />`](#mobilemenutoggle) qui prend en charge l'affichage de la barre latérale de navigation sur petits écrans (mobiles).

#### `MobileMenuToggle`

**Composant par défaut :** [`MobileMenuToggle.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MobileMenuToggle.astro)

Composant utilisé à l'intérieur de [`<PageFrame>`](#pageframe) qui est responsable de l'affichage de la barre latérale de navigation sur petits écrans (mobiles).

#### `TwoColumnContent`

**Composant par défaut :** [`TwoColumnContent.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/TwoColumnContent.astro)  
**Slot nommé :** `right-sidebar`

Composant de mise en page enveloppant le contenu principal de la page et la barre latérale de droite (table des matières).
L'implémentation par défaut prend en charge le changement entre une mise en page à une seule colonne pour petits écrans et une mise en page à deux colonnes pour écrans plus larges.

---

### En-tête

Ces composants affichent la barre de navigation supérieure de Starlight.

#### `Header`

**Composant par défaut :** [`Header.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Header.astro)

Composant d'en-tête affiché en haut de chaque page.
L'implémentation par défaut affiche [`<SiteTitle />`](#sitetitle), [`<Search />`](#search), [`<SocialIcons />`](#socialicons), [`<ThemeSelect />`](#themeselect) et [`<LanguageSelect />`](#languageselect).

#### `SiteTitle`

**Composant par défaut :** [`SiteTitle.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/SiteTitle.astro)

Composant utilisé au début de l'en-tête du site pour afficher le titre du site.
L'implémentation par défaut inclut la logique pour afficher les logos définis dans la configuration de Starlight.

#### `Search`

**Composant par défaut :** [`Search.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Search.astro)

Composant utilisé pour afficher l'interface de recherche de Starlight.
L'implémentation par défaut inclut le bouton dans l'en-tête et le code pour afficher une fenêtre modale de recherche lorsqu'il est cliqué et charger [l'interface utilisateur de Pagefind](https://pagefind.app/).

Lorsque [`pagefind`](/fr/reference/configuration/#pagefind) est désactivé, le composant de recherche par défaut ne sera pas affiché.
Cependant, si vous redéfinissez `Search`, votre composant personnalisé sera toujours affiché même si l'option de configuration `pagefind` est `false`.
Cela vous permet d'ajouter une interface de recherche alternative lorsque vous désactivez Pagefind.

#### `SocialIcons`

**Composant par défaut :** [`SocialIcons.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/SocialIcons.astro)

Composant utilisé dans l'en-tête du site qui inclut des liens avec des icônes vers différents médias sociaux.
L'implémentation par défaut utilise l'option [`social`](/fr/reference/configuration/#social) de la configuration de Starlight pour afficher les icônes et les liens.

#### `ThemeSelect`

**Composant par défaut :** [`ThemeSelect.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/ThemeSelect.astro)

Composant utilisé dans l'en-tête du site qui permet aux utilisateurs de sélectionner leur thème de couleur préféré.

#### `LanguageSelect`

**Composant par défaut :** [`LanguageSelect.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/LanguageSelect.astro)

Component utilisé dans l'en-tête du site qui permet aux utilisateurs de changer de langue.

---

### Barre latérale globale

La barre latérale globale de Starlight contient la navigation principale du site.
Sur des écrans peu larges, elle est masquée derrière un menu déroulant.

#### `Sidebar`

**Composant par défaut :** [`Sidebar.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Sidebar.astro)

Composant utilisé avant le contenu de la page qui contient la navigation globale.
L'implémentation par défaut est affichée comme une barre latérale sur des écrans suffisamment larges et à l'intérieur d'un menu déroulant sur des écrans plus petits (mobiles).
Il utilise aussi [`<MobileMenuFooter />`](#mobilemenufooter) pour afficher des éléments supplémentaires dans le menu mobile.

#### `MobileMenuFooter`

**Composant par défaut :** [`MobileMenuFooter.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MobileMenuFooter.astro)

Composant utilisé à la fin du menu déroulant mobile.
L'implémentation par défaut affiche [`<ThemeSelect />`](#themeselect) et [`<LanguageSelect />`](#languageselect).

---

### Barre latérale de page

La barre latérale de page de Starlight est responsable d'afficher une table des matières mettant en avant les titres de section de la page courante.
Sur des écrans peu larges, elle est remplacée par un menu déroulant adhérant.

#### `PageSidebar`

**Composant par défaut :** [`PageSidebar.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/PageSidebar.astro)

Composant affiché avant le contenu de la page et contenant la table des matières.
L'implémentation par défaut affiche [`<TableOfContents />`](#tableofcontents) et [`<MobileTableOfContents />`](#mobiletableofcontents).

#### `TableOfContents`

**Composant par défaut :** [`TableOfContents.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/TableOfContents.astro)

Composant qui affiche la table des matières de la page courante sur des écrans suffisamment larges.

#### `MobileTableOfContents`

**Composant par défaut :** [`MobileTableOfContents.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MobileTableOfContents.astro)

Composant qui affiche la table des matières de la page courante sur des petits écrans (mobiles).

---

### Contenu

Ces composants sont utilisés dans la colonne principale de contenu de la page.

#### `Banner`

**Composant par défaut :** [`Banner.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Banner.astro)

Composant représentant une bannière affichée en haut de chaque page.
L'implémentation par défaut utilise la valeur du champ [`banner`](/fr/reference/frontmatter/#banner) du frontmatter de la page pour décider de l'affichage ou non.

#### `ContentPanel`

**Composant par défaut :** [`ContentPanel.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/ContentPanel.astro)

Composant de mise en page utilisé pour envelopper les section de la colonne principale de contenu.

#### `PageTitle`

**Composant par défaut :** [`PageTitle.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/PageTitle.astro)

Composant contenant l'élement `<h1>` de la page courante.

Les implémentations personnalisées doivent s'assurer qu'elles définissent `id="_top"` sur l'élément `<h1>` comme dans l'implémentation par défaut.

#### `DraftContentNotice`

**Composant par défaut :** [`DraftContentNotice.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/DraftContentNotice.astro)

Note affichée aux utilisateurs durant le développement lorsque la page actuelle est marquée comme une ébauche.

#### `FallbackContentNotice`

**Composant par défaut :** [`FallbackContentNotice.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/FallbackContentNotice.astro)

Note affichée aux utilisateurs sur les pages où une traduction pour la langue courante n'est pas disponible.
Utilisé uniquement sur les sites multilingues.

#### `Hero`

**Composant par défaut :** [`Hero.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Hero.astro)

Composant affiché en haut de la page lorsque le champ [`hero`](/fr/reference/frontmatter/#hero) est défini dans le frontmatter.
L'implémentation par défaut affiche un large titre, une accroche et des liens d'appel à l'action à côté d'une image facultative.

#### `MarkdownContent`

**Composant par défaut :** [`MarkdownContent.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MarkdownContent.astro)

Composant affiché autour du contenu principal de chaque page.
L'implémentation par défaut définit les styles de base à appliquer au contenu Markdown.

Les styles de contenu Markdown sont également exposés dans `@astrojs/starlight/style/markdown.css` avec une portée limitée à la classe CSS `.sl-markdown-content`.

---

### Pied de page

Ces composants sont affichés en bas de la colonne principale de contenu de la page.

#### `Footer`

**Composant par défaut :** [`Footer.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Footer.astro)

Composant pied de page affiché en bas de chaque page.
L'implémentation par défaut affiche [`<LastUpdated />`](#lastupdated), [`<Pagination />`](#pagination) et [`<EditLink />`](#editlink).

#### `LastUpdated`

**Composant par défaut :** [`LastUpdated.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/LastUpdated.astro)

Composant utilisé dans le pied de page pour afficher la date de dernière mise à jour de la page.

#### `EditLink`

**Composant par défaut :** [`EditLink.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/EditLink.astro)

Composant utilisé dans le pied de page pour afficher un lien vers l'emplacement où la page peut être modifiée.

#### `Pagination`

**Composant par défaut :** [`Pagination.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Pagination.astro)

Composant utilisé dans le pied de page pour afficher des flèches de navigation entre les pages précédentes/suivantes.


================================================
FILE: docs/src/content/docs/fr/reference/plugins.md
================================================
---
title: Référence des modules d'extension
description: Une vue d'ensemble de l'API des modules d'extension Starlight.
tableOfContents:
  maxHeadingLevel: 4
---

Les modules d'extension Starlight peuvent personnaliser la configuration, l'interface utilisateur et le comportement de Starlight, tout en étant faciles à partager et à réutiliser.
Cette page de référence documente l'API à laquelle ces modules d'extension ont accès.

Consultez la [référence de configuration](/fr/reference/configuration/#plugins) pour en savoir plus sur l'utilisation d'un module d'extension Starlight ou visitez la [vitrine des modules d'extension](/fr/resources/plugins/) pour voir une liste de modules d'extension disponibles.

## Référence rapide de l'API

Un module d'extension Starlight a la forme suivante.
Voir ci-dessous pour plus de détails sur les différentes propriétés et paramètres des hooks.

<!-- prettier-ignore-start -->
```ts
interface StarlightPlugin {
  name: string;
  hooks: {
    'i18n:setup'?: (options: {
      injectTranslations: (
        translations: Record<string, Record<string, string>>
      ) => void;
    }) => void | Promise<void>;
    'config:setup': (options: {
      config: StarlightUserConfig;
      updateConfig: (newConfig: StarlightUserConfig) => void;
      addIntegration: (integration: AstroIntegration) => void;
      addRouteMiddleware: (config: { entrypoint: string; order?: 'pre' | 'post' | 'default' }) => void;
      astroConfig: AstroConfig;
      command: 'dev' | 'build' | 'preview';
      isRestart: boolean;
      logger: AstroIntegrationLogger;
      useTranslations: (lang: string) => I18nT;
      absolutePathToLang: (path: string) => string;
    }) => void | Promise<void>;
  };
}
```
<!-- prettier-ignore-end -->

## `name`

**Type :** `string`

Un module d'extension doit fournir un nom unique qui le décrit. Le nom est utilisé lors de [l'affichage des messages](#logger) liés à ce module d'extension et peut être utilisé par d'autres modules d'extension pour détecter la présence de ce dernier.

## `hooks`

Les hooks sont des fonctions que Starlight appelle pour exécuter le code du module d'extension à des moments spécifiques.

Pour référencer le type des arguments d'un hook, utilisez le type utilitaire `HookParameters` et passez le nom du hook.
Dans l'exemple suivant, le paramètre `options` est typé pour correspondre aux arguments passés au hook `config:setup` :

```ts
import type { HookParameters } from '@astrojs/starlight/types';

function configSetup(options: HookParameters['config:setup']) {
  options.useTranslations('fr');
}
```

### `i18n:setup`

Fonction de configuration de l'internationalisation du module d'extension appelée lorsque Starlight est initialisé.
Le hook `i18n:setup` peut être utilisé pour injecter des traductions afin que le module d'extension puisse prendre en charge différentes locales.
Ces traductions seront disponibles via [`useTranslations()`](#usetranslations) dans le hook `config:setup` et dans les composants d'interface utilisateur via [`Astro.locals.t()`](/fr/guides/i18n/#utiliser-les-traductions-de-linterface-utilisateur).

Le hook `i18n:setup` est appelé avec les options suivantes :

#### `injectTranslations`

**Type :** `(translations: Record<string, Record<string, string>>) => void`

Une fonction appelée pour ajouter ou mettre à jour des chaînes de traduction utilisées dans les [API de localisation](/fr/guides/i18n/#utiliser-les-traductions-de-linterface-utilisateur) de Starlight.

Dans l'exemple suivant, un module d'extension injecte des traductions pour une chaîne d'interface utilisateur personnalisée nommée `myPlugin.doThing` pour les locales `en` et `fr` :

```ts {6-13} /(injectTranslations)[^(]/
// plugin.ts
export default {
  name: 'plugin-avec-traductions',
  hooks: {
    'i18n:setup'({ injectTranslations }) {
      injectTranslations({
        en: {
          'myPlugin.doThing': 'Do the thing',
        },
        fr: {
          'myPlugin.doThing': 'Faire le truc',
        },
      });
    },
  },
};
```

Pour utiliser les traductions injectées dans l'interface utilisateur de votre module d'extension, suivez le [guide « Utiliser les traductions de l'interface utilisateur »](/fr/guides/i18n/#utiliser-les-traductions-de-linterface-utilisateur).
Si vous avez besoin d'accéder aux traductions dans le contexte du hook [`config:setup`](#configsetup) de votre module d'extension, vous pouvez utiliser la fonction [`useTranslations()`](#usetranslations).

Le typage des chaînes de traduction injectées pour un module d'extension est généré automatiquement dans le projet d'un utilisateur, mais n'est pas encore disponible lors du développement dans le code source de votre module d'extension.
Pour typer l'objet `locals.t` dans le contexte de votre module d'extension, déclarez les espaces de noms globaux suivants dans un fichier de déclaration TypeScript :

```ts
// env.d.ts
declare namespace App {
  type StarlightLocals = import('@astrojs/starlight').StarlightLocals;
  // Definit l'objet `locals.t` dans le contexte d'un module d'extension.
  interface Locals extends StarlightLocals {}
}

declare namespace StarlightApp {
  // Define les traductions supplémentaires du module d'extension dans l'interface `I18n`.
  interface I18n {
    'myPlugin.doThing': string;
  }
}
```

Vous pouvez également inférer le typage de l'interface `StarlightApp.I18n` à partir d'un fichier source si vous avez un objet contenant vos traductions.

Par exemple, étant donné le fichier source suivant :

```ts title="ui-strings.ts"
export const UIStrings = {
  en: { 'myPlugin.doThing': 'Do the thing' },
  fr: { 'myPlugin.doThing': 'Faire le truc' },
};
```

La déclaration suivante inférerait le typage à partir des clés anglaises dans le fichier source :

```ts title="env.d.ts"
declare namespace StarlightApp {
  type UIStrings = typeof import('./ui-strings').UIStrings.en;
  interface I18n extends UIStrings {}
}
```

### `config:setup`

La fonction de configuration du module d'extension appelée lorsque Starlight est initialisé (pendant le hook [`astro:config:setup`](https://docs.astro.build/fr/reference/integrations-reference/#astroconfigsetup) de l'intégration).
Le hook `config:setup` peut être utilisé pour mettre à jour la configuration de Starlight ou ajouter des intégrations Astro.

Ce hook est appelé avec les options suivantes :

#### `config`

**Type :** `StarlightUserConfig`

Une copie en lecture seule de la [configuration de Starlight](/fr/reference/configuration/) fournie par l'utilisateur.
Cette configuration peut avoir été mise à jour par d'autres modules d'extension configurés avant celui en cours.

#### `updateConfig`

**Type :** `(newConfig: StarlightUserConfig) => void`

Une fonction de rappel pour mettre à jour la [configuration de Starlight](/fr/reference/configuration/) fournie par l'utilisateur.
Spécifiez les clés de configuration de niveau racine que vous souhaitez remplacer.
Pour mettre à jour des valeurs de configuration imbriquées, vous devez fournir l'objet imbriqué entier.

Pour étendre une option de configuration existante sans la remplacer, étendez la valeur existante dans votre nouvelle valeur.
Dans l'exemple suivant, un nouveau compte de média [`social`](/fr/reference/configuration/#social) est ajouté à la configuration existante en étendant `config.social` dans le nouveau tableau `social` :

```ts {6-15}
// module-extension.ts
export default {
  name: 'ajout-twitter-plugin',
  hooks: {
    'config:setup'({ config, updateConfig }) {
      updateConfig({
        social: [
          ...config.social,
          {
            icon: 'twitter',
            label: 'Twitter',
            href: 'https://twitter.com/astrodotbuild',
          },
        ],
      });
    },
  },
};
```

#### `addIntegration`

**Type :** `(integration: AstroIntegration) => void`

Une fonction de rappel pour ajouter une [intégration Astro](https://docs.astro.build/fr/reference/integrations-reference/) requise par le module d'extension.

Dans l'exemple suivant, le module d'extension vérifie d'abord si [l'intégration React d'Astro](https://docs.astro.build/fr/guides/integrations-guide/react/) est configurée et, si ce n'est pas le cas, utilise `addIntegration()` pour l'ajouter :

```ts {14} "addIntegration,"
// module-extension.ts
import react from '@astrojs/react';

export default {
  name: 'plugin-utilisant-react',
  hooks: {
    'config:setup'({ addIntegration, astroConfig }) {
      const isReactLoaded = astroConfig.integrations.find(
        ({ name }) => name === '@astrojs/react'
      );

      // Ajoute seulement l'intégration React si elle n'est pas déjà chargée.
      if (!isReactLoaded) {
        addIntegration(react());
      }
    },
  },
};
```

#### `addRouteMiddleware`

**Type :** `(config: { entrypoint: string; order?: 'pre' | 'post' | 'default' }) => void`

Une fonction appelée pour ajouter un [middleware de route](/fr/guides/route-data/) pour le site.

La propriété `entrypoint` doit être un spécificateur de module pour le fichier middleware de votre module d'extension qui exporte une fonction `onRequest`.

Dans l'exemple suivant, un module d'extension publié sous `@exemple/starlight-module-extension` ajoute un middleware de route utilisant un spécificateur de module npm :

```js {6-9}
// module-extension.ts
export default {
  name: '@exemple/starlight-module-extension',
  hooks: {
    'config:setup'({ addRouteMiddleware }) {
      addRouteMiddleware({
        entrypoint: '@exemple/starlight-module-extension/route-middleware',
      });
    },
  },
};
```

##### Contrôle de l'ordre d'exécution

Par défaut, le middleware du module d'extension s'exécute dans l'ordre d'ajout des modules d'extension.

Utilisez la propriété `order` facultative si vous avez besoin de plus de contrôle sur le moment où votre middleware s'exécute.
Définissez `order: "pre"` pour s'exécuter avant le middleware d'un utilisateur.
Définissez `order: "post"` pour s'exécuter après tout autre middleware.

Si deux modules d'extension ajoutent un middleware avec la même valeur `order`, le module d'extension ajouté en premier s'exécutera en premier.

#### `astroConfig`

**Type :** `AstroConfig`

Une copie en lecture seule de la [configuration d'Astro](https://docs.astro.build/fr/reference/configuration-reference/) fournie par l'utilisateur.

#### `command`

**Type :** `'dev' | 'build' | 'preview'`

La commande utilisée pour exécuter Starlight :

- `dev` - Le projet est exécuté avec `astro dev`
- `build` - Le projet est exécuté avec `astro build`
- `preview` - Le projet est exécuté avec `astro preview`

#### `isRestart`

**Type :** `boolean`

`false` lorsque le serveur de développement démarre, `true` lorsqu'un rechargement est déclenché.
Les raisons courantes d'un redémarrage incluent un utilisateur qui modifie son fichier `astro.config.mjs` pendant que le serveur de développement est en cours d'exécution.

#### `logger`

**Type :** `AstroIntegrationLogger`

Une instance du [journaliseur (logger) d'intégration Astro](https://docs.astro.build/fr/reference/integrations-reference/#astrointegrationlogger) que vous pouvez utiliser pour écrire des messages de journalisation.
Tous les messages seront préfixés par le nom du module d'extension.

```ts {6}
// module-extension.ts
export default {
  name: 'plugin-long-processus',
  hooks: {
    'config:setup'({ logger }) {
      logger.info("Démarrage d'un long processus…");
      // Un long processus…
    },
  },
};
```

L'exemple ci-dessus affichera un message qui inclut le message d'information fourni :

```plaintext frame="terminal"
[plugin-long-processus] Démarrage d'un long processus…
```

#### `useTranslations`

**Type :** `(lang: string) => I18nT`

Appelez `useTranslations()` avec une étiquette de langue BCP-47 pour générer une fonction utilitaire qui fournit l'accès aux chaînes d'interface utilisateur pour cette langue.
`useTranslations()` retourne une fonction équivalente à l'API `Astro.locals.t()` disponible dans les composants Astro.
Pour en savoir plus sur les APIs disponibles, consultez le [guide « Utiliser les traductions de l'interface utilisateur »](/fr/guides/i18n/#utiliser-les-traductions-de-linterface-utilisateur).

```ts {6}
// module-extension.ts
export default {
  name: 'plugin-utilisant-traductions',
  hooks: {
    'config:setup'({ useTranslations, logger }) {
      const t = useTranslations('zh-CN');
      logger.info(t('builtWithStarlight.label'));
    },
  },
};
```

L'exemple ci-dessus affichera un message qui inclut une chaîne d'interface utilisateur intégrée pour la langue chinoise simplifiée :

```shell
[plugin-utilisant-traductions] 基于 Starlight 构建
```

#### `absolutePathToLang`

**Type :** `(path: string) => string`

Appelez `absolutePathToLang()` avec un chemin de fichier absolu pour obtenir la langue de ce fichier.

Cela peut être particulièrement utile lors de l'ajout de [modules d'extension remark ou rehype](https://docs.astro.build/fr/guides/markdown-content/#modules-dextension-markdown) pour traiter les fichiers Markdown ou MDX.
Le [format de fichier virtuel](https://github.com/vfile/vfile) utilisé par ces modules d'extension inclut le [chemin absolu](https://github.com/vfile/vfile#filepath) du fichier en cours de traitement, qui peut être utilisé avec `absolutePathToLang()` pour déterminer la langue du fichier.
La langue retournée peut être utilisé avec l'utilitaire [`useTranslations()`](#usetranslations) pour obtenir des chaînes d'interface utilisateur pour cette langue.

Par exemple, étant donné la configuration de Starlight suivante :

```js
starlight({
  title: 'Ma documentation',
  defaultLocale: 'fr',
  locales: {
    // Documentation en anglais dans `src/content/docs/en/`
    en: { label: 'English' },
    // Documentation en français dans `src/content/docs/fr/`
    fr: { label: 'Français', lang: 'fr' },
  },
});
```

Un module d'extension peut déterminer la langue d'un fichier en utilisant son chemin absolu :

```ts {6-8} //(en)//
// module-extension.ts
export default {
  name: 'plugin-utilisant-traductions',
  hooks: {
    'config:setup'({ absolutePathToLang, useTranslations, logger }) {
      const lang = absolutePathToLang(
        '/chemin/absolu/vers/projet/src/content/docs/en/index.mdx'
      );
      const t = useTranslations(lang);
      logger.info(t('aside.tip'));
    },
  },
};
```

L'exemple ci-dessus affichera un message qui inclut une chaîne d'interface utilisateur intégrée pour la langue anglaise :

```shell
[plugin-utilisant-traductions] Tip
```


================================================
FILE: docs/src/content/docs/fr/reference/route-data.mdx
================================================
---
title: Référence des données de route
description: La documentation de référence complète pour l'objet de données de route de Starlight.
---

L'objet de données de route de Starlight contient des informations sur la page courante.
Apprenez-en plus sur le fonctionnement du modèle de données de Starlight dans le [guide « Données de route »](/fr/guides/route-data/).

Dans les composants Astro, accédez aux données de route à partir de `Astro.locals.starlightRoute` :

```astro {4}
---
// src/components/Custom.astro

const { hasSidebar } = Astro.locals.starlightRoute;
---
```

Dans un [middleware de route](/fr/guides/route-data/#personnalisation-des-données-de-route), accédez aux données de route à partir de l'objet de contexte passé à votre fonction middleware :

```ts {5}
// src/routeData.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

export const onRequest = defineRouteMiddleware((context) => {
	const { hasSidebar } = context.locals.starlightRoute;
});
```

## `starlightRoute`

L'objet `starlightRoute` contient les propriétés suivantes :

### `dir`

**Type :** `'ltr' | 'rtl'`

Le sens d’écriture de la page.

### `lang`

**Type :** `string`

L'étiquette d'identification BCP-47 pour la langue de la page, par exemple `en`, `zh-CN` ou `pt-BR`.

### `locale`

**Type :** `string | undefined`

Le chemin de base utilisé pour servir une langue. `undefined` pour les slugs de la locale racine.

### `siteTitle`

**Type :** `string`

Le titre du site pour la langue de cette page.

### `siteTitleHref`

**Type :** `string`

La valeur de l'attribut `href` du titre du site, renvoyant à la page d'accueil, par exemple `/`.
Pour les sites multilingues, cette valeur inclura la locale actuelle, par exemple `/fr/` ou `/zh-cn/`.

### `slug`

**Type :** `string`

Le slug de la page généré à partir du nom du fichier du contenu.

Cette propriété est dépréciée et sera supprimée dans une version future de Starlight.
Migrez vers la nouvelle API Content Layer en utilisant le [`docsLoader` de Starlight](/fr/manual-setup/#configurer-les-collections-de-contenu) et utilisez la propriété [`id`](#id) à la place.

### `id`

**Type :** `string`

Le slug de cette page ou l'identifiant unique de cette page basé sur le nom du fichier du contenu si l'option [`legacy.collections`](https://docs.astro.build/fr/reference/legacy-flags/#collections) est utilisée.

### `isFallback`

**Type :** `boolean | undefined`

`true` si cette page n'est pas traduite dans la langue actuelle et utilise le contenu de la langue par défaut en tant que repli.
Utilisé uniquement dans les sites multilingues.

### `entryMeta`

**Type :** `{ dir: 'ltr' | 'rtl'; lang: string }`

Métadonnées de la locale pour le contenu de la page. Peut être différent des valeurs de locale de premier niveau lorsque la page utilise un contenu de repli.

### `entry`

L'entrée de la collection de contenu Astro pour la page courante.
Inclut les valeurs du frontmatter pour la page courante dans `entry.data`.

```ts
entry: {
	data: {
		title: string;
		description: string | undefined;
		// etc.
	}
}
```

Pour en savoir plus sur le format de cet objet, consultez la [référence du type d'entrée de collection](https://docs.astro.build/fr/reference/modules/astro-content/#collectionentry).

### `sidebar`

**Type :** `SidebarEntry[]`

Les entrées de la barre latérale de navigation du site pour cette page.

### `hasSidebar`

**Type :** `boolean`

Indique si la barre latérale est affichée sur cette page.

### `pagination`

**Type :** `{ prev?: Link; next?: Link }`

Liens vers la page précédente et suivante dans la barre latérale si celle-ci est activée.

### `toc`

**Type :** `{ minHeadingLevel: number; maxHeadingLevel: number; items: TocItem[] } | undefined`

Table des matières de la page courante si celle-ci est activée.

### `headings`

**Type :** `{ depth: number; slug: string; text: string }[]`

Un tableau de toutes les en-têtes Markdown extraites de la page courante.
Utilisez [`toc`](#toc) à la place si vous souhaitez construire un composant de table des matières qui respecte les options de configuration de Starlight.

### `lastUpdated`

**Type :** `Date | undefined`

Un objet JavaScript de type `Date` représentant la date de dernière mise à jour de cette page si cette fonctionnalité est activée.

### `editUrl`

**Type :** `URL | undefined`

Un objet `URL` de l'adresse où cette page peut être modifiée si cette fonctionnalité est activée.

### `head`

**Type :** [`HeadConfig[]`](/fr/reference/configuration/#headconfig)

Tableau de toutes les balises à inclure à l’intérieur de l’élément `<head>` de la page courante.
Inclut des balises importantes comme `<title>` et `<meta charset="utf-8">`.

## Utilitaires

### `defineRouteMiddleware()`

Utilisez l'utilitaire `defineRouteMiddleware()` pour vous aider à typer votre module de middleware de route :

```ts "defineRouteMiddleware"
// src/routeData.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

export const onRequest = defineRouteMiddleware((context) => {
	// ...
});
```

### Type `StarlightRouteData`

Si vous écrivez du code qui utilise les données de route de Starlight, vous pouvez importer le type `StarlightRouteData` qui correspond au format de `Astro.locals.starlightRoute`.

Dans l'exemple suivant, une fonction `usePageTitleInTOC()` met à jour les données de route pour utiliser le titre de la page courante comme libellé du premier élément de la table des matières, remplaçant le libellé par défaut « Sur cette page ».
Le type `StarlightRouteData` vous permet de vérifier si les modifications des données de route sont valides.

```ts "StarlightRouteData"
// src/route-utils.ts
import type { StarlightRouteData } from '@astrojs/starlight/route-data';

export function usePageTitleInTOC(starlightRoute: StarlightRouteData) {
	const overviewLink = starlightRoute.toc?.items[0];
	if (overviewLink) {
		overviewLink.text = starlightRoute.entry.data.title;
	}
}
```

Cette fonction peut ensuite être appelée à partir d'un middleware de route :

```ts {3,6}
// src/route-middleware.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';
import { usePageTitleInTOC } from './route-utils';

export const onRequest = defineRouteMiddleware((context) => {
	usePageTitleInTOC(context.locals.starlightRoute);
});
```


================================================
FILE: docs/src/content/docs/fr/resources/community-content.mdx
================================================
---
title: Contenu communautaire
description: Découvrez les guides, articles et vidéos produits par la communauté pour vous aider à apprendre et à créer avec Starlight !
---

:::tip[Ajoutez le vôtre !]
Avez-vous produit du contenu sur Starlight ?
Ouvrez une PR ajoutant un lien à cette page !
:::

import { CardGrid, LinkCard } from '@astrojs/starlight/components';

## Articles et revues

Voici une collection de publications et d'articles pour en apprendre plus sur Starlight et les expériences d'autres personnes :

<CardGrid>
	<LinkCard
		href="https://devm.io/open-source/starlight-astro"
		title="Génération de sites statiques avec Starlight"
		description="« Aucune idée n'est trop grande ou trop petite lors de la conception de composants » — une entrevue avec Chris Swithinbank, responsable de Starlight"
	/>
	<LinkCard
		href="https://frontendatscale.com/blog/hybrid-frontend-architecture/"
		title="Une architecture frontend hybride avec Astro et Starlight"
		description="Maxi Ferreira et Ben Holmes construisent un site de documentation avec Starlight, TinaCMS et une aire de test interactive avec authentification pour une API."
	/>
	<LinkCard
		href="https://www.olets.dev/posts/comparing-docs-site-builders-vuepress-vs-starlight/"
		title="Comparaison des générateurs de sites de documentation : VuePress contre Starlight"
		description="Comment les deux frameworks se comparent-ils ?"
	/>
	<LinkCard
		href="https://astro.build/case-studies/wp-engine/"
		title="Étude de cas : Réduction des coûts de développement"
		description="Comment WP Engine a réduit ses coûts de développement par plus de 50 % avec Astro Starlight."
	/>
	<LinkCard
		href="https://maciekpalmowski.dev/blog/building-a-documentation-site-using-astro-starlight/"
		title="Construction d'un site de documentation avec Astro Starlight"
		description="Maciek Palmowski décrit comment Patchstack a migré sa documentation vers Starlight"
	/>
	<LinkCard
		href="https://blog.cloudflare.com/open-source-all-the-way-down-upgrading-our-developer-documentation/"
		title="Open source du début à la fin"
		description="Comment Cloudflare a utilisé Starlight pour mettre à jour sa documentation pour les développeurs."
	/>
	<LinkCard
		href="https://starlight-changelog.netlify.app/"
		title="Starlight Changelog"
		description="Consulter l'ensemble des versions du paquet @astrojs/starlight sur une seule magnifique page."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/contributing-to-starlight"
		title="Contribuer à Starlight"
		description="Mon expérience personnelle et mes suggestions pour contribuer à des projets open source comme Starlight."
	/>
</CardGrid>

## Recettes et guides

Les recettes sont généralement des guides courts et ciblés qui guident un lecteur à travers l'exécution d'un exemple de travail pour une tâche spécifique. Les recettes sont un excellent moyen d'ajouter de nouvelles fonctionnalités ou un nouveau comportement à votre projet Starlight en suivant des instructions étape par étape ! D'autres guides peuvent expliquer des concepts liés à un domaine spécifique, comme l'utilisation d'images ou l'utilisation de MDX.

Explorez le contenu communautaire produit par les utilisateurs de Starlight :

<CardGrid>
	<LinkCard
		href="https://www.webpro.nl/scraps/versioned-docs-with-starlight-and-vercel"
		title="Documentation versionnée avec Starlight et Vercel"
		description="Un guide pour mettre en place des versions séparées d'une documentation pour chaque version majeure d'un projet."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-heading-links"
		title="Ajouter des liens aux titres de Starlight"
		description="Un guide pour utiliser un module d'extension rehype pour partager des liens vers des sections spécifiques de votre documentation."
	/>
	<LinkCard
		href="https://blog.otterlord.dev/posts/starlight-sponsors/"
		title="Ajouter des sponsors à votre site Starlight"
		description="Un guide pour mettre en place un composant de sponsors personnalisé dans la barre latérale de votre documentation."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-og-images"
		title="Ajouter des images Open Graph à Starlight"
		description="Un guide pour générer des images sociales et les balises de métadonnées correspondantes pour vos pages."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-third-party-icon-sets"
		title="Utiliser des ensembles d'icônes tiers dans Starlight"
		description="Un guide pour utiliser unplugin-icons pour étendre la sélection d'icônes disponibles pour Starlight."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-custom-html-head"
		title="Éditer l'en-tête HTML des pages Starlight"
		description="Apprenez à ajouter du contenu d'en-tête commun tel que des analyses d'audience Web, des polices et des scripts."
	/>
	<LinkCard
		href="https://dev.to/mrrobot/publishing-documentation-with-astro-starlight-691"
		title="Publier une documentation avec Astro Starlight"
		description="Démarrer une documentation avec Starlight."
	/>
	<LinkCard
		href="https://events-3bg.pages.dev/jotter/starlight/"
		title="Utiliser les transitions de vue (view transitions)"
		description="Ajoutez la prise en charge des transitions de vue, du routage côté client et de la navigation monopage (SPA) à votre site de documentation Starlight."
	/>
	<LinkCard
		href="https://jamcomments.com/posts/structured-data-with-starlight"
		title="Ajout de données structurées aux pages Starlight"
		description="Apprenez à créer des données structurées JSON-LD dynamiques pour vos pages de documentation."
	/>
	<LinkCard
		href="https://starlight-examples.netlify.app/"
		title="Exemples Starlight"
		description="Collection de ressources StackBlitz démontrant par la pratique comment mettre en place diverses fonctionnalités dans des sites de documentation Starlight."
	/>
	<LinkCard
		href="https://hideoo.dev/notebooks/starlight-plugins-by-example"
		title="Modules d'extension Starlight par l'exemple"
		description="Une collection de notes et d'exemples sur les modules d'extension Starlight et techniques couramment utilisées pour les construire."
	/>
	<LinkCard
		href="https://blog.trueberryless.org/blog/starlight-progress-indicator/"
		title="Ajouter un indicateur de progression de lecture"
		description="Découvrez comment ajouter une barre de progression de lecture horizontale à votre site Starlight."
	/>
	<LinkCard
		href="https://blog.trueberryless.org/blog/starlight-sidebar-whitespace/"
		title="Appliquer des styles personnalisés à votre barre latérale Starlight"
		description="En utilisant un peu de CSS pour ajuster les polices, les couleurs et d'autres éléments de la barre latérale de Starlight."
	/>
	<LinkCard
		href="https://blog.trueberryless.org/blog/starlight-dropdown-and-list-together/"
		title="Starlight Topics : menu déroulant de rubriques sur mobile, liste sur ordinateur"
		description="Combinez deux modules d'extension pour profiter du meilleur des deux mondes sur ordinateur et appareils mobiles."
	/>
	<LinkCard
		href="https://blog.trueberryless.org/blog/starlight-autogenerate-whole-sidebar/"
		title="Agencement de la barre latérale de Starlight avec un middleware"
		description="Utilisez un middleware de routage pour contrôler l'agencement de la barre latérale et les étiquettes de groupe, inspiré des conventions de Nuxt Content."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-custom-social-links"
		title="Ajouter des liens vers les réseaux sociaux avec des icônes personnalisées à Starlight"
		description="Découvrez comment utiliser des icônes personnalisées pour les liens vers les réseaux sociaux dans l'en-tête de votre site web Starlight."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-paste-images-with-visual-studio-code"
		title="Coller des images dans les pages Starlight avec Visual Studio Code"
		description="Améliorez votre manière de travailler avec Starlight en collant des images dans vos pages de documentation à l'aide de Visual Studio Code."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-add-diagrams-using-d2"
		title="Ajouter des diagrammes à votre documentation Starlight à l'aide de D2"
		description="Apprenez à utiliser D2 pour ajouter des diagrammes à votre documentation Starlight."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-og-images-cloudinary-astro-sdk"
		title="Générer des images Open Graph pour Starlight à l'aide du SDK Astro de Cloudinary"
		description="Découvrez comment utiliser le SDK Astro de Cloudinary pour générer des images Open Graph pour votre site web de documentation Starlight."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-list-recent-github-releases"
		title="Lister les dernières versions publiées sur GitHub dans Starlight à l'aide de l'API Content Layer d'Astro"
		description="Découvrez comment utiliser l'API Content Layer d'Astro pour lister les dernières versions publiées sur GitHub d'un projet Starlight."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-sitewide-banner"
		title="Ajouter une bannière pour l'ensemble du site avec Starlight"
		description="Découvrez comment créer une bannière pour l'ensemble du site grâce à la fonctionnalité intégrée de bannière par page de Starlight."
	/>
	<LinkCard
		href="https://lirantal.com/blog/customizing-astro-starlight-sidebar-gated-content-auth"
		title="Personnalisation de la barre latérale de Starlight pour du contenu protégé par authentification"
		description="Sécurisez votre matériel de cours en utilisant Clerk et SSR pour afficher dynamiquement des chapitres dans la barre latérale de Starlight quand l'utilisateur est connecté."
	/>
</CardGrid>

## Contenu vidéo

Découvrez des vidéos et des chaînes avec du contenu Starlight, y compris des flux en direct et du contenu éducatif.

import YouTubeGrid from '~/components/youtube-grid.astro';

### Vidéos officielles

<YouTubeGrid
	videos={[
		{
			href: 'https://www.youtube.com/watch?v=5u0Ds7wzUeI',
			title: 'Starlight par Astro',
			description: 'Regardez la vidéo de lancement officielle de Starlight',
		},
		{
			href: 'https://www.youtube.com/watch?v=j8K-ESJF814',
			title: 'Un an de Starlight !',
			description:
				"Sarah parle du thème de documentation communautaire d'Astro",
		},
	]}
/>

### Vidéos et flux communautaires

<YouTubeGrid
	videos={[
		{
			href: 'https://www.youtube.com/shorts/zjOWezSzd18',
			title: '🌟 MOINS DE 1 MINUTE',
			description:
				"Regardez Ben créer un nouveau site Starlight en moins d'une minute !",
		},
		{
			href: 'https://www.youtube.com/watch?v=sF6UcV3moZg',
			title: 'Construire une documentation avec Starlight et Astro',
			description:
				'Regardez Chris et Alex plonger au cœur de Starlight dans Coder avec CodingCat.dev',
		},
		{
			href: 'https://www.youtube.com/watch?v=sWkkHbwDeQc',
			title: 'Astro Starlight',
			description: 'Introduction à Starlight en moins de une minute',
		},
		{
			href: 'https://www.youtube.com/watch?v=-Ki-1E5gNCk',
			title:
				"Modèle de documentation Astro Starlight (créer des documentations personnalisées d'application !)",
			description:
				"Créez un nouveau site Starlight prêt à l'emploi en environ 5 minutes",
		},
		{
			href: 'https://www.youtube.com/watch?v=12o7WxjAxjM',
			title:
				'Inclure une documentation Starlight dans un projet Next.js avec des proxys',
			description:
				"Configurer un projet Starlight dans un sous-répertoire au sein d'un site Next.js",
		},
		{
			href: 'https://www.youtube.com/watch?v=5pq80drDrNs',
			title:
				"J'ai recréé la documentation de Shadcn en 30 minutes avec cet outil incroyable",
			description:
				"Dans cette vidéo, je passe en revue ce qui rend Starlight si cool et pourquoi vous voudriez l'essayer avec votre prochain projet.",
		},
		{
			href: 'https://www.youtube.com/watch?v=Q1E4Gkt63ko',
			title: 'Astro Starlight et emoji-blast avec Chris Swithinbank',
			description:
				"Chris, le créateur du thème de documentation Starlight pour Astro, m'aide à le configurer pour le nouveau site web d'emoji-blast. 🌟 🎇",
		},
	]}
/>


================================================
FILE: docs/src/content/docs/fr/resources/plugins.mdx
================================================
---
title: Modules d'extension et outils
description: Découvrez les outils communautaires comme des modules d'extension et intégrations qui étendent Starlight !
sidebar:
  order: 1
---

:::tip[Ajoutez le vôtre !]
Avez-vous construit un module d'extension ou un outil pour Starlight ?
Ouvrez une PR ajoutant un lien à cette page !
:::

## Modules d'extension

Les [modules d'extension](/fr/reference/plugins/) peuvent personnaliser la configuration, l'interface utilisateur et le comportement de Starlight, tout en étant faciles à partager et à réutiliser.
Étendez votre site avec des modules d'extension officiels maintenus par l'équipe Starlight et des modules d'extension communautaires maintenus par les utilisateurs de Starlight.

### Modules d'extension officiels

<CardGrid>
	<LinkCard
		href="/fr/guides/site-search/#algolia-docsearch"
		title="Algolia DocSearch"
		description="Remplacer Pagefind, le système de recherche par défaut, par Algolia DocSearch."
	/>
</CardGrid>

### Modules d'extension communautaires

<CardGrid>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-links-validator"
		title="starlight-links-validator"
		description="Vérifier la validité des liens dans vos pages Starlight."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-typedoc"
		title="starlight-typedoc"
		description="Générer des pages Starlight à partir de TypeScript en utilisant TypeDoc."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-blog"
		title="starlight-blog"
		description="Ajouter un blogue à votre site de documentation."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-openapi"
		title="starlight-openapi"
		description="Créer des pages de documentation à partir de spécifications OpenAPI/Swagger."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-obsidian"
		title="starlight-obsidian"
		description="Publier vos coffres (vaults) Obsidian sur votre site Starlight."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-image-zoom"
		title="starlight-image-zoom"
		description="Ajouter des fonctionnalités de zoom aux images de votre documentation."
	/>
	<LinkCard
		href="https://github.com/lorenzolewis/starlight-utils"
		title="starlight-utils"
		description="Étendre Starlight avec une collection d'utilitaires courants."
	/>
	<LinkCard
		href="https://github.com/trueberryless/starlight-view-modes"
		title="starlight-view-modes"
		description="Ajouter différents modes d'affichage à votre site web de documentation."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-versions"
		title="starlight-versions"
		description="Versionner vos pages de documentation Starlight."
	/>
	<LinkCard
		href="https://inox-tools.fryuni.dev/star-warp"
		title="star-warp"
		description="Accéder aux résultats de recherche de votre documentation à la vitesse de la lumière."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-heading-badges"
		title="starlight-heading-badges"
		description="Ajouter des badges à vos en-têtes Markdown et MDX."
	/>
	<LinkCard
		href="https://github.com/Fevol/starlight-site-graph"
		title="starlight-site-graph"
		description="Ajouter un graphe interactif de votre site dans la barre latérale de votre page."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-sidebar-topics"
		title="starlight-sidebar-topics"
		description="Diviser votre documentation en différentes sections, chacune ayant sa propre barre latérale."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-cooler-credit"
		title="starlight-cooler-credit"
		description="Ajouter de jolis crédits pour Starlight ou Astro en bas de la table des matières."
	/>
	<LinkCard
		href="https://github.com/dragomano/starlight-giscus"
		title="starlight-giscus"
		description="Ajouter des commentaires via Giscus à votre site de documentation."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-videos"
		title="starlight-videos"
		description="Enrichir votre documentation avec des guides et des cours au format vidéo."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-kbd"
		title="starlight-kbd"
		description="Documenter facilement des raccourcis clavier."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-auto-sidebar"
		title="starlight-auto-sidebar"
		description="Modifier vos groupes de barre latérale générés automatiquement."
	/>
	<LinkCard
		href="https://github.com/delucis/starlight-llms-txt"
		title="starlight-llms-txt"
		description="Ajouter des fichiers llms.txt à votre site de documentation basé sur llmstxt.org."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-toc-overview-customizer"
		title="starlight-toc-overview-customizer"
		description="Personnaliser la table des matières de Starlight avec un libellé de vue d'ensemble personnalisable."
	/>
	<LinkCard
		href="https://delucis.github.io/starlight-markdown-blocks/"
		title="starlight-markdown-blocks"
		description="Étendre la syntaxe Markdown des encarts de Starlight avec des types de blocs personnalisés."
	/>
	<LinkCard
		href="https://github.com/WindMillCode/starlight-fullview-mode"
		title="starlight-fullview-mode"
		description="Réduire les barres latérales et élargir le contenu pour une expérience plein écran."
	/>
	<LinkCard
		href="https://github.com/frostybee/starlight-scroll-to-top"
		title="starlight-scroll-to-top"
		description="Ajouter un bouton de retour en haut de page à votre site de documentation."
	/>
	<LinkCard
		href="https://github.com/frostybee/starlight-codeblock-fullscreen"
		title="starlight-codeblock-fullscreen"
		description="Ajouter la fonctionnalité de basculement en plein écran aux blocs Expressive Code de votre documentation."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-auto-drafts"
		title="starlight-auto-drafts"
		description="Ajuster le comportement par défaut des ébauches et supprimer automatiquement de la barre latérale les liens vers les ébauches en mode production."
	/>
	<LinkCard
		href="https://github.com/corsfix/starlight-contextual-menu"
		title="starlight-contextual-menu"
		description="Ajouter un menu contextuel à votre documentation Starlight."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-changelogs"
		title="starlight-changelogs"
		description="Afficher les journaux des modifications au côté de la documentation de votre projet."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-github-alerts"
		title="starlight-github-alerts"
		description="Afficher les alertes GitHub sous forme d'encarts Starlight."
	/>
	<LinkCard
		href="https://github.com/dlcastillop/starlight-page-actions"
		title="starlight-page-actions"
		description="Ajoute des boutons d'action aux pages de votre documentation."
	/>
	<LinkCard
		href="https://github.com/typesense/starlight-docsearch-typesense"
		title="starlight-docsearch-typesense"
		description="Une alternative au module d'extension officiel Algolia DocSearch reposant sur Typesense."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-sidebar-swipe/"
		title="starlight-sidebar-swipe"
		description="Rendre la barre latérale gauche accessible par glissement sur les appareils mobiles comme sur Discord Mobile."
	/>
	<LinkCard
		href="https://github.com/Rettend/starlight-plugin-icons"
		title="starlight-plugin-icons"
		description="Ajouter des icônes à Astro Starlight : barre latérale, blocs de code, arborescence de fichiers."
	/>
	<LinkCard
		href="https://github.com/dlcastillop/starlight-ui-tweaks"
		title="starlight-ui-tweaks"
		description="Étend les composants natifs avec des liens de navigation personnalisés, des publicités, des pieds de page axés marketing et un bouton de thème plus épuré."
	/>
	<LinkCard
		href="https://frostybee.github.io/starlight-tags/"
		title="starlight-tags"
		description="Ajouter des étiquettes aux pages de votre documentation Starlight pour organiser et faciliter la recherche de contenu."
	/>
	<LinkCard
		href="https://github.com/dionysuzx/starlight-copy-button"
		title="starlight-copy-button"
		description="Copier une page de documentation complète au format Markdown à l'aide d'un élégant bouton dans le titre de la page."
	/>
	<LinkCard
		href="https://frostybee.github.io/starlight-telescope/"
		title="starlight-telescope"
		description="Accéder rapidement à n'importe quelle page de votre documentation Starlight grâce à la recherche approximative et à la navigation au clavier."
	/>
	<LinkCard
		href="https://frostybee.github.io/starlight-announcement/"
		title="starlight-announcement"
		description="Ajouter des bannières d'annonce améliorées incluant la possibilité de les fermer, des variantes, une planification et un ciblage de page pour votre documentation Starlight."
	/>
</CardGrid>

## Outils et intégrations communautaires

import { CardGrid, LinkCard } from '@astrojs/starlight/components';

Ces outils et intégrations communautaires peuvent être utilisés pour ajouter des fonctionnalités à votre site Starlight.

<CardGrid>
	<LinkCard
		href="https://www.feelback.dev/blog/new-astro-starlight-integration/"
		title="FeelBack"
		description="Ajouter un système de retour d'expérience utilisateur à vos pages de documentation."
	/>
	<LinkCard
		href="https://github.com/val-town/notion-to-astro"
		title="notion-to-astro"
		description="Convertir des exports Notion en documentation Astro Starlight"
	/>
	<LinkCard
		href="https://github.com/mattjennings/astro-live-code"
		title="astro-live-code"
		description="Afficher vos blocs de code MDX sous forme de composants interactifs"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-i18n"
		title="starlight-i18n"
		description="Extension Visual Studio Code pour aider à traduire les pages Starlight."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-package-managers"
		title="starlight-package-managers"
		description="Affiche rapidement les commandes liées à npm pour plusieurs gestionnaires de paquets."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-showcases"
		title="starlight-showcases"
		description="Ensemble de composants Starlight permettant de créer des pages vitrines."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/generator-starlight-plugin"
		title="@hideoo/starlight-plugin"
		description="Un générateur pour rapidement créer des modules d'extension Starlight."
	/>
	<LinkCard
		href="https://github.com/Linkerin/starlight-to-pdf"
		title="starlight-to-pdf"
		description="Un outil en ligne de commande pour convertir des sites web Starlight en fichiers PDF."
	/>
	<LinkCard
		href="https://github.com/joesaby/astro-plantuml"
		title="astro-plantuml"
		description="Générer le contenu PlantUML dans les blocs de code Markdown."
	/>
	<LinkCard
		href="https://github.com/joesaby/astro-mermaid"
		title="astro-mermaid"
		description="Générer du contenu Mermaid côté client dans des blocs de code Markdown."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/astro-d2"
		title="astro-d2"
		description="Transformer des blocs de code Markdown utilisant D2 en diagrammes."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-links"
		title="starlight-links"
		description="Extension Visual Studio Code fournissant IntelliSense pour les liens présents dans les contenus Markdown et MDX de Starlight."
	/>
	<LinkCard
		href="https://docs.contentisland.net/templates/starlight/"
		title="contentisland-cli"
		description="Connecter et synchroniser votre projet Starlight avec le CMS headless Content Island pour modifier et gérer votre documentation."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-sidebar-topics-dropdown"
		title="starlight-sidebar-topics-dropdown"
		description="Diviser vos pages de documentation en plusieurs sous-pages et passer de l'une à l'autre à l'aide d'un menu déroulant dans la barre latérale."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-save-file-component"
		title="starlight-save-file-component"
		description="Afficher rapidement un lien vers une ressource téléchargeable sur votre site Starlight."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-contributor-list"
		title="starlight-contributor-list"
		description="Afficher la liste de tous les contributeurs de votre projet."
	/>
</CardGrid>


================================================
FILE: docs/src/content/docs/fr/resources/showcase.mdx
================================================
---
title: Vitrine Starlight
description: Découvrez les sites construits avec Starlight !
sidebar:
  label: Vitrine des sites
---

:::tip[Ajoutez le vôtre !]
Avez-vous construit un site Starlight ?
[Ouvrez une PR](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md#showcase) ajoutant un lien à cette page !
:::

## Sites

import ShowcaseSites from '~/components/showcase-sites.astro';

Starlight est déjà utilisé en production. Voici quelques sites sur le web :

<ShowcaseSites />

Voir tous les [dépôts publics de projets utilisant Starlight sur GitHub](https://github.com/withastro/starlight/network/dependents).


================================================
FILE: docs/src/content/docs/fr/resources/themes.mdx
================================================
---
title: Thèmes
description: Modifiez l'apparence visuelle de votre documentation avec un thème communautaire pour Starlight
tableOfContents: false
sidebar:
  order: 2
head:
  - tag: style
    content: |
      body { --sl-content-width: 66.75rem; }
---

import ThemeGrid from '~/components/theme-grid.astro';

Un thème est un module d'extension Starlight qui modifie l'apparence visuelle d'un site avec du [CSS personnalisé](/fr/guides/css-and-tailwind/), des [redéfinitions de composants](/fr/guides/overriding-components/), ou d'autres nouvelles fonctionnalités.

### Thèmes communautaires

Installez un thème créé par la communauté pour personnaliser rapidement l'apparence de votre site.

Découvrez ci-dessous un aperçu de tous les thèmes ou essayez-les de manière interactive sur le [site de démonstration de Starlight Themes](https://starlight-themes.netlify.app/).

<ThemeGrid
	labels={{
		/** Accessible label for the theme toggle. */
		legend: 'Aperçu',
		/** Accessible label for the dark color scheme variant. */
		dark: 'Sombre',
		/** Accessible label for the light color scheme variant. */
		light: 'Clair',
	}}
	themes={[
		{
			title: 'Starlight Rapide',
			description:
				'Thème Starlight inspiré du thème Vitesse pour Visual Studio Code.',
			href: 'https://starlight-theme-rapide.vercel.app/',
			previews: { light: 'rapide-light.png', dark: 'rapide-dark.png' },
		},
		{
			title: 'Starlight Obsidian',
			description:
				"Thème Starlight inspiré par le style des sites d'Obsidian Publish.",
			href: 'https://fevol.github.io/starlight-theme-obsidian/',
			previews: { light: 'obsidian-light.png', dark: 'obsidian-dark.png' },
		},
		{
			title: 'Catppuccin for Starlight',
			description: 'Thème apaisant aux couleurs pastel pour Starlight.',
			href: 'https://starlight.catppuccin.com/',
			previews: { light: 'catppuccin-light.png', dark: 'catppuccin-dark.png' },
		},
		{
			title: 'Ion',
			description: 'Un thème élégant et moderne pour Starlight.',
			href: 'https://louisescher.github.io/starlight-ion-theme/',
			previews: { light: 'ion-light.png', dark: 'ion-dark.png' },
		},
		{
			title: 'Starlight Black',
			description: 'Thème Starlight inspiré par la doc de shadcn.',
			href: 'https://starlight-theme-black.vercel.app/',
			previews: { light: 'black-light.png', dark: 'black-dark.png' },
		},
		{
			title: 'Starlight Flexoki',
			description:
				'Un thème chaleureux et convivial basé sur la palette de couleurs Flexoki.',
			href: 'https://delucis.github.io/starlight-theme-flexoki/',
			previews: { light: 'flexoki-light.png', dark: 'flexoki-dark.png' },
		},
		{
			title: 'Starlight Nova',
			description: 'Un superbe thème moderne pour Starlight.',
			href: 'https://starlight-theme-nova.pages.dev/',
			previews: { light: 'nova-light.png', dark: 'nova-dark.png' },
		},
		{
			title: 'Starlight Next.js',
			description: 'Thème Starlight inspiré par la documentation de Next.js.',
			href: 'https://starlight-theme-next.trueberryless.org/',
			previews: { light: 'nextjs-light.png', dark: 'nextjs-dark.png' },
		},
		{
			title: 'Starlight Galaxy',
			description:
				'Un thème Astro Starlight conçu pour la publication de documentation et de contenu éducatif.',
			href: 'https://frostybee.github.io/starlight-theme-galaxy/',
			previews: { light: 'galaxy-light.png', dark: 'galaxy-dark.png' },
		},
		{
			title: 'Starlight Page',
			description:
				'Un thème Starlight intuitif et moderne avec des animations fluides et de subtiles transitions.',
			href: 'https://pelagornis-page.netlify.app/',
			previews: { light: 'page-light.png', dark: 'page-dark.png' },
		},
		{
			title: 'Starlight Gruvbox',
			description: 'Thème groove et rétro pour Starlight',
			href: 'https://starlight-theme-gruvbox.otterlord.dev/',
			previews: { light: 'gruvbox-light.png', dark: 'gruvbox-dark.png' },
		},
		{
			title: 'Starlight Six',
			description: 'Thème Starlight épuré et moderne par Six Technology',
			href: 'https://six-tech.github.io/Six.StarlightTheme/',
			previews: { light: 'six-light.png', dark: 'six-dark.png' },
		},
		{
			title: 'Starlight Vintage',
			description:
				"Un thème Starlight fortement inspiré du design intemporel de l'ancienne documentation d'Astro.",
			href: 'https://starlight-theme-vintage.netlify.app/',
			previews: { light: 'vintage-light.png', dark: 'vintage-dark.png' },
		},
		{
			title: 'Starlight Rosé Pine',
			description: 'Ambiance Soho pour Starlight.',
			href: 'https://starlight-theme-rose-pine.trueberryless.org/',
			previews: { light: 'rose-pine-light.png', dark: 'rose-pine-dark.png' },
		},
	]}
/>

:::tip[Ajoutez le vôtre !]
Avez-vous construit un thème pour Starlight ?
[Ouvrez une PR](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md#themes) ajoutant votre thème à cette page !
:::


================================================
FILE: docs/src/content/docs/getting-started.mdx
================================================
---
title: Getting Started
description: Learn how to start building your next documentation site with Starlight by Astro.
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

Starlight is a full-featured documentation theme built on top of the [Astro](https://astro.build) framework.
This guide will help you get started with a new project.
See the [manual setup instructions](/manual-setup/) to add Starlight to an existing Astro project.

## Quick Start

### Create a new project

Create a new Astro + Starlight project by running the following command in your terminal:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight
```

</TabItem>
</Tabs>

This will create a new [project directory](/guides/project-structure/) with all the necessary files and configurations for your site.

:::tip[See it in action]
Try Starlight in your browser:
[open the template on StackBlitz](https://stackblitz.com/github/withastro/starlight/tree/main/examples/basics).
:::

### Start the development server

When working locally, [Astro’s development server](https://docs.astro.build/en/reference/cli-reference/#astro-dev) lets you preview your work and automatically refreshes your browser when you make changes.

Inside your project directory, run the following command to start the development server:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm run dev
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dev
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dev
```

</TabItem>
</Tabs>

This will log a message to your terminal with the URL of your local preview.
Open this URL to start browsing your site.

### Add content

Starlight is ready for you to add new content, or bring your existing files!

Add new pages to your site by creating Markdown files in the `src/content/docs/` directory.

Read more about file-based routing and support for MDX and Markdoc files in the [“Pages”](/guides/pages/) guide.

### Next steps

- **Configure:** Learn about common options in [“Customizing Starlight”](/guides/customization/).
- **Navigate:** Set up your sidebar with the [“Sidebar Navigation”](/guides/sidebar/) guide.
- **Components:** Discover built-in cards, tabs, and more in the [“Components”](/components/using-components/) guide.
- **Extend:** Explore community add-ons in our [“Plugins”](/resources/plugins/) and [“Themes”](/resources/themes/) catalogs.
- **Deploy:** Publish your work with the [“Deploy your site”](https://docs.astro.build/en/guides/deploy/) guide in the Astro docs.

## Updating Starlight

:::tip
Because Starlight is beta software, there will be frequent updates and improvements.
Be sure to update Starlight regularly!
:::

Starlight is an Astro integration. You can update it and other Astro packages by running the following command in your terminal:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npx @astrojs/upgrade
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dlx @astrojs/upgrade
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dlx @astrojs/upgrade
```

</TabItem>
</Tabs>

See the [Starlight changelog](https://github.com/withastro/starlight/blob/main/packages/starlight/CHANGELOG.md) for a full list of the changes made in each release.

## Troubleshooting Starlight

Use the [project configuration](/reference/configuration/) and [individual page frontmatter configuration](/reference/frontmatter/) reference pages to ensure that your Starlight site is configured and functioning properly.
See the guides in the sidebar for help adding content and customizing your Starlight site.

If your answer cannot be found in these docs, please visit the [full Astro Docs](https://docs.astro.build) for complete Astro documentation.
Your question may be answered by understanding how Astro works in general, underneath this Starlight theme.

You can also check for any known [Starlight issues on GitHub](https://github.com/withastro/starlight/issues), and get help in the [Astro Discord](https://astro.build/chat/) from our active, friendly community! Post questions in our `#support` forum with the "starlight" tag, or visit our dedicated `#starlight` channel to discuss current development and more!


================================================
FILE: docs/src/content/docs/guides/authoring-content.mdx
================================================
---
title: Authoring Content in Markdown
description: An overview of the Markdown syntax Starlight supports.
---

Starlight supports the full range of [Markdown](https://daringfireball.net/projects/markdown/) syntax in `.md` files as well as frontmatter [YAML](https://dev.to/paulasantamaria/introduction-to-yaml-125f) to define metadata such as a title and description.

Please be sure to check the [MDX docs](https://mdxjs.com/docs/what-is-mdx/#markdown) or [Markdoc docs](https://markdoc.dev/docs/syntax) if using those file formats, as Markdown support and usage can differ.

## Frontmatter

You can customize individual pages in Starlight by setting values in their frontmatter.
Frontmatter is set at the top of your files between `---` separators:

```md title="src/content/docs/example.md"
---
title: My page title
---

Page content follows the second `---`.
```

Every page must include at least a `title`.
See the [frontmatter reference](/reference/frontmatter/) for all available fields and how to add custom fields.

## Inline styles

Text can be **bold**, _italic_, or ~~strikethrough~~.

```md
Text can be **bold**, _italic_, or ~~strikethrough~~.
```

You can [link to another page](/getting-started/).

```md
You can [link to another page](/getting-started/).
```

You can highlight `inline code` with backticks.

```md
You can highlight `inline code` with backticks.
```

## Images

Images in Starlight use [Astro’s built-in optimized asset support](https://docs.astro.build/en/guides/images/).

Markdown and MDX support the Markdown syntax for displaying images that includes alt-text for screen readers and assistive technology.

![An illustration of planets and stars featuring the word “astro”](https://raw.githubusercontent.com/withastro/docs/main/public/default-og-image.png)

```md
![An illustration of planets and stars featuring the word “astro”](https://raw.githubusercontent.com/withastro/docs/main/public/default-og-image.png)
```

Relative image paths are also supported for images stored locally in your project.

```md
// src/content/docs/page-1.md

![A rocketship in space](../../assets/images/rocket.svg)
```

## Headings

You can structure content using a heading. Headings in Markdown are indicated by a number of `#` at the start of the line.

### How to structure page content in Starlight

Starlight is configured to automatically use your page title as a top-level heading and will include an "Overview" heading at top of each page's table of contents. We recommend starting each page with regular paragraph text content and using on-page headings from `<h2>` and down:

```md
---
title: Markdown Guide
description: How to use Markdown in Starlight
---

This page describes how to use Markdown in Starlight.

## Inline Styles

## Headings
```

### Automatic heading anchor links

Using headings in Markdown will automatically give you anchor links so you can link directly to certain sections of your page:

```md
---
title: My page of content
description: How to use Starlight's built-in anchor links
---

## Introduction

I can link to [my conclusion](#conclusion) lower on the same page.

## Conclusion

`https://my-site.com/page1/#introduction` navigates directly to my Introduction.
```

Level 2 (`<h2>`) and Level 3 (`<h3>`) headings will automatically appear in the page table of contents.

Learn more about how Astro processes heading `id`s in [the Astro Documentation](https://docs.astro.build/en/guides/markdown-content/#heading-ids)

## Asides

Asides (also known as “admonitions” or “callouts”) are useful for displaying secondary information alongside a page’s main content.

Starlight provides a custom Markdown syntax for rendering asides. Aside blocks are indicated using a pair of triple colons `:::` to wrap your content, and can be of type `note`, `tip`, `caution` or `danger`.

You can nest any other Markdown content types inside an aside, but asides are best suited to short and concise chunks of content.

### Note aside

:::note
Starlight is a documentation website toolkit built with [Astro](https://astro.build/). You can get started with this command:

```sh
npm create astro@latest -- --template starlight
```

:::

````md
:::note
Starlight is a documentation website toolkit built with [Astro](https://astro.build/). You can get started with this command:

```sh
npm create astro@latest -- --template starlight
```

:::
````

### Custom aside titles

You can specify a custom title for the aside in square brackets following the aside type, e.g. `:::tip[Did you know?]`.

:::tip[Did you know?]
Astro helps you build faster websites with [“Islands Architecture”](https://docs.astro.build/en/concepts/islands/).
:::

```md
:::tip[Did you know?]
Astro helps you build faster websites with [“Islands Architecture”](https://docs.astro.build/en/concepts/islands/).
:::
```

### Custom aside icons

You can specify a custom icon for the aside in curly brackets following the aside type or [custom title](#custom-aside-titles), e.g. `:::tip{icon="heart"}` or `:::tip[Did you know?]{icon="heart"}` respectively.
The icon name must be set to the name of [one of Starlight’s built-in icons](/reference/icons/#all-icons).

:::tip{icon="heart"}
Astro helps you build faster websites with [“Islands Architecture”](https://docs.astro.build/en/concepts/islands/).
:::

```md
:::tip{icon="heart"}
Astro helps you build faster websites with [“Islands Architecture”](https://docs.astro.build/en/concepts/islands/).
:::
```

### More aside types

Caution and danger asides are helpful for drawing a user’s attention to details that may trip them up.
If you find yourself using these a lot, it may also be a sign that the thing you are documenting could benefit from being redesigned.

:::caution
If you are not sure you want an awesome docs site, think twice before using [Starlight](/).
:::

:::danger
Your users may be more productive and find your product easier to use thanks to helpful Starlight features.

- Clear navigation
- User-configurable colour theme
- [i18n support](/guides/i18n/)

:::

```md
:::caution
If you are not sure you want an awesome docs site, think twice before using [Starlight](/).
:::

:::danger
Your users may be more productive and find your product easier to use thanks to helpful Starlight features.

- Clear navigation
- User-configurable colour theme
- [i18n support](/guides/i18n/)

:::
```

## Blockquotes

> This is a blockquote, which is commonly used when quoting another person or document.
>
> Blockquotes are indicated by a `>` at the start of each line.

```md
> This is a blockquote, which is commonly used when quoting another person or document.
>
> Blockquotes are indicated by a `>` at the start of each line.
```

## Code blocks

A code block is indicated by a block with three backticks <code>```</code> at the start and end. You can indicate the programming language being used after the opening backticks.

```js
// Javascript code with syntax highlighting.
var fun = function lang(l) {
	dateformat.i18n = require('./lang/' + l);
	return true;
};
```

````md
```js
// Javascript code with syntax highlighting.
var fun = function lang(l) {
	dateformat.i18n = require('./lang/' + l);
	return true;
};
```
````

### Expressive Code features

Starlight uses [Expressive Code](https://expressive-code.com/) to extend formatting possibilities for code blocks.
Expressive Code’s text markers and window frames plugins are enabled by default.
Code block rendering can be configured using Starlight’s [`expressiveCode` configuration option](/reference/configuration/#expressivecode).

#### Text markers

You can highlight specific lines or parts of your code blocks using [Expressive Code text markers](https://expressive-code.com/key-features/text-markers/) on the opening line of your code block.
Use curly braces (`{ }`) to highlight entire lines, and quotation marks to highlight strings of text.

There are three highlighting styles: neutral for calling attention to code, green for indicating inserted code, and red for indicating deleted code.
Both text and entire lines can be marked using the default marker, or in combination with `ins=` and `del=` to produce the desired highlighting.

Expressive Code provides several options for customizing the visual appearance of your code samples.
Many of these can be combined, for highly illustrative code samples.
Please explore the [Expressive Code documentation](https://expressive-code.com/key-features/text-markers/#configuration) for the extensive options available.
Some of the most common examples are shown below:

- [Mark entire lines & line ranges using the `{ }` marker](https://expressive-code.com/key-features/text-markers/#marking-full-lines--line-ranges):

  ```js {2-3}
  function demo() {
  	// This line (#2) and the next one are highlighted
  	return 'This is line #3 of this snippet';
  }
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```js {2-3}
  function demo() {
  	// This line (#2) and the next one are highlighted
  	return 'This is line #3 of this snippet';
  }
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```js {% meta="{2-3}" %}
  function demo() {
  	// This line (#2) and the next one are highlighted
  	return 'This is line #3 of this snippet';
  }
  ```
  ````

  </TabItem>

  </Tabs>

- [Mark selections of text using the `" "` marker or regular expressions](https://expressive-code.com/key-features/text-markers/#marking-individual-text-inside-lines):

  ```js "Individual terms" /Even.*supported/
  // Individual terms can be highlighted, too
  function demo() {
  	return 'Even regular expressions are supported';
  }
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```js "Individual terms" /Even.*supported/
  // Individual terms can be highlighted, too
  function demo() {
  	return 'Even regular expressions are supported';
  }
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```js {% meta="'Individual terms' /Even.*supported/" %}
  // Individual terms can be highlighted, too
  function demo() {
  	return 'Even regular expressions are supported';
  }
  ```
  ````

  </TabItem>

  </Tabs>

- [Mark text or lines as inserted or deleted with `ins` or `del`](https://expressive-code.com/key-features/text-markers/#selecting-inline-marker-types-mark-ins-del):

  ```js "return true;" ins="inserted" del="deleted"
  function demo() {
  	console.log('These are inserted and deleted marker types');
  	// The return statement uses the default marker type
  	return true;
  }
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```js "return true;" ins="inserted" del="deleted"
  function demo() {
  	console.log('These are inserted and deleted marker types');
  	// The return statement uses the default marker type
  	return true;
  }
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```js {% meta="'return true;' ins='inserted' del='deleted'" %}
  function demo() {
  	console.log('These are inserted and deleted marker types');
  	// The return statement uses the default marker type
  	return true;
  }
  ```
  ````

  </TabItem>

  </Tabs>

- [Combine syntax highlighting with `diff`-like syntax](https://expressive-code.com/key-features/text-markers/#combining-syntax-highlighting-with-diff-like-syntax):

  ```diff lang="js"
    function thisIsJavaScript() {
      // This entire block gets highlighted as JavaScript,
      // and we can still add diff markers to it!
  -   console.log('Old code to be removed')
  +   console.log('New and shiny code!')
    }
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```diff lang="js"
    function thisIsJavaScript() {
      // This entire block gets highlighted as JavaScript,
      // and we can still add diff markers to it!
  -   console.log('Old code to be removed')
  +   console.log('New and shiny code!')
    }
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```diff {% meta="lang='js'" %}
    function thisIsJavaScript() {
      // This entire block gets highlighted as JavaScript,
      // and we can still add diff markers to it!
  -   console.log('Old code to be removed')
  +   console.log('New and shiny code!')
    }
  ```
  ````

  </TabItem>

  </Tabs>

#### Frames and titles

Code blocks can be rendered inside a window-like frame.
A frame that looks like a terminal window will be used for shell scripting languages (e.g. `bash` or `sh`).
Other languages display inside a code editor-style frame if they include a title.

A code block’s optional title can be set either with a `title="..."` attribute following the code block's opening backticks and language identifier, or with a file name comment in the first lines of the code.

- [Add a file name tab with a comment](https://expressive-code.com/key-features/frames/#code-editor-frames)

  ```js
  // my-test-file.js
  console.log('Hello World!');
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```js
  // my-test-file.js
  console.log('Hello World!');
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````md
  ```js
  // my-test-file.js
  console.log('Hello World!');
  ```
  ````

  </TabItem>

  </Tabs>

- [Add a title to a Terminal window](https://expressive-code.com/key-features/frames/#terminal-frames)

  ```bash title="Installing dependencies…"
  npm install
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```bash title="Installing dependencies…"
  npm install
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```bash {% title="Installing dependencies…" %}
  npm install
  ```
  ````

  </TabItem>

  </Tabs>

- [Disable window frames with `frame="none"`](https://expressive-code.com/key-features/frames/#overriding-frame-types)

  ```bash frame="none"
  echo "This is not rendered as a terminal despite using the bash language"
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```bash frame="none"
  echo "This is not rendered as a terminal despite using the bash language"
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```bash {% frame="none" %}
  echo "This is not rendered as a terminal despite using the bash language"
  ```
  ````

  </TabItem>

  </Tabs>

## Details

Details (also known as “disclosures” or “accordions”) are useful to hide content that is not immediately relevant.
Users can click a short summary to expand and view the full content.

Use the standard HTML [`<details>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details) and [`<summary>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/summary) elements in your Markdown content to create a disclosure widget.

You can nest any other Markdown syntax inside a `<details>` element.

<details>
<summary>Where and when is the Andromeda constellation most visible?</summary>

The [Andromeda constellation](<https://en.wikipedia.org/wiki/Andromeda_(constellation)>) is most visible in the night sky during the month of November at latitudes between `+90°` and `−40°`.

</details>

```md
<details>
<summary>Where and when is the Andromeda constellation most visible?</summary>

The [Andromeda constellation](<https://en.wikipedia.org/wiki/Andromeda_(constellation)>) is most visible in the night sky during the month of November at latitudes between `+90°` and `−40°`.

</details>
```

## Footnotes

[Footnotes](https://www.markdownguide.org/extended-syntax/#footnotes) are useful for adding brief references or clarifications without interrupting the flow of your content. They appear as numbered superscript links that jump to referenced text collected at the bottom of the page.

Define a footnote using square brackets with a caret and numbered reference:

```md
Here is a footnote[^1] with some additional text after it.

[^1]: My reference.
```

## Other common Markdown features

Starlight supports all other Markdown authoring syntax, such as lists and tables. See the [Markdown Cheat Sheet from The Markdown Guide](https://www.markdownguide.org/cheat-sheet/) for a quick overview of all the Markdown syntax elements.

## Advanced Markdown and MDX configuration

Starlight uses Astro’s Markdown and MDX renderer built on remark and rehype. You can add support for custom syntax and behavior by adding `remarkPlugins` or `rehypePlugins` in your Astro config file. See [“Markdown Plugins”](https://docs.astro.build/en/guides/markdown-content/#markdown-plugins) in the Astro docs to learn more.

## Markdoc

Starlight supports authoring content in Markdoc using the experimental [Astro Markdoc integration](https://docs.astro.build/en/guides/integrations-guide/markdoc/) and the Starlight Markdoc preset.

### Create a new project with Markdoc

Start a new Starlight project with Markdoc pre-configured using `create astro`:

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight/markdoc
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight/markdoc
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight/markdoc
```

</TabItem>
</Tabs>

### Add Markdoc to an existing project

If you already have a Starlight site and want to add Markdoc, follow these steps.

<Steps>

1.  Add Astro’s Markdoc integration:

    <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npx astro add markdoc
    ```

    </TabItem>

    <TabItem label="pnpm">

    ```sh
    pnpm astro add markdoc
    ```

    </TabItem>

    <TabItem label="Yarn">

    ```sh
    yarn astro add markdoc
    ```

    </TabItem>

    </Tabs>

2.  Install the Starlight Markdoc preset:

    <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npm install @astrojs/starlight-markdoc
    ```

    </TabItem>

    <TabItem label="pnpm">

    ```sh
    pnpm add @astrojs/starlight-markdoc
    ```

    </TabItem>

    <TabItem label="Yarn">

    ```sh
    yarn add @astrojs/starlight-markdoc
    ```

    </TabItem>

    </Tabs>

3.  Create a Markdoc configuration file at `markdoc.config.mjs` and use the Starlight Markdoc preset:

    ```js
    import { defineMarkdocConfig } from '@astrojs/markdoc/config';
    import starlightMarkdoc from '@astrojs/starlight-markdoc';

    export default defineMarkdocConfig({
    	extends: [starlightMarkdoc()],
    });
    ```

</Steps>

To learn more about the Markdoc syntax and features, see the [Markdoc documentation](https://markdoc.dev/docs/syntax) or the [Astro Markdoc integration guide](https://docs.astro.build/en/guides/integrations-guide/markdoc/).

### Configuring the Markdoc preset

The `starlightMarkdoc()` preset accepts the following configuration options:

#### `headingLinks`

**type:** `boolean`  
**default:** `true`

Controls whether or not headings are rendered with a clickable anchor link.
Equivalent to the [`markdown.headingLinks`](/reference/configuration/#markdown) option, which applies to Markdown and MDX files.

```js "headingLinks: false"
export default defineMarkdocConfig({
	// Disable the default heading anchor link support
	extends: [starlightMarkdoc({ headingLinks: false })],
});
```


================================================
FILE: docs/src/content/docs/guides/css-and-tailwind.mdx
================================================
---
title: CSS & Styling
description: Learn how to style your Starlight site with custom CSS or integrate with Tailwind CSS.
---

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

You can style your Starlight site with custom CSS files or use the Starlight Tailwind plugin.

For a quick way to change the default style of your site, check out [community themes](/resources/themes/).

## Custom CSS styles

Customize the styles applied to your Starlight site by providing additional CSS files to modify or extend Starlight’s default styles.

<Steps>

1. Add a CSS file to your `src/` directory.
   For example, you could set a wider default column width and larger text size for page titles:

   ```css
   /* src/styles/custom.css */
   :root {
   	--sl-content-width: 50rem;
   	--sl-text-5xl: 3.5rem;
   }
   ```

2. Add the path to your CSS file to Starlight’s `customCss` array in `astro.config.mjs`:

   ```diff lang="js"
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Docs With Custom CSS',
   			customCss: [
   +				// Relative path to your custom CSS file
   +				'./src/styles/custom.css',
   			],
   		}),
   	],
   });
   ```

</Steps>

You can see all the CSS custom properties used by Starlight that you can set to customize your site in the [`props.css` file on GitHub](https://github.com/withastro/starlight/blob/main/packages/starlight/style/props.css).

### Cascade layers

Starlight uses [cascade layers](https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Cascade_layers) internally to manage the order of its styles.
This ensures a predictable CSS order and allows for simpler overrides.
Any custom unlayered CSS will override the default Starlight styles.

If you are using cascade layers, you can use [`@layer`](https://developer.mozilla.org/en-US/docs/Web/CSS/@layer) in your custom CSS to define the order of precedence for different layers relative to styles from the `starlight` layer:

```css "starlight"
/* src/styles/custom.css */
@layer my-reset, starlight, my-overrides;
```

The example above defines a custom layer named `my-reset`, applied before all Starlight layers, and another named `my-overrides`, applied after all Starlight layers.
Any styles in the `my-overrides` layer would take precedence over Starlight’s styles, but Starlight could still change styles set in the `my-reset` layer.

## Tailwind CSS

Tailwind CSS v4 support in Astro projects is provided by the [Tailwind Vite plugin](https://tailwindcss.com/docs/installation/using-vite).
Starlight provides complementary CSS to help configure Tailwind for compatibility with Starlight’s styles.

The Starlight Tailwind CSS applies the following configuration:

- Configures Tailwind’s `dark:` variants to work with Starlight’s dark mode.
- Uses Tailwind [theme colors and fonts](#styling-starlight-with-tailwind) in Starlight’s UI.
- Restores essential parts of Tailwind’s Preflight reset styles.

### Create a new project with Tailwind

Start a new Starlight project with Tailwind CSS pre-configured using `create astro`:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight/tailwind
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight/tailwind
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight/tailwind
```

</TabItem>
</Tabs>

### Add Tailwind to an existing project

If you already have a Starlight site and want to add Tailwind CSS, follow these steps.

<Steps>

1.  Set up Tailwind in your project by running the following command and following the instructions in your terminal:

    <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npx astro add tailwind
    ```

    </TabItem>

    <TabItem label="pnpm">

    ```sh
    pnpm astro add tailwind
    ```

    </TabItem>

    <TabItem label="Yarn">

    ```sh
    yarn astro add tailwind
    ```

    </TabItem>

    </Tabs>

2.  Install Starlight’s Tailwind compatibility package:

    <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npm install @astrojs/starlight-tailwind
    ```

    </TabItem>

    <TabItem label="pnpm">

    ```sh
    pnpm add @astrojs/starlight-tailwind
    ```

    </TabItem>

    <TabItem label="Yarn">

    ```sh
    yarn add @astrojs/starlight-tailwind
    ```

    </TabItem>

    </Tabs>

3.  Replace the contents of the `src/styles/global.css` file scaffolded by Astro for compatibility with Starlight:

    ```css
    /* src/styles/global.css */
    @layer base, starlight, theme, components, utilities;

    @import '@astrojs/starlight-tailwind';
    @import 'tailwindcss/theme.css' layer(theme);
    @import 'tailwindcss/utilities.css' layer(utilities);
    ```

    This Tailwind theme config defines Starlight's [cascade layers](#cascade-layers) order, imports Starlight’s Tailwind complementary CSS, and imports Tailwind’s theme and utility styles.
    If your project requires additional Tailwind configuration, check out the [“Use multiple Tailwind configurations”](#use-multiple-tailwind-configurations) section.

4.  Update the Starlight config to add the Tailwind CSS file as the first item in the `customCss` array:

    ```js ins={11-12}
    // astro.config.mjs
    import { defineConfig } from 'astro/config';
    import starlight from '@astrojs/starlight';
    import tailwindcss from '@tailwindcss/vite';

    export default defineConfig({
    	integrations: [
    		starlight({
    			title: 'Docs with Tailwind',
    			customCss: [
    				// Path to your Tailwind base styles:
    				'./src/styles/global.css',
    			],
    		}),
    	],
    	vite: { plugins: [tailwindcss()] },
    });
    ```

</Steps>

### Styling Starlight with Tailwind

When [creating a new Starlight project with Tailwind](#create-a-new-project-with-tailwind), or when [adding Tailwind to an existing Starlight project](#add-tailwind-to-an-existing-project), Starlight will use values from your [Tailwind theme config](https://tailwindcss.com/docs/theme) located in the `src/styles/global.css` file to style its UI.

If set, the following CSS custom properties will override Starlight’s default styles:

- `--color-accent-*` — used for links and current item highlighting
- `--color-gray-*` — used for background colors and borders
- `--font-sans` — used for UI and content text
- `--font-mono` — used for code examples

```css {9,11,13,25}
/* src/styles/global.css */
@layer base, starlight, theme, components, utilities;

@import '@astrojs/starlight-tailwind';
@import 'tailwindcss/theme.css' layer(theme);
@import 'tailwindcss/utilities.css' layer(utilities);

@theme {
	/* Your preferred text font. Starlight uses a system font stack by default. */
	--font-sans: 'Atkinson Hyperlegible';
	/* Your preferred code font. Starlight uses system monospace fonts by default. */
	--font-mono: 'IBM Plex Mono';
	/* Your preferred accent color. Indigo is closest to Starlight’s defaults. */
	--color-accent-50: var(--color-indigo-50);
	--color-accent-100: var(--color-indigo-100);
	--color-accent-200: var(--color-indigo-200);
	--color-accent-300: var(--color-indigo-300);
	--color-accent-400: var(--color-indigo-400);
	--color-accent-500: var(--color-indigo-500);
	--color-accent-600: var(--color-indigo-600);
	--color-accent-700: var(--color-indigo-700);
	--color-accent-800: var(--color-indigo-800);
	--color-accent-900: var(--color-indigo-900);
	--color-accent-950: var(--color-indigo-950);
	/* Your preferred gray scale. Zinc is closest to Starlight’s defaults. */
	--color-gray-50: var(--color-zinc-50);
	--color-gray-100: var(--color-zinc-100);
	--color-gray-200: var(--color-zinc-200);
	--color-gray-300: var(--color-zinc-300);
	--color-gray-400: var(--color-zinc-400);
	--color-gray-500: var(--color-zinc-500);
	--color-gray-600: var(--color-zinc-600);
	--color-gray-700: var(--color-zinc-700);
	--color-gray-800: var(--color-zinc-800);
	--color-gray-900: var(--color-zinc-900);
	--color-gray-950: var(--color-zinc-950);
}
```

### Use multiple Tailwind configurations

Multiple Tailwind configurations can be used to apply different styles to different parts of your site, e.g. when [using Starlight at a subpath](/manual-setup/#use-starlight-at-a-subpath) or when adding [custom pages](/guides/pages/#custom-pages) to your site.
For example, you may want to use Tailwind’s Preflight reset styles in your custom pages, while still applying Starlight’s compatibility layer to Starlight pages.

The following Tailwind CSS configuration sets up Tailwind without any plugins or extra configuration and can be used as a starting point for non-Starlight pages:

```css title="src/styles/custom-pages-tailwind.css"
/* Load Tailwind without any of Starlight's complementary CSS. */
@import 'tailwindcss';
```

<Steps>

1. For Starlight pages, apply your preferred Tailwind CSS configuration by following [“Add Tailwind to an existing project”](#add-tailwind-to-an-existing-project).

2. For other pages, apply your preferred Tailwind CSS configuration by importing it in those pages. This is often done in a layout component so that Tailwind styles can be used on all pages sharing that layout.
   ```astro
   ---
   // src/layouts/CustomPageLayout.astro
   import '../styles/custom-pages-tailwind.css';
   ---
   ```

</Steps>

To learn more about Tailwind theme configurations, check out the [Tailwind CSS documentation](https://tailwindcss.com/docs/theme).

## Theming

Starlight’s color theme can be controlled by overriding its default custom properties.
These variables are used throughout the UI with a range of gray shades used for text and background colors and an accent color used for links and to highlight current items in navigation.

### Color theme editor

Use the sliders below to modify Starlight’s accent and gray color palettes.
The dark and light preview areas will show the resulting colors, and the whole page will also update to preview your changes.

Use the Contrast Level option to specify which of the Web Content Accessibility Guideline [colour contrast standards](https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable/Color_contrast) to meet.

When you’re happy with your changes, copy the CSS or Tailwind code below and use it in your project.

import ThemeDesigner from '~/components/theme-designer.astro';

<ThemeDesigner
	labels={{
		presets: {
			label: 'Presets',
			ocean: 'Ocean',
			forest: 'Forest',
			oxide: 'Oxide',
			nebula: 'Nebula',
			default: 'Default',
			random: 'Random',
		},
		contrast: {
			label: 'Contrast Level',
		},
		editor: {
			accentColor: 'Accent',
			grayColor: 'Gray',
			hue: 'Hue',
			chroma: 'Chroma',
			pickColor: 'Pick color',
		},
		preview: {
			darkMode: 'Dark mode',
			lightMode: 'Light mode',
			bodyText:
				'Body text is displayed in a gray shade with a high contrast with the background.',
			linkText: 'Links are colored.',
			dimText: 'Some text, like the table of contents, has a lower contrast.',
			inlineCode: 'Inline code has a distinct background.',
		},
	}}
>
	<Fragment slot="css-docs">
		Add the following CSS to your project in a [custom CSS
		file](#custom-css-styles) to apply this theme to your site.
	</Fragment>
	<Fragment slot="tailwind-docs">
		Add the following CSS variables to the `@theme` block in your [Tailwind CSS
		file](#styling-starlight-with-tailwind) to apply this theme to your site.
	</Fragment>
</ThemeDesigner>


================================================
FILE: docs/src/content/docs/guides/customization.mdx
================================================
---
title: Customizing Starlight
description: Learn how to make your Starlight site your own with your logo, custom fonts, landing page design and more.
---

import { Tabs, TabItem, FileTree, Steps } from '@astrojs/starlight/components';

Starlight provides sensible default styling and features, so you can get started quickly with no configuration needed.
When you want to start customizing the look and feel of your Starlight site, this guide has you covered.

## Add your logo

Adding a custom logo to the site header is a quick way to add your individual branding to a Starlight site.

<Steps>

1. Add your logo image file to the `src/assets/` directory:

   <FileTree>

   - src/
     - assets/
       - **my-logo.svg**
     - content/
   - astro.config.mjs

   </FileTree>

2. Add the path to your logo as Starlight’s [`logo.src`](/reference/configuration/#logo) option in `astro.config.mjs`:

   ```diff lang="js"
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Docs With My Logo',
   			logo: {
   +				src: './src/assets/my-logo.svg',
   			},
   		}),
   	],
   });
   ```

</Steps>

By default, the logo will be displayed alongside your site’s `title`.
If your logo image already includes the site title, you can visually hide the title text by setting the `replacesTitle` option.
The `title` text will still be included for screen readers so that the header remains accessible.

```js {5}
starlight({
  title: 'Docs With My Logo',
  logo: {
    src: './src/assets/my-logo.svg',
    replacesTitle: true,
  },
}),
```

### Light and dark logo variants

You can display different versions of your logo in light and dark modes.

<Steps>

1. Add an image file for each variant to `src/assets/`:

   <FileTree>

   - src/
     - assets/
       - **light-logo.svg**
       - **dark-logo.svg**
     - content/
   - astro.config.mjs

   </FileTree>

2. Add the path to your logo variants as the `light` and `dark` options instead of `src` in `astro.config.mjs`:

   ```diff lang="js"
   starlight({
     title: 'Docs With My Logo',
     logo: {
   +    light: './src/assets/light-logo.svg',
   +    dark: './src/assets/dark-logo.svg',
     },
   }),
   ```

</Steps>

## Enable sitemap

Starlight has built-in support for generating a sitemap. Enable sitemap generation by setting your URL as `site` in `astro.config.mjs`:

```js {4}
// astro.config.mjs

export default defineConfig({
	site: 'https://stargazers.club',
	integrations: [starlight({ title: 'Site with sitemap' })],
});
```

Learn how to [add a sitemap link to `robots.txt`](https://docs.astro.build/en/guides/integrations-guide/sitemap/#sitemap-link-in-robotstxt) in the Astro Docs.

## Page layout

By default, Starlight pages use a layout with a global navigation sidebar and a table of contents that shows the current page headings.

You can apply a wider page layout without sidebars by setting [`template: splash`](/reference/frontmatter/#template) in a page’s frontmatter.
This works particularly well for landing pages and you can see it in action on the [homepage of this site](/).

```md {5}
---
# src/content/docs/index.md

title: My Landing Page
template: splash
---
```

## Table of contents

Starlight displays a table of contents on each page to make it easier for readers to jump to the heading they are looking for.
You can customize — or even disable — the table of contents globally in the Starlight integration or on a page-by-page basis in frontmatter.

By default, `<h2>` and `<h3>` headings are included in the table of contents. Change which headings levels to include site-wide using the `minHeadingLevel` and `maxHeadingLevel` options in your [global `tableOfContents`](/reference/configuration/#tableofcontents). Override these defaults on an individual page by adding the corresponding [frontmatter `tableOfContents`](/reference/frontmatter/#tableofcontents) properties:

<Tabs syncKey="config-type">
  <TabItem label="Frontmatter">

```md {4-6}
---
# src/content/docs/example.md
title: Page with only H2s in the table of contents
tableOfContents:
  minHeadingLevel: 2
  maxHeadingLevel: 2
---
```

  </TabItem>
  <TabItem label="Global config">

```js {7}
// astro.config.mjs

defineConfig({
	integrations: [
		starlight({
			title: 'Docs with custom table of contents config',
			tableOfContents: { minHeadingLevel: 2, maxHeadingLevel: 2 },
		}),
	],
});
```

  </TabItem>
</Tabs>

Disable the table of contents entirely by setting the `tableOfContents` option to `false`:

<Tabs syncKey="config-type">
  <TabItem label="Frontmatter">

```md {4}
---
# src/content/docs/example.md
title: Page without a table of contents
tableOfContents: false
---
```

  </TabItem>
  <TabItem label="Global config">

```js {7}
// astro.config.mjs

defineConfig({
	integrations: [
		starlight({
			title: 'Docs with table of contents disabled globally',
			tableOfContents: false,
		}),
	],
});
```

  </TabItem>
</Tabs>

## Social links

Starlight has built-in support for adding links to your social media accounts to the site header via the [`social`](/reference/configuration/#social) option in the Starlight integration.

Each entry in the `social` array must be an object with three properties:

- `icon`: one of Starlight’s [built-in icons](/reference/icons/), e.g. `"github"`.
- `label`: an accessible label for the link, e.g. `"GitHub"`.
- `href`: the URL for the link, e.g. `"https://github.com/withastro/starlight"`.

The following example adds links to the Astro Discord chat and the Starlight GitHub repository:

```js {9-16}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Docs With Social Links',
			social: [
				{ icon: 'discord', label: 'Discord', href: 'https://astro.build/chat' },
				{
					icon: 'github',
					label: 'GitHub',
					href: 'https://github.com/withastro/starlight',
				},
			],
		}),
	],
});
```

## Edit links

Starlight can display an “Edit page” link in each page’s footer.
This makes it easy for a reader to find the file to edit to improve your docs.
For open-source projects in particular, this can help encourage contributions from your community.

To enable edit links, set [`editLink.baseUrl`](/reference/configuration/#editlink) to the URL used to edit your repository in the Starlight integration config.
The value of `editLink.baseUrl` will be prepended to the path to the current page to form the full edit link.

Common patterns include:

- GitHub: `https://github.com/USER_NAME/REPO_NAME/edit/BRANCH_NAME/`
- GitLab: `https://gitlab.com/USER_NAME/REPO_NAME/-/edit/BRANCH_NAME/`

If your Starlight project is not in the root of your repository, include the path to the project at the end of the base URL.

This example shows the edit link configured for the Starlight docs, which live in the `docs/` subdirectory on the `main` branch of the `withastro/starlight` repository on GitHub:

```js {9-11}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Docs With Edit Links',
			editLink: {
				baseUrl: 'https://github.com/withastro/starlight/edit/main/docs/',
			},
		}),
	],
});
```

## Custom 404 page

Starlight sites display a simple 404 page by default.
You can customize this by adding a `404.md` (or `404.mdx`) file to your `src/content/docs/` directory:

<FileTree>

- src/
  - content/
    - docs/
      - **404.md**
      - index.md
- astro.config.mjs

</FileTree>

You can use all of Starlight’s page layout and customization techniques in your 404 page. For example, the default 404 page uses the [`splash` template](#page-layout) and [`hero`](/reference/frontmatter/#hero) component in frontmatter:

```md {4,6-8}
---
# src/content/docs/404.md
title: '404'
template: splash
editUrl: false
hero:
  title: '404'
  tagline: Page not found. Check the URL or try using the search bar.
---
```

### Disabling the default 404 page

If your project requires an entirely customized 404 layout, you can create a `src/pages/404.astro` route and set the [`disable404Route`](/reference/configuration/#disable404route) config option to disable Starlight’s default route:

```js {9}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Docs With Custom 404',
			disable404Route: true,
		}),
	],
});
```

## Custom fonts

By default, Starlight uses sans-serif fonts available on a user’s local device for all text.
This ensures documentation loads quickly in a font that is familiar to each user, without requiring extra bandwidth to download large font files.

If you must add a custom font to your Starlight site, you can set up fonts to use in custom CSS files or with any other [Astro styling technique](https://docs.astro.build/en/guides/styling/).

### Set up fonts

If you already have font files, follow the [local set-up guide](#set-up-local-font-files).
To use Google Fonts, follow the [Fontsource set-up guide](#set-up-a-fontsource-font).

#### Set up local font files

<Steps>

1. Add your font files to a `src/fonts/` directory and create an empty `font-face.css` file:

   <FileTree>

   - src/
     - content/
     - fonts/
       - **CustomFont.woff2**
       - **font-face.css**
   - astro.config.mjs

   </FileTree>

2. Add an [`@font-face` declaration](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face) for each of your fonts in `src/fonts/font-face.css`.
   Use a relative path to the font file in the `url()` function.

   ```css
   /* src/fonts/font-face.css */

   @font-face {
   	font-family: 'Custom Font';
   	/* Use a relative path to the local font file in `url()`. */
   	src: url('./CustomFont.woff2') format('woff2');
   	font-weight: normal;
   	font-style: normal;
   	font-display: swap;
   }
   ```

3. Add the path to your `font-face.css` file to Starlight’s `customCss` array in `astro.config.mjs`:

   ```diff lang="js"
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Docs With a Custom Typeface',
   			customCss: [
   +				// Relative path to your @font-face CSS file.
   +				'./src/fonts/font-face.css',
   			],
   		}),
   	],
   });
   ```

</Steps>

#### Set up a Fontsource font

The [Fontsource](https://fontsource.org/) project simplifies using Google Fonts and other open-source fonts.
It provides npm modules you can install for the fonts you want to use and includes ready-made CSS files to add to your project.

<Steps>

1.  Find the font you want to use in [Fontsource’s catalog](https://fontsource.org/).
    This example will use [IBM Plex Serif](https://fontsource.org/fonts/ibm-plex-serif).

2.  Install the package for your chosen font.
    You can find the package name by clicking “Install” on the Fontsource font page.

         <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npm install @fontsource/ibm-plex-serif
    ```

           </TabItem>

        <TabItem label="pnpm">

    ```sh
    pnpm add @fontsource/ibm-plex-serif
    ```

           </TabItem>

        <TabItem label="Yarn">

    ```sh
    yarn add @fontsource/ibm-plex-serif
    ```

           </TabItem>

      </Tabs>

3.  Add Fontsource CSS files to Starlight’s `customCss` array in `astro.config.mjs`:

    ```diff lang="js"
    // astro.config.mjs
    import { defineConfig } from 'astro/config';
    import starlight from '@astrojs/starlight';

    export default defineConfig({
    	integrations: [
    		starlight({
    			title: 'Docs With a Custom Typeface',
    			customCss: [
    +				// Fontsource files for to regular and semi-bold font weights.
    +				'@fontsource/ibm-plex-serif/400.css',
    +				'@fontsource/ibm-plex-serif/600.css',
    			],
    		}),
    	],
    });
    ```

    Fontsource ships multiple CSS files for each font. See the [Fontsource documentation](https://fontsource.org/docs/getting-started/install#4-weights-and-styles) on including different weights and styles to understand which to use.

</Steps>

### Use fonts

To apply the font you set up to your site, use your chosen font’s name in a [custom CSS file](/guides/css-and-tailwind/#custom-css-styles).
For example, to override Starlight’s default font everywhere, set the `--sl-font` custom property:

```css
/* src/styles/custom.css */

:root {
	--sl-font: 'IBM Plex Serif', serif;
}
```

You can also write more targeted CSS if you want to apply your font more selectively.
For example, to only set a font on the main content, but not the sidebars:

```css
/* src/styles/custom.css */

main {
	font-family: 'IBM Plex Serif', serif;
}
```

Follow the [custom CSS instructions](/guides/css-and-tailwind/#custom-css-styles) to add your styles to your site.


================================================
FILE: docs/src/content/docs/guides/i18n.mdx
================================================
---
title: Internationalization (i18n)
description: Learn how to configure your Starlight site to support multiple languages.
---

import { FileTree, Steps } from '@astrojs/starlight/components';

Starlight provides built-in support for multilingual sites, including routing, fallback content, and full right-to-left (RTL) language support.

## Configure i18n

<Steps>

1. Tell Starlight about the languages you support by passing [`locales`](/reference/configuration/#locales) and [`defaultLocale`](/reference/configuration/#defaultlocale) to the Starlight integration:

   ```js {9-26}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'My Docs',
   			// Set English as the default language for this site.
   			defaultLocale: 'en',
   			locales: {
   				// English docs in `src/content/docs/en/`
   				en: {
   					label: 'English',
   				},
   				// Simplified Chinese docs in `src/content/docs/zh-cn/`
   				'zh-cn': {
   					label: '简体中文',
   					lang: 'zh-CN',
   				},
   				// Arabic docs in `src/content/docs/ar/`
   				ar: {
   					label: 'العربية',
   					dir: 'rtl',
   				},
   			},
   		}),
   	],
   });
   ```

   Your `defaultLocale` will be used for fallback content and UI labels, so choose the language you are most likely to start writing content in, or already have content for.

2. Create a directory for each language in `src/content/docs/`.
   For example, for the configuration shown above, create the following folders:

   <FileTree>

   - src/
     - content/
       - docs/
         - ar/
         - en/
         - zh-cn/

   </FileTree>

3. You can now add content files in your language directories. Use the same file name to associate pages across languages and take advantage of Starlight’s full set of i18n features, including fallback content, translation notices, and more.

   For example, create `ar/index.md` and `en/index.md` to represent the homepage for Arabic and English respectively.

</Steps>

For more advanced i18n scenarios, Starlight also supports configuring internationalization using the [Astro’s `i18n` config](https://docs.astro.build/en/guides/internationalization/#configure-i18n-routing) option.

### Use a root locale

You can use a “root” locale to serve a language without any i18n prefix in its path. For example, if English is your root locale, an English page path would look like `/about` instead of `/en/about`.

To set a root locale, use the `root` key in your `locales` config. If the root locale is also the default locale for your content, remove `defaultLocale` or set it to `'root'`.

```js {9,11-14}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'My Docs',
			defaultLocale: 'root', // optional
			locales: {
				root: {
					label: 'English',
					lang: 'en', // lang is required for root locales
				},
				'zh-cn': {
					label: '简体中文',
					lang: 'zh-CN',
				},
			},
		}),
	],
});
```

When using a `root` locale, keep pages for that language directly in `src/content/docs/` instead of in a dedicated language folder. For example, here are the home page files for English and Chinese when using the config above:

<FileTree>

- src/
  - content/
    - docs/
      - **index.md**
      - zh-cn/
        - **index.md**

</FileTree>

#### Monolingual sites

By default, Starlight is a monolingual (English) site. To create a single language site in another language, set it as the `root` in your `locales` config:

```diff lang="js" {10-13}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'My Docs',
			locales: {
				root: {
					label: '简体中文',
					lang: 'zh-CN',
				},
			},
		}),
	],
});
```

This allows you to override Starlight’s default language without enabling other internationalization features for multi-language sites, such as the language picker.

## Fallback content

Starlight expects you to create equivalent pages in all your languages. For example, if you have an `en/about.md` file, create an `about.md` for each other language you support. This allows Starlight to provide automatic fallback content for pages that have not yet been translated.

If a translation is not yet available for a language, Starlight will show readers the content for that page in the default language (set via `defaultLocale`). For example, if you have not yet created a French version of your About page and your default language is English, visitors to `/fr/about` will see the English content from `/en/about` with a notice that this page has not yet been translated. This helps you add content in your default language and then progressively translate it when your translators have time.

## Translate the site title

By default, Starlight will use the same site title for all languages.
If you need to customize the title for each locale, you can pass an object to [`title`](/reference/configuration/#title-required) in Starlight’s options:

```diff lang="js"
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
-			title: 'My Docs',
+			title: {
+				en: 'My Docs',
+				'zh-CN': '我的文档',
+			},
			defaultLocale: 'en',
			locales: {
				en: { label: 'English' },
				'zh-cn': { label: '简体中文', lang: 'zh-CN' },
			},
		}),
	],
});
```

## Translate Starlight's UI

import LanguagesList from '~/components/languages-list.astro';
import UIStringsList from '~/components/ui-strings-list.astro';

In addition to hosting translated content files, Starlight allows you to translate the default UI strings (e.g. the "On this page" heading in the table of contents) so that your readers can experience your site entirely in the selected language.

<LanguagesList startsSentence /> translated UI strings are provided out of the
box, and we welcome [contributions to add more default
languages](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md).

You can provide translations for additional languages you support — or override our default labels — via the `i18n` data collection.

<Steps>

1. Configure the `i18n` data collection in `src/content.config.ts` if it isn’t configured already:

   ```diff lang="js" ins=/, (i18nLoader|i18nSchema)/
   // src/content.config.ts
   import { defineCollection } from 'astro:content';
   import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
   import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';

   export const collections = {
   	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
   +	i18n: defineCollection({ loader: i18nLoader(), schema: i18nSchema() }),
   };
   ```

2. Create a JSON file in `src/content/i18n/` for each additional locale you want to provide UI translation strings for.
   For example, this would add translation files for Arabic and Simplified Chinese:

   <FileTree>

   - src/
     - content/
       - i18n/
         - ar.json
         - zh-CN.json

   </FileTree>

3. Add translations for the keys you want to translate to the JSON files. Translate only the values, leaving the keys in English (e.g. `"search.label": "Buscar"`).

   These are the English defaults of the existing strings Starlight ships with:

   <UIStringsList />

   Starlight’s code blocks are powered by the [Expressive Code](https://expressive-code.com/) library.
   You can set translations for its UI strings in the same JSON file using `expressiveCode` keys:

   ```json
   {
   	"expressiveCode.copyButtonCopied": "Copied!",
   	"expressiveCode.copyButtonTooltip": "Copy to clipboard",
   	"expressiveCode.terminalWindowFallbackTitle": "Terminal window"
   }
   ```

   Starlight’s search modal is powered by the [Pagefind](https://pagefind.app/) library.
   You can set translations for Pagefind’s UI in the same JSON file using `pagefind` keys:

   ```json
   {
   	"pagefind.clear_search": "Clear",
   	"pagefind.load_more": "Load more results",
   	"pagefind.search_label": "Search this site",
   	"pagefind.filters_label": "Filters",
   	"pagefind.zero_results": "No results for [SEARCH_TERM]",
   	"pagefind.many_results": "[COUNT] results for [SEARCH_TERM]",
   	"pagefind.one_result": "[COUNT] result for [SEARCH_TERM]",
   	"pagefind.alt_search": "No results for [SEARCH_TERM]. Showing results for [DIFFERENT_TERM] instead",
   	"pagefind.search_suggestion": "No results for [SEARCH_TERM]. Try one of the following searches:",
   	"pagefind.searching": "Searching for [SEARCH_TERM]..."
   }
   ```

 </Steps>

### Extend translation schema

Add custom keys to your site’s translation dictionaries by setting `extend` in the `i18nSchema()` options.
In the following example, a new, optional `custom.label` key is added to the default keys:

```diff lang="js"
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { z } from 'astro/zod';
import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';

export const collections = {
	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
	i18n: defineCollection({
		loader: i18nLoader(),
		schema: i18nSchema({
+			extend: z.object({
+				'custom.label': z.string().optional(),
+			}),
		}),
	}),
};
```

Learn more about content collection schemas in [“Defining a collection schema”](https://docs.astro.build/en/guides/content-collections/#defining-the-collection-schema) in the Astro docs.

## Using UI translations

You can access Starlight’s [built-in UI strings](/guides/i18n/#translate-starlights-ui) as well as [user-defined](/guides/i18n/#extend-translation-schema), and [plugin-provided](/reference/plugins/#injecttranslations) UI strings through a unified API powered by [i18next](https://www.i18next.com/).
This includes support for features like [interpolation](https://www.i18next.com/translation-function/interpolation) and [pluralization](https://www.i18next.com/translation-function/plurals).

In Astro components, this API is available as part of the [global `Astro` object](https://docs.astro.build/en/reference/api-reference/#locals) as `Astro.locals.t`:

```astro title="example.astro"
<p dir={Astro.locals.t.dir()}>
	{Astro.locals.t('404.text')}
</p>
```

You can also use the API in [endpoints](https://docs.astro.build/en/guides/endpoints/), where the `locals` object is available as part of the [endpoint context](https://docs.astro.build/en/reference/api-reference/#locals):

```ts title="src/pages/404.ts"
export const GET = (context) => {
	return new Response(context.locals.t('404.text'));
};
```

In the context of a Starlight plugin, you can use the [`useTranslations()`](/reference/plugins/#usetranslations) helper to access this API for a specific language.
See the [plugins reference](/reference/plugins/) for more information.

### Rendering a UI string

Render UI strings using the `locals.t()` function.
This is an instance of i18next’s `t()` function, which takes a UI string key as its first argument and returns the corresponding translation for the current language.

For example, given a custom translation file with the following content:

```json title="src/content/i18n/en.json"
{
	"link.astro": "Astro documentation",
	"link.astro.custom": "Astro documentation for {{feature}}"
}
```

The first UI string can be rendered by passing `'link.astro'` to the `t()` function:

```astro {3}
<!-- src/components/Example.astro -->
<a href="https://docs.astro.build/">
	{Astro.locals.t('link.astro')}
</a>
<!-- Renders: <a href="...">Astro documentation</a> -->
```

The second UI string uses i18next’s [interpolation syntax](https://www.i18next.com/translation-function/interpolation) for the `{{feature}}` placeholder.
The value for `feature` must be set in an options object passed as the second argument to `t()`:

```astro {3}
<!-- src/components/Example.astro -->
<a href="https://docs.astro.build/en/guides/astro-db/">
	{Astro.locals.t('link.astro.custom', { feature: 'Astro DB' })}
</a>
<!-- Renders: <a href="...">Astro documentation for Astro DB</a> -->
```

See the [i18next documentation](https://www.i18next.com/overview/api#t) for more information on how to use the `t()` function with interpolation, formatting, and more.

### Advanced APIs

#### `t.all()`

The `locals.t.all()` function returns an object containing all UI strings available for the current locale.

```astro
---
// src/components/Example.astro
const allStrings = Astro.locals.t.all();
//    ^
//    {
//      "skipLink.label": "Skip to content",
//      "search.label": "Search",
//      …
//    }
---
```

#### `t.exists()`

To check if a translation key exists, use the `locals.t.exists()` function with the translation key as first argument.
Pass an optional second argument if you need to check if a translation exists for a specific locale.

```astro
---
// src/components/Example.astro
const keyExists = Astro.locals.t.exists('a.key');
//    ^ true
const keyExistsInFrench = Astro.locals.t.exists('other.key', { lngs: ['fr'] });
//    ^ false
---
```

See the [`exists()` reference in the i18next documentation](https://www.i18next.com/overview/api#exists) for more information.

#### `t.dir()`

The `locals.t.dir()` function returns the text direction of the current or a specific locale.

```astro
---
// src/components/Example.astro
const currentDirection = Astro.locals.t.dir();
//    ^
//    'ltr'
const arabicDirection = Astro.locals.t.dir('ar');
//    ^
//    'rtl'
---
```

See the [`dir()` reference in the i18next documentation](https://www.i18next.com/overview/api#dir) for more information.

## Accessing the current locale

You can use [`Astro.currentLocale`](https://docs.astro.build/en/reference/api-reference/#currentlocale) to read the current locale in `.astro` components.

The following example reads the current locale and uses it with the [`getRelativeLocaleUrl()`](https://docs.astro.build/en/reference/modules/astro-i18n/#getrelativelocaleurl) helper to generate a link to an about page in the current language:

```astro
---
// src/components/AboutLink.astro
import { getRelativeLocaleUrl } from 'astro:i18n';
---

<a href={getRelativeLocaleUrl(Astro.currentLocale ?? 'en', 'about')}>About</a>
```


================================================
FILE: docs/src/content/docs/guides/overriding-components.mdx
================================================
---
title: Overriding Components
description: Learn how to override Starlight’s built-in components to add custom elements to your documentation site’s UI.
---

import { Steps } from '@astrojs/starlight/components';

Starlight’s default UI and configuration options are designed to be flexible and work for a range of content. Much of Starlight's default appearance can be customized with [CSS](/guides/css-and-tailwind/) and [configuration options](/guides/customization/).

When you need more than what’s possible out of the box, Starlight supports building your own custom components to extend or override (completely replace) its default components.

## When to override

Overriding Starlight’s default components can be useful when:

- You want to change how a part of Starlight’s UI looks in a way not possible with [custom CSS](/guides/css-and-tailwind/).
- You want to change how a part of Starlight’s UI behaves.
- You want to add some additional UI alongside Starlight’s existing UI.

## How to override

<Steps>

1. Choose the Starlight component you want to override.
   You can find a full list of components in the [Overrides Reference](/reference/overrides/).

   :::tip
   Not sure which component you need to override? Use the [interactive Starlight Overrides Map](https://starlight-overrides-map.netlify.app/) to discover the names of Starlight's UI components.
   :::

   This example will override Starlight’s [`SocialIcons`](/reference/overrides/#socialicons) component in the page nav bar.

2. Create an Astro component to replace the Starlight component with.
   This example renders a contact link.

   ```astro
   ---
   // src/components/EmailLink.astro

   const email = 'houston@example.com';
   ---

   <a href=`mailto:${email}`>E-mail Me</a>
   ```

3. Tell Starlight to use your custom component in the [`components`](/reference/configuration/#components) configuration option in `astro.config.mjs`:

   ```js {9-12}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'My Docs with Overrides',
   			components: {
   				// Override the default `SocialIcons` component.
   				SocialIcons: './src/components/EmailLink.astro',
   			},
   		}),
   	],
   });
   ```

</Steps>

## Reuse a built-in component

You can build with Starlight’s default UI components just as you would with your own: importing and rendering them in your own custom components. This allows you to keep all of Starlight's basic UI within your design, while adding extra UI alongside them.

The example below shows a custom component that renders an e-mail link along with the default `SocialIcons` component:

```astro {3,7}
---
// src/components/EmailLink.astro
import Default from '@astrojs/starlight/components/SocialIcons.astro';
---

<a href="mailto:houston@example.com">E-mail Me</a>
<Default><slot /></Default>
```

When rendering a built-in component inside a custom component add a [`<slot />`](https://docs.astro.build/en/basics/astro-components/#slots) inside the default component. This makes sure that if the component is passed any child elements, Astro knows where to render them.

If you are reusing the [`PageFrame`](/reference/overrides/#pageframe) or [`TwoColumnContent`](/reference/overrides/#twocolumncontent) components which contain [named slots](https://docs.astro.build/en/basics/astro-components/#named-slots), you also need to [transfer](https://docs.astro.build/en/basics/astro-components/#transferring-slots) these slots as well.

The example below shows a custom component that reuses the `TwoColumnContent` component which contains an additional `right-sidebar` named slot that needs to be transferred:

```astro {8}
---
// src/components/CustomContent.astro
import Default from '@astrojs/starlight/components/TwoColumnContent.astro';
---

<Default>
	<slot />
	<slot name="right-sidebar" slot="right-sidebar" />
</Default>
```

## Use page data

When overriding a Starlight component, you can access the global [`starlightRoute` object](/guides/route-data/) containing all the data for the current page.
This allows you to use these values to control how your component template renders.

In the following example, a replacement [`PageTitle`](/reference/overrides/#pagetitle) component displays the current page’s title as set in the content’s frontmatter:

```astro {4} "{title}"
---
// src/components/Title.astro

const { title } = Astro.locals.starlightRoute.entry.data;
---

<h1 id="_top">{title}</h1>

<style>
	h1 {
		font-family: 'Comic Sans';
	}
</style>
```

Learn more about all the available properties in the [Route Data Reference](/reference/route-data/).

### Only override on specific pages

Component overrides apply to all pages. However, you can conditionally render using values from `starlightRoute` to determine when to show your custom UI, when to show Starlight’s default UI, or even when to show something entirely different.

In the following example, a component overriding Starlight's [`Footer`](/reference/overrides/#footer-1) displays "Built with Starlight 🌟" on the homepage only, and otherwise shows the default footer on all other pages:

```astro
---
// src/components/ConditionalFooter.astro
import Default from '@astrojs/starlight/components/Footer.astro';

const isHomepage = Astro.locals.starlightRoute.id === '';
---

{
	isHomepage ? (
		<footer>Built with Starlight 🌟</footer>
	) : (
		<Default>
			<slot />
		</Default>
	)
}
```

Learn more about conditional rendering in [Astro’s Template Syntax guide](https://docs.astro.build/en/basics/astro-syntax/#dynamic-html).


================================================
FILE: docs/src/content/docs/guides/pages.mdx
================================================
---
title: Pages
description: Learn how to create and manage your documentation site’s pages with Starlight.
sidebar:
  order: 1
tableOfContents:
  maxHeadingLevel: 4
---

Starlight generates your site’s HTML pages based on your content, with flexible options provided via Markdown frontmatter.
In addition, Starlight projects have full access to [Astro’s powerful page generation tools](https://docs.astro.build/en/basics/astro-pages/).
This guide shows how page generation works in Starlight.

## Content pages

### File formats

Starlight supports authoring content in Markdown and MDX with no configuration required.
You can add support for Markdoc by following the [“Markdoc” guide](/guides/authoring-content/#markdoc).

### Add pages

Add new pages to your site by creating `.md` or `.mdx` files in `src/content/docs/`.
Use sub-folders to organize your files and to create multiple path segments.

For example, the following file structure will generate pages at `example.com/hello-world` and `example.com/reference/faq`:

import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src/
  - content/
    - docs/
      - hello-world.md
      - reference/
        - faq.md

</FileTree>

### Type-safe frontmatter

All Starlight pages share a customizable [common set of frontmatter properties](/reference/frontmatter/) to control how the page appears:

```md
---
title: Hello, World!
description: This is a page in my Starlight-powered site
---
```

If you forget anything important, Starlight will let you know.

## Custom pages

For advanced use cases, you can add custom pages by creating a `src/pages/` directory.
The `src/pages/` directory uses [Astro's file-based routing](https://docs.astro.build/en/basics/astro-pages/#file-based-routing) and includes support for `.astro` files amongst other page formats.
This is helpful if you need to build pages with a completely custom layout or generate a page from an alternative data source.

For example, this project mixes Markdown content in `src/content/docs/` with Astro and HTML routes in `src/pages/`:

<FileTree>

- src/
  - content/
    - docs/
      - hello-world.md
  - pages/
    - custom.astro
    - archived.html

</FileTree>

Read more in the [“Pages” guide in the Astro docs](https://docs.astro.build/en/basics/astro-pages/).

### Using Starlight’s design in custom pages

To use the Starlight layout in custom pages, wrap your page content with the [`<StarlightPage>` component](#starlightpage-component).
This can be helpful if you are generating content dynamically but still want to use Starlight’s design.

To add anchor links to headings that match Starlight’s Markdown anchor link styles, you can use the [`<AnchorHeading>` component](#anchorheading-component) in your custom pages.

```astro
---
// src/pages/custom-page/example.astro
import StarlightPage from '@astrojs/starlight/components/StarlightPage.astro';
import AnchorHeading from '@astrojs/starlight/components/AnchorHeading.astro';
import CustomComponent from './CustomComponent.astro';
---

<StarlightPage frontmatter={{ title: 'My custom page' }}>
	<p>This is a custom page with a custom component:</p>
	<CustomComponent />

	<AnchorHeading level="2" id="learn-more">Learn more</AnchorHeading>
	<p>
		<a href="https://starlight.astro.build/">Read more in the Starlight docs</a>
	</p>
</StarlightPage>
```

#### `<StarlightPage>` component

The `<StarlightPage />` component renders a full page of content using Starlight’s layout and styles.

```astro
---
import StarlightPage from '@astrojs/starlight/components/StarlightPage.astro';
---

<StarlightPage frontmatter={{ title: 'My custom page' }}>
	<!-- Custom page content -->
</StarlightPage>
```

The `<StarlightPage />` component accepts the following props.

##### `frontmatter`

**required**  
**type:** `StarlightPageFrontmatter`

Set the [frontmatter properties](/reference/frontmatter/) for this page, similar to frontmatter in Markdown pages.
The [`title`](/reference/frontmatter/#title-required) property is required and all other properties are optional.

The following properties differ from Markdown frontmatter:

- The [`slug`](/reference/frontmatter/#slug) property is not supported and is automatically set based on the custom page’s URL.
- The [`editUrl`](/reference/frontmatter/#editurl) option requires a URL to display an edit link.
- The [`sidebar`](/reference/frontmatter/#sidebar) frontmatter property for customizing how the page appears in [autogenerated link groups](/reference/configuration/#sidebar) is not available. Pages using the `<StarlightPage />` component are not part of a collection and cannot be added to an autogenerated sidebar group.
- The [`draft`](/reference/frontmatter/#draft) option only displays a [notice](/reference/overrides/#draftcontentnotice) that the page is a draft but does not automatically exclude it from production builds.

##### `sidebar`

**type:** [`SidebarItem[]`](/reference/configuration/#sidebaritem)  
**default:** the sidebar generated based on the [global `sidebar` config](/reference/configuration/#sidebar)

Provide a custom site navigation sidebar for this page.
If not set, the page will use the default global sidebar.

For example, the following page overrides the default sidebar with a link to the homepage and a group of links to various other custom pages.

```astro {3-13}
<StarlightPage
	frontmatter={{ title: 'Orion' }}
	sidebar={[
		{ label: 'Home', link: '/' },
		{
			label: 'Constellations',
			items: [
				{ label: 'Andromeda', link: '/andromeda/' },
				{ label: 'Orion', link: '/orion/' },
				{ label: 'Ursa Minor', link: '/ursa-minor/', badge: 'Stub' },
			],
		},
	]}
>
	Example content.
</StarlightPage>
```

See the [“Sidebar Navigation”](/guides/sidebar/) guide to learn more about the available options for customizing the sidebar.

##### `hasSidebar`

**type:** `boolean`  
**default:** `false` if [`frontmatter.template`](/reference/frontmatter/#template) is `'splash'`, otherwise `true`

Control whether or not the sidebar should be displayed on this page.

##### `headings`

**type:** `{ depth: number; slug: string; text: string }[]`  
**default:** `[]`

Provide an array of all the headings on this page.
Starlight will generate the page table of contents from these headings if provided.

##### `dir`

**type:** `'ltr' | 'rtl'`  
**default:** the writing direction for the current locale

Set the writing direction for this page’s content.

##### `lang`

**type:** `string`  
**default:** the language of the current locale

Set the BCP-47 language tag for this page’s content, e.g. `en`, `zh-CN`, or `pt-BR`.

##### `isFallback`

**type:** `boolean`  
**default:** `false`

Indicate if this page is using [fallback content](/guides/i18n/#fallback-content) because there is no translation for the current language.

#### `<AnchorHeading>` component

The `<AnchorHeading />` component renders an HTML heading element with a clickable anchor link that matches Starlight’s Markdown styles.

```astro
---
import AnchorHeading from '@astrojs/starlight/components/AnchorHeading.astro';
---

<AnchorHeading level="2" id="sub-heading">Sub heading</AnchorHeading>
```

It accepts the following props as well as any other valid [global HTML attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes).

##### `level`

**required**  
**type:** `1 | 2 | 3 | 4 | 5 | 6`

The heading level to render.
For example, `level="1"` would render an `<h1>` element.

##### `id`

**required**  
**type:** `string`

The unique ID for this heading.
This will be used as the `id` attribute of the rendered heading and the anchor icon will link to it.


================================================
FILE: docs/src/content/docs/guides/project-structure.mdx
================================================
---
title: Project Structure
description: Learn how to organize files in your Starlight project.
---

This guide will show you how a Starlight project is organized and what the different files in your project do.

Starlight projects generally follow the same file and directory structure as other Astro projects. See [Astro’s project structure documentation](https://docs.astro.build/en/basics/project-structure/) for more detail.

## Files and directories

- `astro.config.mjs` — The Astro configuration file; includes the Starlight integration and configuration.
- `src/content.config.ts` — Content collections configuration file; adds Starlight’s frontmatter schemas to your project.
- `src/content/docs/` — Content files. Starlight turns each `.md`, `.mdx` or `.mdoc` file in this directory into a page on your site.
- `src/content/i18n/` (optional) — Translation data to support [internationalization](/guides/i18n/).
- `src/` — Other source code and files (components, styles, images, etc.) for your project.
- `public/` — Static assets (fonts, favicon, PDFs, etc.) that will not be processed by Astro.

## Example project contents

A Starlight project directory might look like this:

import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- public/
  - favicon.svg
- src/
  - assets/
    - logo.svg
    - screenshot.jpg
  - components/
    - CustomButton.astro
    - InteractiveWidget.jsx
  - content/
    - docs/
      - guides/
        - 01-getting-started.md
        - 02-advanced.md
      - index.mdx
  - content.config.ts
- astro.config.mjs
- package.json
- tsconfig.json

</FileTree>


================================================
FILE: docs/src/content/docs/guides/route-data.mdx
================================================
---
title: Route Data
description: Learn how Starlight’s page data model is used to render your pages and how you can customize it.
---

import { Steps } from '@astrojs/starlight/components';

When Starlight renders a page in your documentation, it first creates a route data object to represent what is on that page.
This guide explains how route data is generated, how to use it, and how you can customize it to modify Starlight’s default behavior.

See the [“Route Data Reference”](/reference/route-data/) for a full list of the available properties.

## What is route data?

Starlight route data is an object containing all the information required to render a single page.
It includes information for the current page as well as data generated from your Starlight configuration.

## Using route data

All of Starlight’s components use route data to decide what to render for each page.
For example, the [`siteTitle`](/reference/route-data/#sitetitle) string is used to display the site title and the [`sidebar`](/reference/route-data/#sidebar) array is used to render the global sidebar navigation.

You can access this data from the `Astro.locals.starlightRoute` global in Astro components:

```astro title="example.astro" {2}
---
const { siteTitle } = Astro.locals.starlightRoute;
---

<p>The title of this site is “{siteTitle}”</p>
```

This can be useful for example when building [component overrides](/guides/overriding-components/) to customize what you display.

## Customizing route data

Starlight’s route data works out of the box and does not require any configuration.
However, for advanced use cases, you may want to customize route data for some or all pages to modify how your site displays.

This is a similar concept to [component overrides](/guides/overriding-components/), but instead of modifying how Starlight renders your data, you modify the data Starlight renders.

### When to customize route data

Customizing route data can be useful when you want to modify how Starlight processes your data in a way not possible with existing configuration options.

For example, you may want to filter sidebar items or customize titles for specific pages.
Changes like this do not require modifying Starlight’s default components, only the data passed to those components.

### How to customize route data

You can customize route data using a special form of “middleware”.
This is a function that is called every time Starlight renders a page and can modify values in the route data object.

<Steps>

1. Create a new file exporting an `onRequest` function using Starlight’s `defineRouteMiddleware()` utility:

   ```ts
   // src/routeData.ts
   import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

   export const onRequest = defineRouteMiddleware(() => {});
   ```

2. Tell Starlight where your route data middleware file is located in `astro.config.mjs`:

   ```js ins={9}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'My delightful docs site',
   			routeMiddleware: './src/routeData.ts',
   		}),
   	],
   });
   ```

3. Update your `onRequest` function to modify route data.

   The first argument your middleware will receive is [Astro’s `context` object](https://docs.astro.build/en/reference/api-reference/).
   This contains full information about the current page render, including the current URL and `locals`.

   In this example, we are going to make our docs more exciting by adding an exclamation mark to the end of every page’s title.

   ```ts
   // src/routeData.ts
   import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

   export const onRequest = defineRouteMiddleware((context) => {
   	// Get the content collection entry for this page.
   	const { entry } = context.locals.starlightRoute;
   	// Update the title to add an exclamation mark.
   	entry.data.title = entry.data.title + '!';
   });
   ```

</Steps>

#### Multiple route middleware

Starlight also supports providing multiple middleware.
Set `routeMiddleware` to an array of paths to add more than one middleware handler:

```js {9}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'My site with multiple middleware',
			routeMiddleware: ['./src/middleware-one.ts', './src/middleware-two.ts'],
		}),
	],
});
```

#### Waiting for later route middleware

To wait for middleware later in the stack to run before executing your code, you can await the `next()` callback passed as the second argument to your middleware function.
This can be useful to wait for a plugin’s middleware to run before making changes for example.

```ts "next" "await next();"
// src/routeData.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

export const onRequest = defineRouteMiddleware(async (context, next) => {
	// Wait for later middleware to run.
	await next();
	// Modify route data.
	const { entry } = context.locals.starlightRoute;
	entry.data.title = entry.data.title + '!';
});
```


================================================
FILE: docs/src/content/docs/guides/sidebar.mdx
================================================
---
title: Sidebar Navigation
description: Learn how to set up and customize your Starlight site’s sidebar navigation links.
---

import { FileTree } from '@astrojs/starlight/components';
import SidebarPreview from '~/components/sidebar-preview.astro';

A well-organized sidebar is key to a good documentation as it is one of the main ways users will navigate your site. Starlight provides a complete set of options to customize your sidebar layout and content.

## Default sidebar

By default, Starlight will automatically generate a sidebar based on the filesystem structure of your documentation, using each file's `title` property as the sidebar entry.

For example, given the following file structure:

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - andromeda.md
        - orion.md
      - stars/
        - betelgeuse.md

</FileTree>

The following sidebar will be automatically generated:

<SidebarPreview
	config={[
		{
			label: 'constellations',
			items: [
				{ label: 'Andromeda', link: '' },
				{ label: 'Orion', link: '' },
			],
		},
		{
			label: 'stars',
			items: [{ label: 'Betelgeuse', link: '' }],
		},
	]}
/>

Learn more about autogenerated sidebars in the [autogenerated groups](#autogenerated-groups) section.

## Add links and link groups

To configure your sidebar links and groups of links (within a collapsible header), use the [`starlight.sidebar`](/reference/configuration/#sidebar) property in `astro.config.mjs`.

By combining links and groups, you can create a wide variety of sidebar layouts.

### Internal links

Add a link to a page in `src/content/docs/` using an object with the `slug` property.
The linked page’s title will be used as the label by default.

For example, with the following configuration:

```js "slug:"
starlight({
	sidebar: [
		{ slug: 'constellations/andromeda' },
		{ slug: 'constellations/orion' },
	],
});
```

And the following file structure:

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - andromeda.md
        - orion.md

</FileTree>

The following sidebar will be generated:

<SidebarPreview
	config={[
		{ label: 'Andromeda', link: '' },
		{ label: 'Orion', link: '' },
	]}
/>

To override the values inferred from a linked page’s frontmatter, you can add `label`, [`translations`](#internationalization), and [`attrs`](#custom-html-attributes) properties.

See ["Customizing autogenerated links"](#customizing-autogenerated-links-in-frontmatter) for more details about controlling the sidebar appearance from page frontmatter.

#### Shorthand for internal links

Internal links can also be specified by providing only a string for the page slug as a shorthand.

For example, the following configuration is equivalent to the configuration above, which used `slug`:

```js "slug:"
starlight({
	sidebar: ['constellations/andromeda', 'constellations/orion'],
});
```

### Other links

Add a link to an external or non-docs page using an object with `label` and `link` properties.

```js "label:" "link:"
starlight({
	sidebar: [
		// A link to a non-docs page on this site.
		{ label: 'Meteor Store', link: '/shop/' },
		// An external link to the NASA website.
		{ label: 'NASA', link: 'https://www.nasa.gov/' },
	],
});
```

The configuration above generates the following sidebar:

<SidebarPreview
	config={[
		{ label: 'Meteor Store', link: '' },
		{ label: 'NASA', link: 'https://www.nasa.gov/' },
	]}
/>

### Groups

You can add structure to your sidebar by grouping related links together under a collapsible heading.
Groups can contain both links and other sub-groups.

Add a group using an object with `label` and `items` properties.
The `label` will be used as the heading for the group.
Add links or subgroups to the `items` array.

```js /^\s*(label:|items:)/
starlight({
	sidebar: [
		// A group of links labelled "Constellations".
		{
			label: 'Constellations',
			items: [
				'constellations/carina',
				'constellations/centaurus',
				// A nested group of links for seasonal constellations.
				{
					label: 'Seasonal',
					items: [
						'constellations/andromeda',
						'constellations/orion',
						'constellations/ursa-minor',
					],
				},
			],
		},
	],
});
```

The configuration above generates the following sidebar:

<SidebarPreview
	config={[
		{
			label: 'Constellations',
			items: [
				{ label: 'Carina', link: '' },
				{ label: 'Centaurus', link: '' },
				{
					label: 'Seasonal',
					items: [
						{ label: 'Andromeda', link: '' },
						{ label: 'Orion', link: '' },
						{ label: 'Ursa Minor', link: '' },
					],
				},
			],
		},
	]}
/>

### Autogenerated groups

Starlight can automatically generate a group in your sidebar based on a directory of your docs.
This is helpful when you do not want to manually enter each sidebar item in a group.

By default, pages are sorted in alphabetical order according to the file [`id`](/reference/route-data/#id).

Add an autogenerated group using an object with `label` and `autogenerate` properties. Your `autogenerate` configuration must specify the `directory` to use for sidebar entries. For example, with the following configuration:

```js "label:" "autogenerate:"
starlight({
	sidebar: [
		{
			label: 'Constellations',
			// Autogenerate a group of links for the 'constellations' directory.
			autogenerate: { directory: 'constellations' },
		},
	],
});
```

And the following file structure:

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - carina.md
        - centaurus.md
        - seasonal/
          - andromeda.md

</FileTree>

The following sidebar will be generated:

<SidebarPreview
	config={[
		{
			label: 'Constellations',
			items: [
				{ label: 'Carina', link: '' },
				{ label: 'Centaurus', link: '' },
				{
					label: 'seasonal',
					items: [{ label: 'Andromeda', link: '' }],
				},
			],
		},
	]}
/>

## Customizing autogenerated links in frontmatter

Use the [`sidebar` frontmatter field](/reference/frontmatter/#sidebar) in individual pages to customize autogenerated links.

Sidebar frontmatter options allow you to set a [custom label](/reference/frontmatter/#label), use [custom attributes](/reference/frontmatter/#attrs), add a [badge](/reference/frontmatter/#badge) to a link, [hide](/reference/frontmatter/#hidden) a link from the sidebar, or define a [custom sort weighting](/reference/frontmatter/#order).

```md "sidebar:"
---
# src/content/docs/example.md
title: My page
sidebar:
  # Set a custom label for the link
  label: Custom sidebar label
  # Set a custom order for the link (lower numbers are displayed higher up)
  order: 2
  # Add a badge to the link
  badge:
    text: New
    variant: tip
---
```

An autogenerated group including a page with the frontmatter above will generate the following sidebar:

<SidebarPreview
	config={[
		{
			label: 'Guides',
			items: [
				{ label: 'A page', link: '' },
				{
					label: 'Custom sidebar label',
					link: '',
					badge: { text: 'New', variant: 'tip' },
				},
				{ label: 'Another page', link: '' },
			],
		},
	]}
/>

:::note
The `sidebar` frontmatter configuration is only used for links in autogenerated groups and docs links defined with the `slug` property. It does not apply to links defined with the `link` property.
:::

## Badges

Links, groups, and autogenerated groups can also include a `badge` property to display a badge next to their label.

```js {9,16}
starlight({
	sidebar: [
		{
			label: 'Stars',
			items: [
				// A link with a "Supergiant" badge.
				{
					slug: 'stars/persei',
					badge: 'Supergiant',
				},
			],
		},
		// An autogenerated group with an "Outdated" badge.
		{
			label: 'Moons',
			badge: 'Outdated',
			autogenerate: { directory: 'moons' },
		},
	],
});
```

The configuration above generates the following sidebar:

<SidebarPreview
	config={[
		{
			label: 'Stars',
			items: [
				{
					label: 'Persei',
					link: '',
					badge: { text: 'Supergiant', variant: 'default' },
				},
			],
		},
		{
			label: 'Moons',
			badge: { text: 'Outdated', variant: 'default' },
			items: [
				{
					label: 'Io',
					link: '',
				},
				{
					label: 'Europa',
					link: '',
				},
				{
					label: 'Ganymede',
					link: '',
				},
			],
		},
	]}
/>

### Badge variants and custom styling

Customize the badge styling using an object with `text`, `variant`, and `class` properties.

The `text` represents the content to display (e.g. "New").
By default, the badge will use the accent color of your site. To use a built-in badge style, set the `variant` property to one of the following values: `note`, `tip`, `danger`, `caution` or `success`.

Optionally, you can create a custom badge style by setting the `class` property to a CSS class name.

```js {9}
starlight({
	sidebar: [
		{
			label: 'Stars',
			items: [
				// A link with a yellow "Stub" badge.
				{
					slug: 'stars/sirius',
					badge: { text: 'Stub', variant: 'caution' },
				},
			],
		},
	],
});
```

The configuration above generates the following sidebar:

<SidebarPreview
	config={[
		{
			label: 'Stars',
			items: [
				{
					label: 'Sirius',
					link: '',
					badge: { text: 'Stub', variant: 'caution' },
				},
			],
		},
	]}
/>

Learn more about [using and customizing badges](/components/badges/#usage).

## Custom HTML attributes

Links can also include an `attrs` property to add custom HTML attributes to the link element.

In the following example, `attrs` is used to add a `target="_blank"` attribute, so that the link opens in a new tab, and to apply a custom `style` attribute to italicize the link label:

```js {10}
starlight({
	sidebar: [
		{
			label: 'Resources',
			items: [
				// An external link to the NASA website opening in a new tab.
				{
					label: 'NASA',
					link: 'https://www.nasa.gov/',
					attrs: { target: '_blank', style: 'font-style: italic' },
				},
			],
		},
	],
});
```

The configuration above generates the following sidebar:

<SidebarPreview
	config={[
		{
			label: 'Resources',
			items: [
				{
					label: 'NASA',
					link: 'https://www.nasa.gov/',
					attrs: {
						target: '_blank',
						style: 'font-style: italic',
					},
				},
			],
		},
	]}
/>

### Custom HTML attributes for autogenerated links

Customize HTML attributes of all links in [autogenerated groups](#autogenerated-groups) by defining the `attrs` property in the `autogenerate` configuration.
Individual pages can specify custom attributes using the [`sidebar.attrs` frontmatter field](/reference/frontmatter/#attrs) which will be merged with the `autogenerate.attrs` configuration.

For example, with the following configuration:

```js {9}
starlight({
	sidebar: [
		{
			label: 'Constellations',
			autogenerate: {
				// Autogenerate a group of links for the 'constellations' directory.
				directory: 'constellations',
				// Italicize all link labels in this group.
				attrs: { style: 'font-style: italic' },
			},
		},
	],
});
```

And the following file structure:

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - carina.md
        - centaurus.md
        - seasonal/
          - andromeda.md

</FileTree>

The following sidebar will be generated with all autogenerated links italicized:

<SidebarPreview
	config={[
		{
			label: 'Constellations',
			items: [
				{ label: 'Carina', link: '', attrs: { style: 'font-style: italic' } },
				{
					label: 'Centaurus',
					link: '',
					attrs: { style: 'font-style: italic' },
				},
				{
					label: 'seasonal',
					items: [
						{
							label: 'Andromeda',
							link: '',
							attrs: { style: 'font-style: italic' },
						},
					],
				},
			],
		},
	]}
/>

## Internationalization

Use the `translations` property on link and group entries to translate the link or group label for each supported language by specifying a [BCP-47](https://www.w3.org/International/questions/qa-choosing-language-tags) language tag, e.g. `"en"`, `"ar"`, or `"zh-CN"`, as the key and the translated label as the value.
The `label` property will be used for the default locale and for languages without a translation.

```js {5-7,11-13,18-20}
starlight({
	sidebar: [
		{
			label: 'Constellations',
			translations: {
				'pt-BR': 'Constelações',
			},
			items: [
				{
					label: 'Andromeda',
					translations: {
						'pt-BR': 'Andrômeda',
					},
					slug: 'constellations/andromeda',
				},
				{
					label: 'Scorpius',
					translations: {
						'pt-BR': 'Escorpião',
					},
					slug: 'constellations/scorpius',
				},
			],
		},
	],
});
```

Browsing the documentation in Brazilian Portuguese will generate the following sidebar:

<SidebarPreview
	config={[
		{
			label: 'Constelação',
			items: [
				{ label: 'Andrômeda', link: '' },
				{ label: 'Escorpião', link: '' },
			],
		},
	]}
/>

### Internationalization with internal links

[Internal links](#internal-links) will automatically use translated page titles from content frontmatter by default:

```js {9-10}
starlight({
	sidebar: [
		{
			label: 'Constellations',
			translations: {
				'pt-BR': 'Constelações',
			},
			items: [
				{ slug: 'constellations/andromeda' },
				{ slug: 'constellations/scorpius' },
			],
		},
	],
});
```

Browsing the documentation in Brazilian Portuguese will generate the following sidebar:

<SidebarPreview
	config={[
		{
			label: 'Constelações',
			items: [
				{ label: 'Andrômeda', link: '' },
				{ label: 'Escorpião', link: '' },
			],
		},
	]}
/>

In multilingual sites, the value of `slug` does not include the language portion of the URL.
For example, if you have pages at `en/intro` and `pt-br/intro`, the slug is `intro` when configuring the sidebar.

### Internationalization with badges

For [badges](#badges), the `text` property can be a string, or for multilingual sites, an object with values for each different locale.
When using the object form, the keys must be [BCP-47](https://www.w3.org/International/questions/qa-choosing-language-tags) tags (e.g. `en`, `ar`, or `zh-CN`):

```js {11-16}
starlight({
	sidebar: [
		{
			label: 'Constellations',
			translations: {
				'pt-BR': 'Constelações',
			},
			items: [
				{
					slug: 'constellations/andromeda',
					badge: {
						text: {
							en: 'New',
							'pt-BR': 'Novo',
						},
					},
				},
			],
		},
	],
});
```

Browsing the documentation in Brazilian Portuguese will generate the following sidebar:

<SidebarPreview
	config={[
		{
			label: 'Constelações',
			items: [
				{
					label: 'Andrômeda',
					link: '',
					badge: { text: 'Novo', variant: 'default' },
				},
			],
		},
	]}
/>

## Collapsing groups

Groups of links can be collapsed by default by setting the `collapsed` property to `true`.

```js {5-6}
starlight({
	sidebar: [
		{
			label: 'Constellations',
			// Collapse the group by default.
			collapsed: true,
			items: ['constellations/andromeda', 'constellations/orion'],
		},
	],
});
```

The configuration above generates the following sidebar:

<SidebarPreview
	config={[
		{
			label: 'Constellations',
			collapsed: true,
			items: [
				{ label: 'Andromeda', link: '' },
				{ label: 'Orion', link: '' },
			],
		},
	]}
/>

[Autogenerated groups](#autogenerated-groups) respect the `collapsed` value of their parent group:

```js {5-6}
starlight({
	sidebar: [
		{
			label: 'Constellations',
			// Collapse the group and its autogenerated subgroups by default.
			collapsed: true,
			autogenerate: { directory: 'constellations' },
		},
	],
});
```

The configuration above generates the following sidebar:

<SidebarPreview
	config={[
		{
			label: 'Constellations',
			collapsed: true,
			items: [
				{ label: 'Carina', link: '' },
				{ label: 'Centaurus', link: '' },
				{
					label: 'seasonal',
					collapsed: true,
					items: [{ label: 'Andromeda', link: '' }],
				},
			],
		},
	]}
/>

This behavior can be overridden by defining the `autogenerate.collapsed` property.

```js {5-7} "collapsed: true"
starlight({
	sidebar: [
		{
			label: 'Constellations',
			// Do not collapse the "Constellations" group but collapse its
			// autogenerated subgroups.
			collapsed: false,
			autogenerate: { directory: 'constellations', collapsed: true },
		},
	],
});
```

The configuration above generates the following sidebar:

<SidebarPreview
	config={[
		{
			label: 'Constellations',
			items: [
				{ label: 'Carina', link: '' },
				{ label: 'Centaurus', link: '' },
				{
					label: 'seasonal',
					collapsed: true,
					items: [{ label: 'Andromeda', link: '' }],
				},
			],
		},
	]}
/>


================================================
FILE: docs/src/content/docs/guides/site-search.mdx
================================================
---
title: Site Search
description: Learn about Starlight’s built-in site search features and how to customize them.
tableOfContents:
  maxHeadingLevel: 4
---

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

By default, Starlight sites include full-text search powered by [Pagefind](https://pagefind.app/), which is a fast and low-bandwidth search tool for static sites.

No configuration is required to enable search. Build and deploy your site, then use the search bar in the site header to find content.

## Hide content in search results

### Exclude a page

To exclude a page from your search index, add [`pagefind: false`](/reference/frontmatter/#pagefind) to the page’s frontmatter:

```md title="src/content/docs/not-indexed.md" ins={3}
---
title: Content to hide from search
pagefind: false
---
```

### Exclude part of a page

Pagefind will ignore content inside an element with the [`data-pagefind-ignore`](https://pagefind.app/docs/indexing/#removing-individual-elements-from-the-index) attribute.

In the following example, the first paragraph will display in search results, but the contents of the `<div>` will not:

```md title="src/content/docs/partially-indexed.md" ins="data-pagefind-ignore"
---
title: Partially indexed page
---

This text will be discoverable via search.

<div data-pagefind-ignore>

This text will be hidden from search.

</div>
```

## Alternative search providers

### Algolia DocSearch

If you have access to [Algolia’s DocSearch program](https://docsearch.algolia.com/) and want to use it instead of Pagefind, you can use the official Starlight DocSearch plugin.

<Steps>

1. Install `@astrojs/starlight-docsearch`:

   <Tabs syncKey="pkg">

   <TabItem label="npm">

   ```sh
   npm install @astrojs/starlight-docsearch
   ```

   </TabItem>

   <TabItem label="pnpm">

   ```sh
   pnpm add @astrojs/starlight-docsearch
   ```

   </TabItem>

   <TabItem label="Yarn">

   ```sh
   yarn add @astrojs/starlight-docsearch
   ```

   </TabItem>

   </Tabs>

2. Add DocSearch to your Starlight [`plugins`](/reference/configuration/#plugins) config in `astro.config.mjs` and pass it your Algolia `appId`, `apiKey`, and `indexName`:

   ```js ins={4,10-16}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';
   import starlightDocSearch from '@astrojs/starlight-docsearch';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Site with DocSearch',
   			plugins: [
   				starlightDocSearch({
   					appId: 'YOUR_APP_ID',
   					apiKey: 'YOUR_SEARCH_API_KEY',
   					indexName: 'YOUR_INDEX_NAME',
   				}),
   			],
   		}),
   	],
   });
   ```

</Steps>

With this updated configuration, the search bar on your site will now open an Algolia modal instead of the default search modal.

#### DocSearch configuration

The Starlight DocSearch plugin supports customizing the DocSearch component with the following inline options:

- `maxResultsPerGroup`: Limit the number of results displayed for each search group. Default is `5`.
- `disableUserPersonalization`: Prevent DocSearch from saving a user’s recent searches and favorites to local storage. Default is `false`.
- `insights`: Enable the Algolia Insights plugin and send search events to your DocSearch index. Default is `false`.
- `searchParameters`: An object customizing the [Algolia Search Parameters](https://www.algolia.com/doc/api-reference/search-api-parameters/).

##### Additional DocSearch options

A separate configuration file is required to pass function options like `transformItems()` or `resultsFooterComponent()` to the DocSearch component.

<Steps>

1. Create a TypeScript file exporting your DocSearch configuration.

   ```ts
   // src/config/docsearch.ts
   import type { DocSearchClientOptions } from '@astrojs/starlight-docsearch';

   export default {
   	appId: 'YOUR_APP_ID',
   	apiKey: 'YOUR_SEARCH_API_KEY',
   	indexName: 'YOUR_INDEX_NAME',
   	getMissingResultsUrl({ query }) {
   		return `https://github.com/algolia/docsearch/issues/new?title=${query}`;
   	},
   	// ...
   } satisfies DocSearchClientOptions;
   ```

2. Pass the path to your configuration file to the Starlight DocSearch plugin in `astro.config.mjs`.

   ```js {11-13}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';
   import starlightDocSearch from '@astrojs/starlight-docsearch';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Site with DocSearch',
   			plugins: [
   				starlightDocSearch({
   					clientOptionsModule: './src/config/docsearch.ts',
   				}),
   			],
   		}),
   	],
   });
   ```

</Steps>

See the [DocSearch JavaScript client API Reference](https://docsearch.algolia.com/docs/api/) for all supported options.

#### Translating the DocSearch UI

DocSearch only provides English UI strings by default.
Add translations of the modal UI for your language using Starlight’s built-in [internationalization system](/guides/i18n/#translate-starlights-ui).

<Steps>

1. Extend Starlight’s `i18n` content collection definition with the DocSearch schema in `src/content.config.ts`:

   ```js ins={5} ins=/{ extend: .+ }/
   // src/content.config.ts
   import { defineCollection } from 'astro:content';
   import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
   import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';
   import { docSearchI18nSchema } from '@astrojs/starlight-docsearch/schema';

   export const collections = {
   	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
   	i18n: defineCollection({
   		loader: i18nLoader(),
   		schema: i18nSchema({ extend: docSearchI18nSchema() }),
   	}),
   };
   ```

2. Add translations to your JSON files in `src/content/i18n/`.

   These are the English defaults used by DocSearch:

   ```json title="src/content/i18n/en.json"
   {
   	"docsearch.searchBox.resetButtonTitle": "Clear the query",
   	"docsearch.searchBox.resetButtonAriaLabel": "Clear the query",
   	"docsearch.searchBox.cancelButtonText": "Cancel",
   	"docsearch.searchBox.cancelButtonAriaLabel": "Cancel",
   	"docsearch.searchBox.searchInputLabel": "Search",

   	"docsearch.startScreen.recentSearchesTitle": "Recent",
   	"docsearch.startScreen.noRecentSearchesText": "No recent searches",
   	"docsearch.startScreen.saveRecentSearchButtonTitle": "Save this search",
   	"docsearch.startScreen.removeRecentSearchButtonTitle": "Remove this search from history",
   	"docsearch.startScreen.favoriteSearchesTitle": "Favorite",
   	"docsearch.startScreen.removeFavoriteSearchButtonTitle": "Remove this search from favorites",

   	"docsearch.errorScreen.titleText": "Unable to fetch results",
   	"docsearch.errorScreen.helpText": "You might want to check your network connection.",

   	"docsearch.footer.selectText": "to select",
   	"docsearch.footer.selectKeyAriaLabel": "Enter key",
   	"docsearch.footer.navigateText": "to navigate",
   	"docsearch.footer.navigateUpKeyAriaLabel": "Arrow up",
   	"docsearch.footer.navigateDownKeyAriaLabel": "Arrow down",
   	"docsearch.footer.closeText": "to close",
   	"docsearch.footer.closeKeyAriaLabel": "Escape key",
   	"docsearch.footer.searchByText": "Search by",

   	"docsearch.noResultsScreen.noResultsText": "No results for",
   	"docsearch.noResultsScreen.suggestedQueryText": "Try searching for",
   	"docsearch.noResultsScreen.reportMissingResultsText": "Believe this query should return results?",
   	"docsearch.noResultsScreen.reportMissingResultsLinkText": "Let us know."
   }
   ```

</Steps>

### Community search providers

[Community plugins](/resources/plugins/#community-plugins) can also provide alternatives to Starlight’s built-in Pagefind search provider.

#### Typesense DocSearch

The [Starlight DocSearch Typesense](https://starlight-docsearch.typesense.org/) community plugin provides an open-source and self-hostable alternative that integrates the [DocSearch](https://github.com/typesense/typesense-docsearch.js) interface with a [Typesense](https://typesense.org/) backend.

See the [“Getting Started”](https://starlight-docsearch.typesense.org/getting-started/) guide in the Starlight DocSearch Typesense documentation to learn how to use it in your project.


================================================
FILE: docs/src/content/docs/hi/404.md
================================================
---
title: पेज नहीं मिला
template: splash
editUrl: false
lastUpdated: false
hero:
  title: '404'
  tagline: <strong>Houston, हमें एक समस्या है।</strong> हमें वह पेज नहीं मिला.<br> URL जांचें या खोज बार का उपयोग करने का प्रयास करें।
  actions:
    - text: अवतरण पेज पर वापस आये
      icon: right-arrow
      link: /hi/
      variant: primary
---


================================================
FILE: docs/src/content/docs/hi/environmental-impact.md
================================================
---
title: पर्यावरण-अनुकूल दस्तावेज़
description: जानें कि कैसे Starlight आपको हरित दस्तावेज़ीकरण साइट बनाने और आपके कार्बन निशान को कम करने में मदद कर सकता है।
---

वेब उद्योग के जलवायु प्रभाव का अनुमान वैश्विक कार्बन उत्सर्जन के [2%][sf] से [4% के बीच][bbc] है, जो लगभग एयरलाइन उद्योग के उत्सर्जन के बराबर है।
किसी वेबसाइट के पारिस्थितिक प्रभाव की गणना करने में कई जटिल कारक होते हैं, लेकिन इस मार्गदर्शिका में आपके दस्तावेज़ साइट के पर्यावरणीय पदचिह्न को कम करने के लिए कुछ युक्तियां शामिल हैं।

अच्छी खबर यह है कि Starlight को चुनना एक बेहतरीन शुरुआत है।
Website Carbon Calculator के अनुसार, यह साइट [परीक्षण किए गए 99% वेब पेजों की तुलना में अधिक स्वच्छ है][sl-carbon], जो प्रति पेज भेंट में 0.01 ग्राम CO₂ का उत्पादन करती है।

## पेज का वजन

एक वेब पेज जितना अधिक डेटा स्थानांतरित करता है, उसे उतने ही अधिक शक्ति संसाधनों की आवश्यकता होती है।
एप्रिल 2023 में, [HTTP आर्काइव के डेटा][http] के अनुसार, औसत वेब पेज के लिए उपयोगकर्ता को 2,000 KB से अधिक डाउनलोड करने की आवश्यकता थी

Starlight ऐसे पेज बनाता है जो यथासंभव हल्के होते हैं।
उदाहरण के लिए, पहले दर्शन पर, एक उपयोगकर्ता 50 KB से कम संपीड़ित डेटा डाउनलोड करेगा - HTTP संग्रह माध्य का केवल 2.5%।
एक अच्छी कैशिंग रणनीति के साथ, बाद के नेविगेशन कम से कम 10 KB तक डाउनलोड हो सकते हैं।

### छवियाँ

जबकि Starlight एक अच्छी आधार रेखा प्रदान करता है, आपके द्वारा अपने दस्तावेज़ पेजों में जोड़ी गई छवियां आपके पेज का वजन तेजी से बढ़ा सकती हैं।
Starlight आपके Markdown और MDX फ़ाइलों में स्थानीय छवियों को अनुकूलित करने के लिए Astro के [अनुकूलित संपत्ति समर्थन][assets] का उपयोग करता है।

### UI अवयव

React या Vue जैसे UI फ्रेमवर्क के साथ निर्मित अवयव आसानी से एक पेज पर बड़ी मात्रा में Javascript जोड़ सकते हैं।
क्योंकि Starlight Astro पर बनाया गया है, [Astro द्वीप समूह][islands] की बदौलत इन जैसे अवयव डिफ़ॉल्ट रूप से **शून्य client-side Jacascript** लोड करते हैं।

### कैशिंग

कैशिंग का उपयोग यह नियंत्रित करने के लिए किया जाता है कि कोई ब्राउज़र पहले से डाउनलोड किए गए डेटा को कितनी देर तक संग्रहीत कर सकता है और उसका पुन: उपयोग करता है।
एक अच्छी कैशिंग रणनीति यह सुनिश्चित करती है कि उपयोगकर्ता को नई सामग्री बदलने पर जल्द से जल्द मिल जाए, लेकिन जब सामग्री नहीं बदली है तो उसे बार-बार डाउनलोड करने से भी बचा जा सकता है।

कैशिंग को कॉन्फ़िगर करने का सबसे आम तरीका [`Cache-Control` HTTP header][cache] है।
Starlight का उपयोग करते समय, आप `/_astro/` निर्देशिका में हर चीज़ के लिए एक लंबा cache समय निर्धारित कर सकते हैं।
इस निर्देशिका में CSS, JavaScript और अन्य बंडल संपत्तियां शामिल हैं जिन्हें अनावश्यक डाउनलोड को कम करते हुए हमेशा के लिए सुरक्षित रूप से cache किया जा सकता है:

```
Cache-Control: public, max-age=604800, immutable
```

कैशिंग को कैसे कॉन्फ़िगर करें यह आपके वेब होस्ट पर निर्भर करता है। उदाहरण के लिए, Vercel बिना किसी कॉन्फ़िगरेशन की आवश्यकता के आपके लिए इस कैशिंग रणनीति को लागू करता है, जबकि आप अपने परियोजना में `public/_headers` फ़ाइल जोड़कर [नेटलिफाई के लिए कस्टम हेडर][ntl-headers] सेट कर सकते हैं:

```
/_astro/*
  Cache-Control: public
  Cache-Control: max-age=604800
  Cache-Control: immutable
```

[cache]: https://csswizardry.com/2019/03/cache-control-for-civilians/
[ntl-headers]: https://docs.netlify.com/routing/headers/

## शक्ति की खपत

एक वेब पेज कैसे बनाया जाता है यह उपयोगकर्ता के उपकरण पर चलने में लगने वाली शक्ति को प्रभावित कर सकता है।
न्यूनतम Javascript का उपयोग करके, Starlight उपयोगकर्ता के फोन, टैबलेट या कंप्यूटर को पेजो को लोड करने और प्रस्तुत करने के लिए आवश्यक प्रसंस्करण शक्ति की मात्रा को कम कर देता है।

वैश्लेषिकी ट्रैकिंग स्क्रिप्ट या वीडियो एम्बेड जैसी JavaScript-भारी सामग्री सुविधाएं जोड़ते समय सावधान रहें क्योंकि ये पेज शक्ति उपयोग को बढ़ा सकते हैं।
यदि आपको विश्लेषण की आवश्यकता है, तो [Cabin][cabin], [Fathom][fathom] या [Plausible][plausible] जैसे हल्के विकल्प चुनने पर विचार करें।
[उपयोगकर्ता इंटरैक्शन पर वीडियो लोड][lazy-video] होने की प्रतीक्षा करके YouTube और Vimeo वीडियो जैसे एंबेड को बेहतर बनाया जा सकता है।
[`astro-embed`][embed] जैसे पैकेज सामान्य सेवाओं के लिए मदद कर सकते हैं।

:::tip[क्या आप जानते हैं?]
JavaScript को पार्स करना और संकलित करना ब्राउज़र द्वारा किए जाने वाले सबसे महंगे कार्यों में से एक है।
समान आकार की JPEG छवि प्रस्तुत करने की तुलना में, [JavaScript को संसाधित होने में 30 गुना से अधिक समय लग सकता है][cost-of-js]।
:::

[cabin]: https://withcabin.com/
[fathom]: https://usefathom.com/
[plausible]: https://plausible.io/
[lazy-video]: https://web.dev/iframe-lazy-loading/
[embed]: https://www.npmjs.com/package/astro-embed
[cost-of-js]: https://medium.com/dev-channel/the-cost-of-javascript-84009f51e99e

## होस्टिंग

जहां एक वेब पेज होस्ट किया गया है, उसका इस बात पर बड़ा प्रभाव पड़ सकता है कि आपकी दस्तावेज़ीकरण साइट पर्यावरण के अनुकूल कितनी है।
डेटा सेंटर और सर्वर फ़ार्म का बड़ा पारिस्थितिक प्रभाव हो सकता है, जिसमें उच्च बिजली की खपत और पानी का गहन उपयोग शामिल है।

नवीकरणीय शक्ति का उपयोग करने वाले होस्ट को चुनने का मतलब आपकी साइट के लिए कम कार्बन उत्सर्जन होगा। [Green Web Directory][gwb] एक उपकरण है जो आपको होस्टिंग कंपनियों को ढूंढने में मदद कर सकता है।

[gwb]: https://www.thegreenwebfoundation.org/directory/

## तुलना

क्या आप जानना चाहते हैं कि अन्य दस्तावेज़ीकरण फ्रेमवर्क की तुलना कैसे की जाती है?
[Website Carbon Calculator][wcc] के साथ ये परीक्षण विभिन्न उपकरणों के साथ बनाए गए समान पृष्ठों की तुलना करते हैं।

| फ्रेमवर्क                   | प्रति पृष्ठ विज़िट CO₂ | रेटिंग |
| --------------------------- | ---------------------- | :----: |
| [Starlight][sl-carbon]      | 0.01g                  |   A+   |
| [Read the Docs][rtd-carbon] | 0.05g                  |   A+   |
| [Sphinx][sx-carbon]         | 0.06g                  |   A+   |
| [VitePress][vp-carbon]      | 0.07g                  |   A+   |
| [Docus][dc-carbon]          | 0.09g                  |   A+   |
| [docsify][dy-carbon]        | 0.10g                  |   A    |
| [Nextra][nx-carbon]         | 0.11g                  |   A    |
| [MkDocs][mk-carbon]         | 0.19g                  |   B    |
| [Docusaurus][ds-carbon]     | 0.21g                  |   B    |
| [GitBook][gb-carbon]        | 0.43g                  |   C    |
| [Mintlify][mt-carbon]       | 1.22g                  |   F    |

<small>डेटा 22 जुलाई 2024 को एकत्र किया गया। नवीनतम आंकड़े देखने के लिए लिंक पर क्लिक करें।</small>

[sl-carbon]: https://www.websitecarbon.com/website/starlight-astro-build-getting-started/
[vp-carbon]: https://www.websitecarbon.com/website/vitepress-dev-guide-what-is-vitepress/
[dc-carbon]: https://www.websitecarbon.com/website/docus-dev-introduction-getting-started/
[sx-carbon]: https://www.websitecarbon.com/website/sphinx-doc-org-en-master-usage-quickstart-html/
[mk-carbon]: https://www.websitecarbon.com/website/mkdocs-org-getting-started/
[nx-carbon]: https://www.websitecarbon.com/website/nextra-site-docs-docs-theme-start/
[dy-carbon]: https://www.websitecarbon.com/website/docsify-js-org/
[ds-carbon]: https://www.websitecarbon.com/website/docusaurus-io-docs/
[rtd-carbon]: https://www.websitecarbon.com/website/docs-readthedocs-io-en-stable-index-html/
[gb-carbon]: https://www.websitecarbon.com/website/docs-gitbook-com/
[mt-carbon]: https://www.websitecarbon.com/website/mintlify-com-docs-quickstart/

## और अधिक संसाधन

### उपकरण

- [Website Carbon Calculator][wcc]
- [GreenFrame](https://greenframe.io/)
- [Ecograder](https://ecograder.com/)
- [WebPageTest Carbon Control](https://www.webpagetest.org/carbon-control/)
- [Ecoping](https://ecoping.earth/)

### लेख और वार्ता

- [“Building a greener web”](https://youtu.be/EfPoOt7T5lg), Michelle Barker द्वारा वार्ता
- [“Sustainable Web Development Strategies Within An Organization”](https://www.smashingmagazine.com/2022/10/sustainable-web-development-strategies-organization/), Michelle Barker का लेख
- [“A sustainable web for everyone”](https://2021.stateofthebrowser.com/speakers/tom-greenwood/), Tom Greenwood द्वारा वार्ता
- [“How Web Content Can Affect Power Usage”](https://webkit.org/blog/8970/how-web-content-can-affect-power-usage/), Benjamin Poulain और Simon Fraser का लेख

[sf]: https://www.sciencefocus.com/science/what-is-the-carbon-footprint-of-the-internet/
[bbc]: https://www.bbc.com/future/article/20200305-why-your-internet-habits-are-not-as-clean-as-you-think
[http]: https://httparchive.org/reports/state-of-the-web
[assets]: https://docs.astro.build/hi/guides/assets/
[islands]: https://docs.astro.build/hi/concepts/islands/
[wcc]: https://www.websitecarbon.com/


================================================
FILE: docs/src/content/docs/hi/getting-started.mdx
================================================
---
title: पहले कदम
description: जानें कि Astro द्वारा Starlight के साथ अपना अगला अगली दस्तावेज़ीकरण साइट का निर्माण कैसे शुरू करें।
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

Starlight [Astro](https://astro.build) फ्रेमवर्क के शीर्ष पर निर्मित एक पूर्ण-विशेषीकृत दस्तावेज़ीकरण थीम है।
यह मार्गदर्शिका आपको एक नई परियोजना शुरू करने में मदद करेगी।
मौजूदा Astro परियोजना में Starlight जोड़ने के लिए [मैन्युअल सेटअप निर्देश](/hi/manual-setup/) देखें।

## जल्दी शुरुआत करें

### एक नयी परियोजना बनाएं

अपने टर्मिनल में निम्नलिखित आदेश चलाकर एक नयी Astro + Starlight परियोजना बनाएं:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight
```

</TabItem>
</Tabs>

यह आपकी साइट के लिए सभी आवश्यक फ़ाइलों और कॉन्फ़िगरेशन के साथ एक नई [परियोजना निर्देशिका](/hi/guides/project-structure/) बनाएगा।

:::tip[इसे क्रियान्वित करके देखें]
अपने ब्राउज़र में Starlight आज़माएँ:
[StackBlitz पर टेम्पलेट खोलें](https://stackblitz.com/github/withastro/starlight/tree/main/examples/basics).
:::

### विकास सर्वर शुरू करें

स्थानीय स्तर पर काम करते समय, [Astro का विकास सर्वर](https://docs.astro.build/hi/reference/cli-reference/#astro-dev) आपको अपने काम का पूर्वावलोकन करने देता है और जब आप परिवर्तन करते हैं तो स्वचालित रूप से आपके ब्राउज़र को रीफ्रेश करता है।

अपनी परियोजना निर्देशिका के अंदर, विकास सर्वर शुरू करने के लिए निम्नलिखित आदेश चलाएँ:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm run dev
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dev
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dev
```

</TabItem>
</Tabs>

यह आपके स्थानीय पूर्वावलोकन के URL के साथ आपके टर्मिनल पर एक संदेश लॉग करेगा।
अपनी साइट ब्राउज़ करने के लिए इस URL को खोलें।

### सामग्री जोड़ें

Starlight आपके लिए नई सामग्री जोड़ने, या अपनी मौजूदा फ़ाइलें लाने के लिए तैयार है!

`src/content/docs/` निर्देशिका में Markdown फ़ाइलें बनाकर अपनी साइट पर नए पेज जोड़ें।

["पेज"](/hi/guides/pages/) गाइड में MDX और Markdoc फाइलों के लिए फ़ाइल-आधारित रूटिंग और समर्थन के बारे में और पढ़ें।

### अगले कदम

- **कॉन्फ़िगर:** ["कस्टमाइज़िंग स्टारलाइट"](/hi/guides/customization/) में सामान्य विकल्पों के बारे में जानें।
- **नेविगेट:** ["साइडबार नेविगेशन"](/hi/guides/sidebar/) गाइड के साथ अपना साइडबार सेट करें।
- **अवयवों:** ["अवयवों"](/hi/components/using-components/) मार्गदर्शिका में अंतर्निहित कार्ड, टैब और बहुत कुछ खोजें।
- **डिप्लॉय:** Astro Docs में ["अपनी साइट परिनियोजित करें"](https://docs.astro.build/hi/guides/deploy/) मार्गदर्शिका के साथ अपना कार्य प्रकाशित करें।

## Starlight को अद्यतन करें

:::tip
क्योंकि Starlight बीटा सॉफ्टवेयर है, इसमें लगातार अपडेट और सुधार होते रहेंगे। Starlight को नियमित रूप से अपडेट करना सुनिश्चित रखे!
:::

Starlight एक Astro एकीकरण है। आप अपने टर्मिनल में निम्नलिखित आदेश चलाकर इसे और अन्य Astro पैकेज का अद्यतन कर सकते हैं:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npx @astrojs/upgrade
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dlx @astrojs/upgrade
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dlx @astrojs/upgrade
```

</TabItem>
</Tabs>

प्रत्येक रिलीज़ में किए गए परिवर्तनों की पूरी सूची के लिए [Starlight चेंजलॉग](https://github.com/withastro/starlight/blob/main/packages/starlight/CHANGELOG.md) देखें।

## समस्या निवारण Starlight में

यह सुनिश्चित करने के लिए कि आपकी Starlight साइट कॉन्फ़िगर है और ठीक से काम कर रही है, [परियोजना कॉन्फ़िगरेशन](/hi/reference/configuration/) और [व्यक्तिगत पेज फ्रंटमैटर कॉन्फ़िगरेशन](/hi/reference/frontmatter/) संदर्भ पेजो का उपयोग करें।
सामग्री जोड़ने और अपनी स्टारलाइट साइट को अनुकूलित करने में सहायता के लिए साइडबार में मार्गदर्शिकाएँ देखें।

यदि आपका उत्तर इन दस्तावेज़ों में नहीं मिल सकता है, तो संपूर्ण Astro दस्तावेज़ीकरण के लिए कृपया [Astro दस्तावेज़](https://docs.astro.build/hi) देखें।
आपके प्रश्न का उत्तर यह समझकर दिया जा सकता है कि इस Starlight थीम के तहत Astro सामान्य रूप से कैसे काम करता है।

आप [GitHub पर किसी ज्ञात Starlight समस्या](https://github.com/withastro/starlight/issues) की भी जांच कर सकते हैं, और हमारे सक्रिय, मैत्रीपूर्ण समुदाय से [Astro Discord](https://astro.build/chat/) में सहायता प्राप्त कर सकते हैं! हमारे `#support` फोरम में "Starlight" टैग के साथ प्रश्न पोस्ट करें, या वर्तमान विकास और अधिक पर चर्चा करने के लिए हमारे समर्पित `#Starlight` चैनल पर जाएँ!


================================================
FILE: docs/src/content/docs/hi/index.mdx
================================================
---
title: Starlight 🌟 दस्तावेज़ीकरण साइटें बनाएं Astro के साथ
head:
  - tag: title
    content: Starlight 🌟 दस्तावेज़ीकरण साइटें बनाएं Astro के साथ
description: Starlight आपको Astro के साथ सुंदर, उच्च प्रदर्शन वाली दस्तावेज़ीकरण वेबसाइट बनाने में मदद करता है।
template: splash
editUrl: false
lastUpdated: false
hero:
  title: अपने दस्तावेज़ों को Starlight से चमकाएँ
  tagline: एक तारकीय दस्तावेज़ीकरण वेबसाइट बनाने के लिए आपको जो कुछ भी चाहिए वह सब कुछ इधर हैं। तेज़, अभिगम्य और उपयोग में आसान।
  image:
    file: ~/assets/hero-star.webp
  actions:
    - text: शुरू हो जाओ
      icon: right-arrow
      link: /hi/getting-started/
    - text: GitHub पर देखें
      icon: external
      variant: minimal
      link: https://github.com/withastro/starlight
---

import { CardGrid, Card } from '@astrojs/starlight/components';
import AboutAstro from '~/components/about-astro.astro';
import TestimonialGrid from '~/components/testimonial-grid.astro';
import Testimonial from '~/components/testimonial.astro';

<CardGrid stagger>
	<Card title="दस्तावेज़ीकरण जो आनंदित करता है" icon="open-book">
		इसमें शामिल हैं: साइट मार्गदर्शन, खोज, अंतर्राष्ट्रीयकरण, SEO, पढ़ने में
		आसान Typography, कोड हाइलाइटिंग, डार्क मोड और बहुत कुछ।
	</Card>
	<Card title="Astro द्वारा संचालित" icon="rocket">
		Astro की पूरी शक्ति और प्रदर्शन का लाभ उठाएं। विस्तार करें Starlight का अपने
		पसंदीदा Astro एकीकरण और लाइब्रेरी का उपयोग करके।
	</Card>
	<Card title="Markdown, Markdoc, और MDX" icon="document">
		अपनी पसंदीदा Markup भाषा लाएँ। Starlight आपको बिल्ट-इन फ्रंटमैटर मान्यकरण के
		साथ TypeScript प्रकार-सुरक्षा देता है ।
	</Card>
	<Card title="अपने स्वयं के UI अवयवों लाएँ" icon="puzzle">
		Starlight एक फ्रेमवर्क-अज्ञेयवादी, संपूर्ण दस्तावेज़ समाधान के रूप में
		उपलब्ध है। React, Vue, Svelte, Solid और अन्य के साथ विस्तार करें।
	</Card>
</CardGrid>

<TestimonialGrid title="जानिए लोग क्या कह रहे हैं">
  <Testimonial
    name="Rachel"
    handle="rachelnabors"
    cite="https://twitter.com/astrodotbuild/status/1724934718745915558"
  >
		Astro टीम ने विकसित किया है कैसे दस्तावेज़ बनाए जा सकते हैं और उनके Starlight परियोजना के साथ यह सब विशेषताएं सामने से उपलब्ध हैं आपके लिए
  </Testimonial>
  <Testimonial
    name="Flavio"
    handle="flaviocopes"
    cite="https://twitter.com/flaviocopes/status/1738237658717905108"
  >
		Astro की आधिकारिक स्टार्टर किट Starlight दस्तावेज़ीकरण वेबसाइट बनाने के लिए वास्तव में एक अविश्वसनीय उपकरण है
  </Testimonial>
  <Testimonial
    name="Tomek"
    handle="sulco"
    cite="https://twitter.com/sulco/status/1735610348730802342"
  >
		Starlight एक बेहतरीन DX का हमारा पसंदीदा उदाहरण है: गति, सुविधा और विस्तार पर ध्यान प्रेरणादायक है। यह प्रौद्योगिकी और दिखाव का ख्याल रखता है, ताकि आप अपनी सामग्री पर ध्यान केंद्रित कर सकें 👏
     
		StackBlitz टीम को यह बिल्कुल पसंद है!
  </Testimonial>
  <Testimonial
    name="Roberto"
    handle="RmeetsH"
    cite="https://twitter.com/RmeetsH/status/1735783992018760090"
  >
		Starlight मेरे लिए गेम-चेंजर रही है, जिससे मुझे सामग्री निर्माण पर ध्यान केंद्रित करने का मौका मिला है।

    इसका सहज डिज़ाइन न केवल मेरे कार्य प्रवाह को सुव्यवस्थित करता है बल्कि ओपन-स्त्रोत डेवलपर्स के लिए ज्ञानप्राप्ति समय को भी कम करता है।

  </Testimonial>
  <Testimonial
    name="Joel"
    handle="jhooks"
    cite="https://twitter.com/jhooks/status/1727405160547418405"
  >
		Course Builder दस्तावेज़ के लिए Starlight के साथ कुछ और समय बिताया और यह अब तक बहुत अच्छा रहा है। बहुत सारे अच्छे स्पर्श और Markdown में लिखने पर ध्यान केंद्रित किया जा सकता है न कि साइट के साथ खिलवाड़ करने पर।
  </Testimonial>
  <Testimonial
    name="Rick"
    handle="rick_viscomi"
    cite="https://twitter.com/rick_viscomi/status/1665867447910510593"
  >
		मेने Starlight के साथ खेलना शुरू किया. कहना होगा कि मैं इसके हटकर प्रदर्शन से बहुत प्रभावित हूं।

    💯💯💯💯

  </Testimonial>
  <Testimonial
    name="Nicolas"
    handle="beaussan"
    cite="https://twitter.com/beaussan/status/1735625189583466893"
  >
		Astro की शक्ति और गति और Starlight के टूलींग के बीच, दस्तावेज़ीकरण के साथ शुरुआत करने के लिए Starlight सबसे अच्छा तरीका है, यह स्वर्ग में एक जोड़ी है।

    पिछले कुछ समय से में यहाँ जा रहा हु और मुझे यह बहुत पसंद है!

  </Testimonial>
  <Testimonial
    name="Sylwia"
    handle="SylwiaVargas"
    cite="https://x.com/SylwiaVargas/status/1726556825741578286"
  >
		मैंने अपने आखिरी नौकरी में Starlight का उपयोग किया और मुझे यह बहुत पसंद आया। बेहतरीन अवयव, सहज ज्ञान युक्त डिजाइन और अति संवेदनशील समुदाय (जब भी किसी को कुछ चाहिए होता है, तो वे इसे तुरंत भेज देंगे या आपको समाधान बताएंगे)। बहुत ही सुखद अनुभव।
  </Testimonial>
  <Testimonial
    name="Lou Cyx"
    handle="loucyx"
    cite="https://elk.zone/m.webtoo.ls/@loucyx@mastodon.social/111587380021362284"
  >
		Starlight की बदौलत मेरी मोनोरेपो साइट के दस्तावेज़ पहले से कहीं बेहतर दिखते हैं। Astro की सारी शक्ति खोए बिना इसका उपयोग करना बेहद आसान है। इस पर काम करने के लिए धन्यवाद!
  </Testimonial>
  <Testimonial
    name="BowTiedWebReaper"
    handle="BowTiedWebReapr"
    cite="https://twitter.com/BowTiedWebReapr/status/1735633399501697517"
  >
		दस्तावेज़ीकरण के लिए Starlight मेरा पसंदीदा उपकरण है। इससे मेरी मौजूदा Astro उत्पाद वेबसाइट पर दस्तावेज़ जोड़ना बहुत आसान हो गया, बजाय किसी अन्य टूल के साथ उपयोग करने के लिए उपडोमेन की आवश्यकता होती है।
  </Testimonial>
  <Testimonial
    name="Jeff"
    handle="J_Everhart383"
    cite="https://twitter.com/J_Everhart383/status/1691900590048292908"
  >
		मैं WPEngine Atlas Platform दस्तावेज़ों का पुनर्निर्माण कर रहा हूँ। जब मैं कहता हूं कि Starlight में वह सब कुछ है जो आपको A+ दस्तावेज़ प्लेटफॉर्म बनाने के लिए चाहिए, तो मुझ पर विश्वास करें 🙌
  </Testimonial>
  <Testimonial
    name="Chloe"
    handle="solelychloe"
    cite="https://twitter.com/solelychloe/status/1695115277602628082"
  >
		Starlight को आज़माएं!

    हम इसे अपनी कुछ साइटों के लिए उपयोग करते हैं और यह बहुत बढ़िया है।

  </Testimonial>
</TestimonialGrid>

<AboutAstro title="आप तक लाने वाले हैं">
Astro गति के लिए डिज़ाइन किया गया ऑल-इन-वन वेब फ्रेमवर्क है।
अपने कंटेंट को कहीं से भी खींचें और हर जगह डिप्लॉय करें, यह सब आपके पसंदीदा UI अवयवों और लाइब्रेरीज़ द्वारा संचालित है।

[Astro के बारे में जानें](https://astro.build/)

</AboutAstro>


================================================
FILE: docs/src/content/docs/id/404.md
================================================
---
title: Halaman tidak ditemukan
template: splash
editUrl: false
lastUpdated: false
hero:
  title: '404'
  tagline: <strong>Houston, kita ada masalah.</strong> Halaman yang kita cari tidak ada.<br>Tolong cek kolom URL atau gunakan fitur pencarian.
  actions:
    - text: Beranda
      icon: right-arrow
      link: /id/
      variant: primary
---


================================================
FILE: docs/src/content/docs/id/environmental-impact.md
================================================
---
title: Dokumentasi yang ramah lingkungan
description: Pelajari bagaimana Starlight bisa membantu Anda membangun website dokumentasi yang lebih ramah lingkungan dan mengurangi jejak karbon Anda.
---

Estimasi dampak dari industri web terhadap iklim berkisar antara [2%][sf] hingga [4% dari emisi karbon global ][bbc], kira-kira setara dengan emisi industri penerbangan. Ada banyak faktor kompleks dalam menghitung dampak ekologis sebuah website, namun panduan ini mencakup beberapa tips untuk mengurangi jejak lingkungan dari website dokumentasi Anda.

Berita baiknya adalah, memilih Starlight adalah awal yang baik. Menurut Website Carbon Calculator, website ini [lebih bersih daripada 99% website-website yang telah diuji][sl-carbon], menghasilkan 0,01g CO₂ per kunjungan halaman.

## Berat halaman

Semakin banyak data yang ditransfer oleh sebuah halaman web, semakin banyak sumber daya energi yang diperlukan.
Pada bulan April 2023, nilai median dari banyaknya data yang harus di-_download_ user ketika mengakses sebuah halaman website adalah lebih dari 2.000 KB berdasarkan [data dari HTTP Archive][http].

Starlight membangun halaman-halaman yang seringan mungkin. Sebagai contoh, pada kunjungan pertama, pengguna hanya perlu mengunduh kurang dari 50 KB data yang telah dikompresi — hanya 2,5% dari nilai median HTTP Archive. Dengan strategi caching yang baik, kunjungan selanjutnya dapat mengunduh hanya sekitar 10 KB.

### Gambar

Meskipun Starlight memberikan basis yang baik, gambar yang Anda tambahkan ke halaman dokumentasi Anda dapat dengan cepat meningkatkan berat halaman Anda.
Starlight menggunakan [dukungan aset yang dioptimalkan][assets] dari Astro untuk mengoptimalkan gambar lokal dalam file Markdown dan MDX Anda.

### Komponen UI

Komponen yang dibangun dengan _UI frameworks_ seperti React atau Vue dapat dengan mudah menambahkan banyak JavaScript ke halaman.
Karena Starlight dibangun di atas Astro, komponen seperti ini secara default tidak memuat JavaScript di sisi klien berkat [Astro Islands][islands].

### Caching

_Caching_ digunakan untuk mengontrol berapa lama browser menyimpan dan menggunakan kembali data yang telah diunduh sebelumnya.
Strategi caching yang baik memastikan bahwa pengguna mendapatkan konten baru sesegera mungkin ketika ada perubahan, tetapi juga menghindari pengunduhan yang tidak perlu dari konten yang sama berulang kali ketika konten tersebut tidak mengalami perubahan.

Cara paling umum untuk mengonfigurasi caching adalah dengan menggunakan [`Cache-Control` HTTP header][cache].
Ketika menggunakan Starlight, Anda dapat mengatur waktu _cache_ yang lama untuk semua yang ada di direktori /\_astro/.
Direktori ini berisi CSS, JavaScript, dan aset lainnya yang dapat di-cache secara permanen, mengurangi pengunduhan yang tidak perlu:

```
Cache-Control: public, max-age=604800, immutable
```

Cara mengkonfigurasi caching tergantung pada penyedia hosting website Anda. Misalnya, Vercel menerapkan strategi caching ini untuk Anda tanpa ada konfigurasi yang diperlukan, sementara Anda dapat mengatur [header kustom untuk Netlify][ntl-headers] dengan menambahkan file `public/_headers` ke proyek Anda:

```
/_astro/*
  Cache-Control: public
  Cache-Control: max-age=604800
  Cache-Control: immutable
```

[cache]: https://csswizardry.com/2019/03/cache-control-for-civilians/
[ntl-headers]: https://docs.netlify.com/routing/headers/

## Konsumsi daya

Cara sebuah halaman web dibangun dapat mempengaruhi besarnya daya yang dibutuhkan untuk menjalankannya di perangkat pengguna.
Dengan menggunakan JavaScript yang minimal, Starlight mengurangi jumlah daya pemrosesan yang dibutuhkan oleh telepon, tablet, atau komputer pengguna untuk memuat dan merender halaman.

Perhatikan saat menambahkan fitur seperti skrip pelacakan analitik atau konten yang kaya akan JavaScript seperti video yang disematkan, karena hal ini dapat meningkatkan penggunaan daya halaman.
Jika Anda memerlukan analitik, pertimbangkan untuk memilih opsi yang lebih ringan seperti [Cabin][cabin], [Fathom][fathom], atau [Plausible][plausible].
Penyisipan video seperti YouTube dan Vimeo dapat ditingkatkan dengan menunggu [pemuatan video saat ada interaksi pengguna][lazy-video].
_Package_ seperti [astro-embed][embed] dapat membantu untuk layanan umum.

:::tip[Tahukah Anda?]
_Parsing_ dan kompilasi JavaScript adalah salah satu tugas yang paling mahal bagi browser.
Dibandingkan dengan merender gambar JPEG dengan ukuran yang sama, [pemrosesan JavaScript dapat memakan waktu lebih dari 30 kali lebih lama][cost-of-js].
:::

[cabin]: https://withcabin.com/
[fathom]: https://usefathom.com/
[plausible]: https://plausible.io/
[lazy-video]: https://web.dev/iframe-lazy-loading/
[embed]: https://www.npmjs.com/package/astro-embed
[cost-of-js]: https://medium.com/dev-channel/the-cost-of-javascript-84009f51e99e

## Hosting

Dimana website di-_hosting_ dapat memiliki dampak besar terhadap seberapa ramah lingkungan website dokumentasi Anda.
Pusat data dan rumah server dapat memiliki dampak ekologis yang besar, termasuk konsumsi listrik yang tinggi dan penggunaan air yang intensif.

Memilih penyedia hosting yang menggunakan energi terbarukan berarti emisi karbon yang lebih rendah untuk website Anda. [Green Web Directory][gwb] adalah salah satu alat yang dapat membantu Anda menemukan perusahaan hosting yang ramah lingkungan.

[gwb]: https://www.thegreenwebfoundation.org/directory/

## Perbandingan

Tertarik bagaimana perbandingannya dengan _framework_ dokumentasi lainnya? Tes ini dengan [Website Carbon Calculator][wcc] membandingkan halaman-halaman serupa yang dibangun dengan _tool_ yang berbeda.

| Framework                   | CO₂ per kunjungan halaman | Peringkat |
| --------------------------- | ------------------------- | :-------: |
| [Starlight][sl-carbon]      | 0.01g                     |    A+     |
| [Read the Docs][rtd-carbon] | 0.05g                     |    A+     |
| [Sphinx][sx-carbon]         | 0.06g                     |    A+     |
| [VitePress][vp-carbon]      | 0.07g                     |    A+     |
| [Docus][dc-carbon]          | 0.09g                     |    A+     |
| [docsify][dy-carbon]        | 0.10g                     |     A     |
| [Nextra][nx-carbon]         | 0.11g                     |     A     |
| [MkDocs][mk-carbon]         | 0.19g                     |     B     |
| [Docusaurus][ds-carbon]     | 0.21g                     |     B     |
| [GitBook][gb-carbon]        | 0.43g                     |     C     |
| [Mintlify][mt-carbon]       | 1.22g                     |     F     |

<small>Data dikumpulkan pada 22 Juli 2024. Klik link untuk melihat angka terkini.</small>

[sl-carbon]: https://www.websitecarbon.com/website/starlight-astro-build-getting-started/
[vp-carbon]: https://www.websitecarbon.com/website/vitepress-dev-guide-what-is-vitepress/
[dc-carbon]: https://www.websitecarbon.com/website/docus-dev-introduction-getting-started/
[sx-carbon]: https://www.websitecarbon.com/website/sphinx-doc-org-en-master-usage-quickstart-html/
[mk-carbon]: https://www.websitecarbon.com/website/mkdocs-org-getting-started/
[nx-carbon]: https://www.websitecarbon.com/website/nextra-site-docs-docs-theme-start/
[dy-carbon]: https://www.websitecarbon.com/website/docsify-js-org/
[ds-carbon]: https://www.websitecarbon.com/website/docusaurus-io-docs/
[rtd-carbon]: https://www.websitecarbon.com/website/docs-readthedocs-io-en-stable-index-html/
[gb-carbon]: https://www.websitecarbon.com/website/docs-gitbook-com/
[mt-carbon]: https://www.websitecarbon.com/website/mintlify-com-docs-quickstart/

## Sumber Tambahan

### Tools

- [Website Carbon Calculator][wcc]
- [GreenFrame](https://greenframe.io/)
- [Ecograder](https://ecograder.com/)
- [WebPageTest Carbon Control](https://www.webpagetest.org/carbon-control/)
- [Ecoping](https://ecoping.earth/)

### Articles and presentasi

- [“Building a greener web”](https://youtu.be/EfPoOt7T5lg), talk by Michelle Barker
- [“Sustainable Web Development Strategies Within An Organization”](https://www.smashingmagazine.com/2022/10/sustainable-web-development-strategies-organization/), article by Michelle Barker
- [“A sustainable web for everyone”](https://2021.stateofthebrowser.com/speakers/tom-greenwood/), talk by Tom Greenwood
- [“How Web Content Can Affect Power Usage”](https://webkit.org/blog/8970/how-web-content-can-affect-power-usage/), article by Benjamin Poulain and Simon Fraser

[sf]: https://www.sciencefocus.com/science/what-is-the-carbon-footprint-of-the-internet/
[bbc]: https://www.bbc.com/future/article/20200305-why-your-internet-habits-are-not-as-clean-as-you-think
[http]: https://httparchive.org/reports/state-of-the-web
[assets]: https://docs.astro.build/en/guides/assets/
[islands]: https://docs.astro.build/en/concepts/islands/
[wcc]: https://www.websitecarbon.com/


================================================
FILE: docs/src/content/docs/id/getting-started.mdx
================================================
---
title: Memulai
description: Pelajari cara membuat website dokumentasi baru Anda dengan Starlight oleh Astro.
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

Starlight adalah tema dokumentasi berfitur lengkap yang dibangun di atas _framework_ [Astro](https://astro.build).
Panduan ini akan membantu Anda memulai proyek baru.
Lihat [petunjuk penyiapan manual](/id/manual-setup/) untuk menambahkan Starlight ke proyek Astro yang sudah ada.

## Mulai Cepat

### Membuat proyek baru

Buat proyek Astro + Starlight baru dengan menjalankan perintah berikut di terminal Anda:

<Tabs>
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight
```

</TabItem>
</Tabs>

Perintah tersebut akan membuat [direktori proyek](/id/guides/project-structure/) baru berisikan seluruh file dan konfigurasi yang diperlukan untuk website Anda.

:::tip[Lihat itu beraksi]
Cobalah Starlight di browser Anda:
[buka dengan StackBlitz](https://stackblitz.com/github/withastro/starlight/tree/main/examples/basics).
:::

### Mulai server pengembangan

Ketika bekerja secara lokal, [server pengembangan Astro](https://docs.astro.build/en/reference/cli-reference/#astro-dev) memungkinkan Anda melihat pratinjau pekerjaan Anda dan secara otomatis me-_refresh_ peramban ketika Anda membuat perubahan.

Di dalam direktori proyek Anda, jalankan perintah berikut untuk memulai server pengembangan:

<Tabs>
<TabItem label="npm">

```sh
npm run dev
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dev
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dev
```

</TabItem>
</Tabs>

Ini akan mencatat pesan ke terminal Anda dengan URL pratinjau lokal Anda.
Buka URL tersebut untuk mulai menjelajahi situs Anda.

### Tambahkan konten

Starlight siap untuk ditambahkan konten baru, atau pindahkan konten Anda yang sudah ada!

Tambahkan halaman baru ke website anda dengan membuat file Markdown di direktori `src/content/docs/`.

Baca selengkapnya tentang perutean berbasis file serta dukungan untuk MDX dan Markdoc di panduan [“Halaman”](/id/guides/pages/).

### Langkah selanjutnya

- **Mengkonfigurasi:** Pelajari tentang opsi umum dalam ["Menyesuaikan Starlight”](/id/guides/customization/).
- **Navigasi:** Siapkan sidebar Anda dengan panduan ["Navigasi Sidebar”](/id/guides/sidebar/).
- **Komponen:** Temukan kartu, tab dan bawaan lainnya di dalam panduan ["Komponen”](/id/components/using-components/).
- **Sebarkan:** Publikasikan karya Anda dengan panduan [“_Deploy_ situs Anda”](https://docs.astro.build/en/guides/deploy/) di dokumentasi Astro.

## Memperbarui Starlight

:::tip
Karena Starlight adalah perangkat lunak beta, akan ada pembaruan dan peningkatan yang sering dilakukan.
Pastikan untuk memperbarui Starlight secara teratur!
:::

Starlight adalah integrasi Astro, dan diperbarui seperti integrasi `@astrojs/*` lainnya:

<Tabs>
<TabItem label="npm">

```sh
npm install @astrojs/starlight@latest
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm upgrade @astrojs/starlight --latest
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn upgrade @astrojs/starlight --latest
```

</TabItem>
</Tabs>

Lihat [_changelog_ Starlight](https://github.com/withastro/starlight/blob/main/packages/starlight/CHANGELOG.md) untuk daftar lengkap perubahan yang dibuat dalam setiap rilis.

## Troubleshooting Starlight

Gunakan [konfigurasi proyek](/id/reference/configuration/) dan halaman referensi [konfigurasi _frontmatter_ halaman individual](/id/reference/frontmatter/) untuk memastikan bahwa situs Starlight Anda telah dikonfigurasi dan berfungsi dengan baik.
Lihat panduan di _sidebar_ untuk bantuan menambahkan konten dan menyesuaikan situs Starlight Anda.

Jika jawaban Anda tidak dapat ditemukan dalam dokumentasi ini, silakan kunjungi [Dokumentasi Astro](https://docs.astro.build) untuk dokumentasi lengkap Astro.
Pertanyaan Anda mungkin terjawab dengan memahami cara kerja Astro secara umum, di bawah tema Starlight ini.

Anda juga dapat memeriksa masalah Starlight yang diketahui di [GitHub](https://github.com/withastro/starlight/issues), dan dapatkan bantuan di [Astro Discord](https://astro.build/chat/) dari komunitas kami yang aktif dan ramah! Kirimkan pertanyaan di forum `#support` kami dengan tag "starlight", atau kunjungi kanal `#starlight` khusus kami untuk mendiskusikan perkembangan terkini dan banyak lagi!


================================================
FILE: docs/src/content/docs/id/index.mdx
================================================
---
title: Starlight 🌟 Membangun website dokumentasi dengan Astro
head:
  - tag: title
    content: Starlight 🌟 Membangun website dokumentasi dengan Astro
description: Starlight membantu membangun website dokumentasi yang menawan dan berperforma tinggi dengan Astro.
template: splash
editUrl: false
lastUpdated: false
hero:
  title: Buat dokumentasi yang bersinar dengan Starlight
  tagline: Semua yang Anda butuhkan untuk membangun website dokumentasi yang luar biasa. Cepat, ramah pengguna, dan sangat mudah digunakan.
  image:
    file: ~/assets/hero-star.webp
  actions:
    - text: Memulai
      icon: right-arrow
      link: /id/getting-started/
    - text: Lihat di GitHub
      icon: external
      variant: minimal
      link: https://github.com/withastro/starlight
---

import { CardGrid, Card } from '@astrojs/starlight/components';
import AboutAstro from '~/components/about-astro.astro';
import TestimonialGrid from '~/components/testimonial-grid.astro';
import Testimonial from '~/components/testimonial.astro';

<CardGrid stagger>
	<Card title="Dokumentasi yang menawan" icon="open-book">
		Sudah termasuk: Navigasi website, pencarian, terjemahan, SEO, tipografi yang
		mudah dibaca, _code highlighting_, mode gelap, dan masih banyak lagi.
	</Card>
	<Card title="Berbasis Astro" icon="rocket">
		Manfaatkan kekuatan penuh dan performa Astro. Kembangkan Starlight dengan
		_library_ dan integrasi Astro favorit Anda.
	</Card>
	<Card title="Markdown, Markdoc, and MDX" icon="document">
		Gunakan bahasa markup favorit Anda. Starlight menyediakan validasi
		_frontmatter_ bawaan dengan TypeScript _type-safety_.
	</Card>
	<Card title="Gunakan komponen UI pilihan Anda" icon="puzzle">
		Starlight adalah solusi dokumentasi yang lengkap dan _framework-agnostic_.
		Kembangkan lebih jauh dengan React, Vue, Svelte, Solid, dan lain-lain.
	</Card>
</CardGrid>

<TestimonialGrid title="Apa yang orang katakan">
  <Testimonial
    name="Rachel"
    handle="rachelnabors"
    cite="https://twitter.com/astrodotbuild/status/1724934718745915558"
  >
    Tim Astro telah MERUBAH cara pembuatan dokumentasi dan Anda bisa mendapatkan semuanya langsung dengan proyek Starlight mereka.
  </Testimonial>
  <Testimonial
    name="Flavio"
    handle="flaviocopes"
    cite="https://twitter.com/flaviocopes/status/1738237658717905108"
  >
    Astros _starter kit_ resmi Starlight adalah alat yang benar-benar luar biasa untuk membangun situs web dokumentasi
  </Testimonial>
  <Testimonial
    name="Tomek"
    handle="sulco"
    cite="https://twitter.com/sulco/status/1735610348730802342"
  >
    Starlight adalah contoh terbaik DX yang hebat: kecepatan, kenyamanan, dan
	perhatian terhadap detailnya sangat menginspirasi. Ia memperhatikan teknologi dan tampilan,
	sehingga Anda dapat fokus pada konten Anda 👏

    Tim StackBlitz sangat menyukainya!

  </Testimonial>
  <Testimonial
    name="Roberto"
    handle="RmeetsH"
    cite="https://twitter.com/RmeetsH/status/1735783992018760090"
  >
    Starlight telah mengubah permainan bagi saya, memungkinkan saya untuk fokus pada pembuatan konten.

    Desainnya yang intuitif tidak hanya menyederhanakan alur kerja saya tetapi juga mengurangi waktu orientasi bagi pengembang _open-source_.

  </Testimonial>
  <Testimonial
    name="Joel"
    handle="jhooks"
    cite="https://twitter.com/jhooks/status/1727405160547418405"
  >
    Menghabiskan lebih banyak waktu dengan Starlight untuk dokumentasi Course Builder dan sejauh ini hasilnya sangat bagus. Banyak sentuhan yang bagus dan dapat fokus menulis dalam Markdown dan tidak mengutak-atik situs.
  </Testimonial>
  <Testimonial
    name="Rick"
    handle="rick_viscomi"
    cite="https://twitter.com/rick_viscomi/status/1665867447910510593"
  >
    Mulai bermain dengan Starlight. Harus saya akui saya sangat terkesan dengan kinerjanya saat pertama kali digunakan.

    💯💯💯💯

  </Testimonial>
  <Testimonial
    name="Nicolas"
    handle="beaussan"
    cite="https://twitter.com/beaussan/status/1735625189583466893"
  >
    Starlight adalah cara terbaik untuk memulai dokumentasi, antara 
	kekuatan dan kecepatan Astro, dan fitur dari Starlight, ini adalah pilihan yang 
	tepat.

    Ini telah menjadi pilihan saya untuk beberapa waktu sekarang, dan saya terus menyukainya!

  </Testimonial>
  <Testimonial
    name="Sylwia"
    handle="SylwiaVargas"
    cite="https://x.com/SylwiaVargas/status/1726556825741578286"
  >
    Saya menggunakan Starlight pada pekerjaan terakhir saya dan menyukainya. Komponen yang hebat, 
	desain yang intuitif, dan komunitas yang sangat responsif (kapan pun seseorang membutuhkan sesuatu, 
	mereka akan segera mengirimkannya atau memberi tahu Anda solusinya). Pengalaman yang sangat menyenangkan.
  </Testimonial>
  <Testimonial
    name="Lou Cyx"
    handle="loucyx"
    cite="https://elk.zone/m.webtoo.ls/@loucyx@mastodon.social/111587380021362284"
  >
    Dokumen di situs monorepo saya terlihat lebih baik dari sebelumnya berkat Starlight. Sangat mudah digunakan tanpa kehilangan semua kelebihan Astro. Terima kasih telah mengerjakannya!
  </Testimonial>
  <Testimonial
    name="BowTiedWebReaper"
    handle="BowTiedWebReapr"
    cite="https://twitter.com/BowTiedWebReapr/status/1735633399501697517"
  >
    Starlight adalah alat andalan saya untuk dokumentasi. Alat ini memudahkan saya menambahkan dokumen ke situs web produk Astro saya yang sudah ada, dibanding menggunakan subdomain untuk digunakan dengan alat lain.
  </Testimonial>
  <Testimonial
    name="Jeff"
    handle="J_Everhart383"
    cite="https://twitter.com/J_Everhart383/status/1691900590048292908"
  >
    Saya sedang membangun kembali dokumentasi WPEngine Atlas Platform. Percayalah ketika saya mengatakan Starlight memiliki semua yang Anda butuhkan untuk membuat platform dokumentasi A+ 🙌
  </Testimonial>
  <Testimonial
    name="Chloe"
    handle="solelychloe"
    cite="https://twitter.com/solelychloe/status/1695115277602628082"
  >
    Cobalah Starlight!

    Saya menggunakannya untuk beberapa situs saya dan hasilnya bagus.

  </Testimonial>
</TestimonialGrid>

<AboutAstro title="Dipersembahkan oleh">
Astro adalah _web framework_ serbaguna yang didesain untuk kecepatan.
Gunakan konten Anda dari sumber mana saja dan _deploy_ di mana saja, 
semuanya didukung oleh _library_ dan komponen UI favorit Anda.

[Pelajari tentang Astro](https://astro.build/)

</AboutAstro>


================================================
FILE: docs/src/content/docs/index.mdx
================================================
---
title: Starlight 🌟 Build documentation sites with Astro
head:
  - tag: title
    content: Starlight 🌟 Build documentation sites with Astro
description: Starlight helps you build beautiful, high-performance documentation websites with Astro.
template: splash
editUrl: false
lastUpdated: false
hero:
  title: Make your docs shine with Starlight
  tagline: Everything you need to build a stellar documentation website. Fast, accessible, and easy-to-use.
  image:
    file: ~/assets/hero-star.webp
  actions:
    - text: Get started
      icon: right-arrow
      link: /getting-started/
    - text: View on GitHub
      icon: external
      variant: minimal
      link: https://github.com/withastro/starlight
---

import { CardGrid, Card } from '@astrojs/starlight/components';
import AboutAstro from '~/components/about-astro.astro';
import TestimonialGrid from '~/components/testimonial-grid.astro';
import Testimonial from '~/components/testimonial.astro';

<CardGrid stagger>
	<Card title="Documentation that delights" icon="open-book">
		Includes: Site navigation, search, internationalization, SEO, easy-to-read
		typography, code highlighting, dark mode and more.
	</Card>
	<Card title="Powered by Astro" icon="rocket">
		Leverage the full power and performance of Astro. Extend Starlight with your
		favorite Astro integrations and libraries.
	</Card>
	<Card title="Markdown, Markdoc, and MDX" icon="document">
		Bring your favorite markup language. Starlight gives you built-in
		frontmatter validation with TypeScript type-safety.
	</Card>
	<Card title="Bring your own UI components" icon="puzzle">
		Starlight ships as a framework-agnostic, complete docs solution. Extend with
		React, Vue, Svelte, Solid, and more.
	</Card>
</CardGrid>

<TestimonialGrid title="What people are saying">
  <Testimonial
    name="Rachel"
    handle="rachelnabors"
    cite="https://twitter.com/astrodotbuild/status/1724934718745915558"
  >
    The Astro team have EVOLVED how docs can be done and you can get it all out of the box with their Starlight project.
  </Testimonial>
  <Testimonial
    name="Flavio"
    handle="flaviocopes"
    cite="https://twitter.com/flaviocopes/status/1738237658717905108"
  >
    Astro’s official starter kit Starlight is a truly incredible tool for building a documentation website
  </Testimonial>
  <Testimonial
    name="Tomek"
    handle="sulco"
    cite="https://twitter.com/sulco/status/1735610348730802342"
  >
    Starlight is our go-to example of a great DX: the speed, convenience, and
    attention to details is inspiring. It takes care of the tech and the looks,
    so you can focus on your content 👏

    StackBlitz team absolutely loves it!

  </Testimonial>
  <Testimonial
    name="Roberto"
    handle="RmeetsH"
    cite="https://twitter.com/RmeetsH/status/1735783992018760090"
  >
    Starlight has been a game-changer for me, allowing me to focus on content creation.

    Its intuitive design not only streamlines my workflow but also reduces onboarding time for open-source developers.

  </Testimonial>
  <Testimonial
    name="Joel"
    handle="jhooks"
    cite="https://twitter.com/jhooks/status/1727405160547418405"
  >
    Spent some more time with Starlight for the Course Builder docs and it’s been great so far. Lots of nice touches and can focus on writing in Markdown and not fiddling with the site.
  </Testimonial>
  <Testimonial
    name="Rick"
    handle="rick_viscomi"
    cite="https://twitter.com/rick_viscomi/status/1665867447910510593"
  >
    Started playing with Starlight. Gotta say I’m very impressed with the performance out of the box.

    💯💯💯💯

  </Testimonial>
  <Testimonial
    name="Nicolas"
    handle="beaussan"
    cite="https://twitter.com/beaussan/status/1735625189583466893"
  >
    Starlight is the best way to get started with documentation, between the
    power and speed of Astro, and the tooling from Starlight, it’s a match in
    heaven.

    It has been my go to for a while now, and I keep on loving it!

  </Testimonial>
  <Testimonial
    name="Sylwia"
    handle="SylwiaVargas"
    cite="https://x.com/SylwiaVargas/status/1726556825741578286"
  >
    I used Starlight in my last job and loved it. Great components, intuitive
    design, and super-responsive community (whenever anyone needed something,
    they’d ship it soonish or tell you a workaround). Very pleasant experience.
  </Testimonial>
  <Testimonial
    name="Lou Cyx"
    handle="loucyx"
    cite="https://elk.zone/m.webtoo.ls/@loucyx@mastodon.social/111587380021362284"
  >
    The docs on my monorepo site look better than ever thanks to Starlight. It’s extremely easy to use without losing all the power of Astro. Thank you for working on it!
  </Testimonial>
  <Testimonial
    name="BowTiedWebReaper"
    handle="BowTiedWebReapr"
    cite="https://twitter.com/BowTiedWebReapr/status/1735633399501697517"
  >
    Starlight is my go-to tool for documentation. It made it super easy to add docs to my existing Astro product website, vs needing a subdomain to use with another tool.
  </Testimonial>
  <Testimonial
    name="Jeff"
    handle="J_Everhart383"
    cite="https://twitter.com/J_Everhart383/status/1691900590048292908"
  >
    I’ve been rebuilding the WPEngine Atlas Platform docs. Trust me when I say Starlight has everything you need to make an A+ docs platform 🙌
  </Testimonial>
  <Testimonial
    name="Chloe"
    handle="solelychloe"
    cite="https://twitter.com/solelychloe/status/1695115277602628082"
  >
    Give Starlight a try!

    I use it for a few of my sites and it’s great.

  </Testimonial>
</TestimonialGrid>

<AboutAstro title="Brought to you by">
Astro is the all-in-one web framework designed for speed.
Pull your content from anywhere and deploy everywhere, all powered by your favorite UI components and libraries.

[Learn about Astro](https://astro.build/)

</AboutAstro>


================================================
FILE: docs/src/content/docs/it/404.md
================================================
---
title: Non trovato
template: splash
editUrl: false
lastUpdated: false
hero:
  title: '404'
  tagline: <strong>Houston, abbiamo un problema.</strong> Non siamo riusciti a trovare quella pagina.<br>Controlla l'URL o prova a utilizzare la barra di ricerca.
  actions:
    - text: Torna alla home
      icon: right-arrow
      link: /it/
      variant: primary
---


================================================
FILE: docs/src/content/docs/it/environmental-impact.md
================================================
---
title: Documentazione ecologica
description: Impara come Starlight può aiutarti a costruire siti per documentazione più verdi e ridurre la tua impronta ecologica.
---

Le stime dell'impatto ambientale del web si aggirano tra il [2%][sf] e il [4% delle emissioni globali di gas serra][bbc], equivalente circa alle emissioni dell'industria aerea.
Ci sono molti complessi fattori per calcolare l'impatto ambientale di un sito web, ma questa guida include dei consigli per ridurre l'impronta ecologica del tuo sito.

La buona notizia è che scegliere Starlight è un ottimo punto di partenza.
Secondo il Website Carbon Calculator, questo sito è [più pulito del 99% delle pagine web testate][sl-carbon], producendo 0,01 g di CO₂ per pagina visitata.

## Peso per pagina

Più dati una pagina web trasferisce, più risorse energetiche sono necessarie.
Nell'aprile 2023, la pagina web media richiede all'utente di scaricare più di 2.000 KB secondo i [dati dell'HTTP Archive][http].

Starlight costruisce le pagine nel modo più leggero possibile.
Per esempio, alla prima visita, l'utente scaricherà meno di 50 KB di dati compressi — soltanto il 2,5 % della media dell'HTTP Archive.
Inoltre, con una strategia appropriata di cache, successive visite potranno richiedere solamente 10 KB.

### Immagini

Anche se Starlight fornisce un buon punto di partenza, le immagini possono velocemente aumentare il peso della pagina.
Starlight usa il [supporto ottimizzato degli asset][assets] di Astro per ottimizzare le immagini nei file Markdown e MDX.

### Componenti UI

I componenti costruiti con framework UI come React o Vue possono facilmente aggiungere grandi quantità di JavaScript nella pagina.
Dato che Starlight è costruito su Astro, i componenti come questo caricano **zero JavaScript all'utente per default** grazie alle [Isole Astro][islands].

### Caching

La cache è utilizzata per salvare per un periodo di tempo dati già scaricati in modo che il browser possa riutilizzarli.
Una buona strategia di cache permette all'utente di scaricare nuovi contenuti il prima possibile quando cambiano, ma anche evitare di scaricare nuovamente gli stessi più volte quando non sono cambiati.

Il modo più comune per configurarla è grazie al [`Cache-Control` header HTTP][cache].
Quando si utilizza Starlight, puoi controllare per quanto tempo salvare in cache nella cartella `/_astro/`.
Questa cartella contiene CSS, JavaScript e altri asset che possono essere salvati in cache per sempre, riducendo download non necessari:

```
Cache-Control: public, max-age=604800, immutable
```

La configurazione della cache dipende dal tuo host. Per esempio, Vercel applica questa strategia di cache per te senza configurazione richiesta, mentre puoi specificare degli [headers personalizzati per Netlify][ntl-headers] aggiungendo il file `public/_headers` nel progetto:

```
/_astro/*
  Cache-Control: public
  Cache-Control: max-age=604800
  Cache-Control: immutable
```

[cache]: https://csswizardry.com/2019/03/cache-control-for-civilians/
[ntl-headers]: https://docs.netlify.com/routing/headers/

## Consumo energetico

Come una pagina web sia costruita può impattare l'energia richiesta per visualizzarla nel dispositivo dell'utente.
Starlight riduce il consumo energetico del cellulare, tablet o computer che l'utente utilizza sfruttando pochissimo JavaScript.

Bisogna fare attenzione quando si vuole aggiungere funzionalità come script analitici o contenuti che utilizzano grandi quantità di JavaScript come video incorporati, dato che questi possono aumentare il consumo energetico.
Se necessario, si considerino [Cabin][cabin], [Fathom][fathom], o [Plausible][plausible] per funzionalità analitiche siccome non sono pesanti.
Video integrati come YouTube e Vimeo possono essere migliorati aspettando di [caricare il video dopo interazione][lazy-video].
Pacchetti come [`astro-embed`][embed] possono aiutare per servizi comuni.

:::tip[Lo sapevi ?]
L'analisi e la compilazione di JavaScript è una delle operazioni più costose che il browser deve fare.
Se si confronta con la visualizzazione di un'immagine JPEG dello stesso peso, [JavaScript può richiedere anche più di 30 volte il tempo necessario per essere processato][cost-of-js].
:::

[cabin]: https://withcabin.com/
[fathom]: https://usefathom.com/
[plausible]: https://plausible.io/
[lazy-video]: https://web.dev/iframe-lazy-loading/
[embed]: https://www.npmjs.com/package/astro-embed
[cost-of-js]: https://medium.com/dev-channel/the-cost-of-javascript-84009f51e99e

## Hosting

La piattaforma utilizzata per hostare un sito può avere un impatto significativo per l'impronta ecologica.
I data center e server farm possono impattare di molto l'ambiente, usando grandi quantità di energia elettrica e d'acqua.

Scegliere un host che usi energia da fonti rinnovabili significa ridurre le emissioni di gas serra per il tuo sito. Il [Green Web Directory][gwb] è uno degli strumenti che si possono utilizzare per trovare host di questo tipo.

[gwb]: https://www.thegreenwebfoundation.org/directory/

## Comparazioni

Curioso di come altri framework per documentazioni si comparano?
Questi test eseguiti con [Website Carbon Calculator][wcc] confrontano pagine simili costruite con diversi framework.

| Framework                   | CO₂ per visita | Voto |
| --------------------------- | -------------- | :--: |
| [Starlight][sl-carbon]      | 0.01g          |  A+  |
| [Read the Docs][rtd-carbon] | 0.05g          |  A+  |
| [Sphinx][sx-carbon]         | 0.06g          |  A+  |
| [VitePress][vp-carbon]      | 0.07g          |  A+  |
| [Docus][dc-carbon]          | 0.09g          |  A+  |
| [docsify][dy-carbon]        | 0.10g          |  A   |
| [Nextra][nx-carbon]         | 0.11g          |  A   |
| [MkDocs][mk-carbon]         | 0.19g          |  B   |
| [Docusaurus][ds-carbon]     | 0.21g          |  B   |
| [GitBook][gb-carbon]        | 0.43g          |  C   |
| [Mintlify][mt-carbon]       | 1.22g          |  F   |

<small>Dati collezionati il 22 Luglio 2024. Clicca i link per vedere i dati aggiornati.</small>

[sl-carbon]: https://www.websitecarbon.com/website/starlight-astro-build-getting-started/
[vp-carbon]: https://www.websitecarbon.com/website/vitepress-dev-guide-what-is-vitepress/
[dc-carbon]: https://www.websitecarbon.com/website/docus-dev-introduction-getting-started/
[sx-carbon]: https://www.websitecarbon.com/website/sphinx-doc-org-en-master-usage-quickstart-html/
[mk-carbon]: https://www.websitecarbon.com/website/mkdocs-org-getting-started/
[nx-carbon]: https://www.websitecarbon.com/website/nextra-site-docs-docs-theme-start/
[dy-carbon]: https://www.websitecarbon.com/website/docsify-js-org/
[ds-carbon]: https://www.websitecarbon.com/website/docusaurus-io-docs/
[rtd-carbon]: https://www.websitecarbon.com/website/docs-readthedocs-io-en-stable-index-html/
[gb-carbon]: https://www.websitecarbon.com/website/docs-gitbook-com/
[mt-carbon]: https://www.websitecarbon.com/website/mintlify-com-docs-quickstart/

## Altre risorse

### Strumenti

- [Website Carbon Calculator][wcc]
- [GreenFrame](https://greenframe.io/)
- [Ecograder](https://ecograder.com/)
- [WebPageTest Carbon Control](https://www.webpagetest.org/carbon-control/)
- [Ecoping](https://ecoping.earth/)

### Articoli e discussioni

- [“Building a greener web”](https://youtu.be/EfPoOt7T5lg), conferenza di Michelle Barker
- [“Sustainable Web Development Strategies Within An Organization”](https://www.smashingmagazine.com/2022/10/sustainable-web-development-strategies-organization/), articolo di Michelle Barker
- [“A sustainable web for everyone”](https://2021.stateofthebrowser.com/speakers/tom-greenwood/), conferenza di Tom Greenwood
- [“How Web Content Can Affect Power Usage”](https://webkit.org/blog/8970/how-web-content-can-affect-power-usage/), articolo di Benjamin Poulain e Simon Fraser

[sf]: https://www.sciencefocus.com/science/what-is-the-carbon-footprint-of-the-internet/
[bbc]: https://www.bbc.com/future/article/20200305-why-your-internet-habits-are-not-as-clean-as-you-think
[http]: https://httparchive.org/reports/state-of-the-web
[assets]: https://docs.astro.build/en/guides/assets/
[islands]: https://docs.astro.build/en/concepts/islands/
[wcc]: https://www.websitecarbon.com/


================================================
FILE: docs/src/content/docs/it/getting-started.mdx
================================================
---
title: Come iniziare
description: Scopri come iniziare a costruire il tuo prossimo sito di documentazione con Starlight di Astro.
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

Starlight è un tema di documentazione completo di funzionalità costruito sulla base del framework [Astro](https://astro.build/it/).
Questa guida ti aiuterà a iniziare con un nuovo progetto.
Consulta le [istruzioni di configurazione manuale](/it/manual-setup/) per aggiungere Starlight a un progetto Astro esistente.

## Avvio Rapido

### Crea un nuovo progetto

Crea un nuovo progetto Astro + Starlight eseguendo il seguente comando nel tuo terminale:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight
```

</TabItem>
</Tabs>

Questo creerà una nuova [directory di progetto](/it/guides/project-structure/) con tutti i file e le configurazioni necessari per il tuo sito.

:::tip[Vedilo in azione]
Prova Starlight nel tuo browser:
[apri il modello su StackBlitz](https://stackblitz.com/github/withastro/starlight/tree/main/examples/basics).
:::

### Avvia il server di sviluppo

Quando lavori in locale, il [server di sviluppo di Astro](https://docs.astro.build/it/reference/cli-reference/#astro-dev) ti consente di visualizzare in anteprima il tuo lavoro e aggiorna automaticamente il browser quando apporti modifiche.

All'interno della directory del progetto, esegui il seguente comando per avviare il server di sviluppo:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm run dev
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dev
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dev
```

</TabItem>
</Tabs>

Questo registrerà un messaggio nel tuo terminale con l'URL dell'anteprima locale.
Apri questo URL per iniziare a navigare nel tuo sito.

### Aggiungi contenuti

Starlight è pronto per aggiungere nuovi contenuti o portare i tuoi file esistenti!

Aggiungi nuove pagine al tuo sito creando file Markdown nella directory `src/content/docs/`.

Leggi di più sulla navigazione basata su file e sul supporto per i file MDX e Markdoc nella guida [“Pagine”](/it/guides/pages/).

### Prossimi passi

- **Configura:** scopri le opzioni comuni in ["Personalizzazione di Starlight"](/it/guides/customization/).
- **Naviga:** configura la tua barra laterale con la guida ["Navigazione laterale"](/it/guides/sidebar/).
- **Componenti:** scopri schede incorporate, tabulazioni e altro nella guida ["Componenti"](/it/components/using-components/).
- **Distribuisci:** pubblica il tuo lavoro con la guida ["Distribuisci il tuo sito"](https://docs.astro.build/it/guides/deploy/) nella documentazione di Astro.

## Aggiorna Starlight

:::tip
Poiché Starlight è un software beta, ci saranno frequenti aggiornamenti e miglioramenti.
Assicurati di aggiornare regolarmente Starlight!
:::

Starlight è un'integrazione Astro. Puoi aggiornarlo e aggiornare altri pacchetti Astro eseguendo il seguente comando nel tuo terminale:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npx @astrojs/upgrade
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dlx @astrojs/upgrade
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dlx @astrojs/upgrade
```

</TabItem>
</Tabs>

Consulta il [changelog di Starlight](https://github.com/withastro/starlight/blob/main/packages/starlight/CHANGELOG.md) per un elenco completo delle modifiche apportate in ogni versione.

## Risoluzione dei problemi di Starlight

Usa le pagine di riferimento della [configurazione del progetto](/it/reference/configuration/) e della [configurazione frontmatter della singola pagina](/it/reference/frontmatter/) per assicurarti che il tuo sito Starlight sia configurato e funzionante correttamente.
Consulta le guide nella barra laterale per aiutarti ad aggiungere contenuti e personalizzare il tuo sito Starlight.

Se la tua risposta non può essere trovata in questa documentazione, visita la [documentazione completa di Astro](https://docs.astro.build/it/) per la documentazione completa di Astro.
La tua domanda potrebbe trovare risposta comprendendo il funzionamento generale di Astro, sotto questo tema Starlight.

Puoi anche controllare eventuali [problemi noti di Starlight su GitHub](https://github.com/withastro/starlight/issues) e ottenere aiuto nel [Discord di Astro](https://astro.build/chat/) dalla nostra comunità attiva e amichevole! Pubblica domande nel nostro forum `#support` con il tag "starlight" o visita il nostro canale dedicato `#starlight` per discutere degli sviluppi attuali e di altro ancora!


================================================
FILE: docs/src/content/docs/it/index.mdx
================================================
---
title: Starlight 🌟 Costruire siti per documentazione con Astro
head:
  - tag: title
    content: Starlight 🌟 Costruire siti per documentazione con Astro
description: Starlight ti aiuta a creare siti belli e performanti con Astro.
template: splash
editUrl: false
lastUpdated: false
hero:
  title: Fai brillare la tua documentazione con Starlight
  tagline: Tutto quello di cui hai bisogno per creare documentazione stellare. Veloce, accessibile e facile da usare.
  image:
    file: ~/assets/hero-star.webp
  actions:
    - text: Inizia
      icon: right-arrow
      link: /it/getting-started/
    - text: Vedi su GitHub
      icon: external
      variant: minimal
      link: https://github.com/withastro/starlight
---

import { CardGrid, Card } from '@astrojs/starlight/components';
import AboutAstro from '~/components/about-astro.astro';
import TestimonialGrid from '~/components/testimonial-grid.astro';
import Testimonial from '~/components/testimonial.astro';

<CardGrid stagger>
	<Card title="Documentazione che delizia" icon="open-book">
		Include: Navigazione, ricerca, internazionalizzazione, SEO, caratteri facili
		da leggere, evidenziazione del codice, tema scuro e altro.
	</Card>
	<Card title="Basato su Astro" icon="rocket">
		Sfrutta la potenza di Astro. Estendi Starlight con le tue integrazioni e
		librerie preferite.
	</Card>
	<Card title="Markdown, Markdoc e MDX" icon="document">
		Utilizza il tuo linguaggio markup preferito. Starlight fornisce validazione
		frontmatter con TypeScript.
	</Card>
	<Card title="Utilizza i tuoi componenti UI" icon="puzzle">
		Starlight è una soluzione indipendente da framework. Estendi come vuoi con
		React, Vue, Svelte, Solid e altro.
	</Card>
</CardGrid>

<TestimonialGrid title="Cosa dicono le persone">
  <Testimonial
    name="Rachel"
    handle="rachelnabors"
    cite="https://twitter.com/astrodotbuild/status/1724934718745915558"
  >
    Il team di Astro ha FATTO EVOLVERE il modo in cui la documentazione può essere realizzata e puoi ottenerla tutta out-of-the-box con il loro progetto Starlight.
  </Testimonial>
  <Testimonial
    name="Flavio"
    handle="flaviocopes"
    cite="https://twitter.com/flaviocopes/status/1738237658717905108"
  >
    Lo starter kit ufficiale di Astro Starlight è uno strumento davvero incredibile per costruire un sito web di documentazione
  </Testimonial>
  <Testimonial
    name="Tomek"
    handle="sulco"
    cite="https://twitter.com/sulco/status/1735610348730802342"
  >
    Starlight è il nostro esempio di riferimento di una grande esperienza utente: la velocità, la comodità e
    l'attenzione ai dettagli è fonte di ispirazione. Si occupa della parte tecnica e dell'aspetto,
    in modo che tu possa concentrarti sui tuoi contenuti 👏
     
    Il team di StackBlitz lo adora assolutamente!
  </Testimonial>
  <Testimonial
    name="Roberto"
    handle="RmeetsH"
    cite="https://twitter.com/RmeetsH/status/1735783992018760090"
  >
		Starlight è stato un game changer per me, permettendomi di concentrarmi sulla creazione di contenuti.

    	Il suo design intuitivo non solo ottimizza il mio flusso di lavoro ma riduce anche il tempo di onboarding per gli sviluppatori open source.

  </Testimonial>
  <Testimonial
    name="Joel"
    handle="jhooks"
    cite="https://twitter.com/jhooks/status/1727405160547418405"
  >
		Ho trascorso un po' più di tempo con Starlight per la documentazione di Course Builder ed è stato ottimo finora. Molte funzionalità utili e in più posso concentrarmi sulla scrittura in Markdown e non smanettare con il sito.
  </Testimonial>
  <Testimonial
    name="Rick"
    handle="rick_viscomi"
    cite="https://twitter.com/rick_viscomi/status/1665867447910510593"
  >
		Ho iniziato a giocare con Starlight. Devo dire che sono molto colpito dalle prestazioni out-of-the-box.

    	💯💯💯💯

  </Testimonial>
  <Testimonial
    name="Nicolas"
    handle="beaussan"
    cite="https://twitter.com/beaussan/status/1735625189583466893"
  >
		Starlight è il modo migliore per iniziare con la documentazione, tra
		la potenza e la velocità di Astro, e gli strumenti di Starlight, è un match in
		paradiso.

    	È stato il mio riferimento per un po' di tempo, e continuo ad amarlo!

  </Testimonial>
  <Testimonial
    name="Sylwia"
    handle="SylwiaVargas"
    cite="https://x.com/SylwiaVargas/status/1726556825741578286"
  >
		Ho usato Starlight nel mio ultimo lavoro e mi è piaciuto molto. Ottimi componenti, design
		intuitivo e community super-reattiva (ogni volta che qualcuno aveva bisogno di qualcosa,
		loro lo avrebbero implementato quasi subito oppure ti avrebbero detto una soluzione alternativa). Esperienza molto piacevole.
  </Testimonial>
  <Testimonial
    name="Lou Cyx"
    handle="loucyx"
    cite="https://elk.zone/m.webtoo.ls/@loucyx@mastodon.social/111587380021362284"
  >
		La documentazione sul mio sito monorepo sembra migliore che mai grazie a Starlight. È estremamente facile da usare senza perdere tutta la potenza di Astro. Grazie per averci lavorato!
  </Testimonial>
  <Testimonial
    name="BowTiedWebReaper"
    handle="BowTiedWebReapr"
    cite="https://twitter.com/BowTiedWebReapr/status/1735633399501697517"
  >
		Starlight è il mio strumento di riferimento per la documentazione. Ha reso super facile aggiungere la documentazione al mio sito web di prodotto fatto con Astro, rispetto alla necessità di usare un sottodominio con un altro strumento.
  </Testimonial>
  <Testimonial
    name="Jeff"
    handle="J_Everhart383"
    cite="https://twitter.com/J_Everhart383/status/1691900590048292908"
  >
		Sto ricostruendo la documentazione della piattaforma WPEngine Atlas. Credimi quando dico che Starlight ha tutto ciò di cui hai bisogno per creare una piattaforma di documentazione di classe A 🙌
  </Testimonial>
  <Testimonial
    name="Chloe"
    handle="solelychloe"
    cite="https://twitter.com/solelychloe/status/1695115277602628082"
  >
		Prova Starlight!

    	Lo uso per alcuni dei miei siti ed è fantastico.

  </Testimonial>
</TestimonialGrid>

<AboutAstro title="Sviluppato da">
Astro è un framework completo progettato per essere veloce.
Prendi i tuoi contenuti da dove preferisci e pubblica dove vuoi, il tutto con i tuoi componenti UI e librerie preferite.

[Impara di più su Astro](https://astro.build/)

</AboutAstro>


================================================
FILE: docs/src/content/docs/it/resources/community-content.mdx
================================================
---
title: Contenuti della community
description: Scopri guide, articoli e video prodotti dalla community per imparare e costruire con Starlight!
---

:::tip[Aggiungi il tuo!]
Hai prodotto dei contenuti su Starlight?
Apri una PR aggiungendo un link a questa pagina!
:::

import { CardGrid, LinkCard } from '@astrojs/starlight/components';

## Articoli e recensioni

Qui trovi una raccolta di post e articoli per saperne di più su Starlight e le esperienze di altre persone:

<CardGrid>
	<LinkCard
		href="https://devm.io/open-source/starlight-astro"
		title="Generazione di siti statici con Starlight"
		description="“Nessuna idea è troppo grande o troppo piccola quando si progettano componenti” — intervista con Chris Swithinbank, leader di Starlight"
	/>
	<LinkCard
		href="https://frontendatscale.com/blog/hybrid-frontend-architecture/"
		title="Architettura frontend ibrida con Astro e Starlight"
		description="Maxi Ferreira e Ben Holmes costruiscono un sito di documentazione con Starlight, TinaCMS e un Playground API interattivo con autenticazione."
	/>
	<LinkCard
		href="https://www.olets.dev/posts/comparing-docs-site-builders-vuepress-vs-starlight/"
		title="Confronto tra generatori di siti di documentazione: VuePress vs Starlight"
		description="Come si confrontano i due framework?"
	/>
</CardGrid>

## Ricette e guide

Le ricette sono tipicamente brevi guide pratiche che guidano il lettore attraverso il completamento di un esempio funzionante per uno specifico compito. Le ricette sono un ottimo modo per aggiungere nuove funzionalità o comportamenti al tuo progetto Starlight seguendo istruzioni passo passo! Altre guide potrebbero spiegare concetti specifici, come l'uso di immagini o come si lavora con MDX.

Esplora i contenuti prodotti dalla community e gestiti dagli utenti di Starlight:

<CardGrid>
	<LinkCard
		href="https://www.webpro.nl/scraps/versioned-docs-with-starlight-and-vercel"
		title="Documentazione versionata con Starlight e Vercel"
		description="Una guida all'implementazione di versioni separate della documentazione per ogni versione principale di un progetto"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-heading-links"
		title="Aggiungi link agli heading di Starlight"
		description="Una guida all'uso di un plugin rehype per condividere link a sezioni specifiche della tua documentazione"
	/>
	<LinkCard
		href="https://blog.otterlord.dev/posts/starlight-sponsors/"
		title="Aggiungi sponsor al tuo sito Starlight"
		description="Una guida per implementare un componente sponsor personalizzato nella sidebar della tua documentazione"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-og-images"
		title="Aggiungi immagini Open Graph a Starlight"
		description="Una guida alla generazione di immagini social e dei tag meta corrispondenti per le tue pagine"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-third-party-icon-sets"
		title="Usa set di icone di terze parti in Starlight"
		description="Una guida all'uso di unplugin-icons per espandere la selezione di icone disponibili per Starlight"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-custom-html-head"
		title="Modifica l'HTML head delle pagine di Starlight"
		description="Scopri come aggiungere contenuti comuni per l'head come analytics web, font e script"
	/>
	<LinkCard
		href="https://dev.to/mrrobot/publishing-documentation-with-astro-starlight-691"
		title="Pubblicare documentazione con Astro Starlight"
		description="Come iniziare con la documentazione Starlight"
	/>
	<LinkCard
		href="https://events-3bg.pages.dev/jotter/starlight/guide/"
		title="Abilita le Transizioni di Vista"
		description="Ottieni quell'aspetto e sensazione simile a SPA con il supporto alle transizioni di vista di Bag of Tricks"
	/>
	<LinkCard
		href="https://jamcomments.com/posts/structured-data-with-starlight"
		title="Aggiungere Dati Strutturati alle Pagine Starlight"
		description="Impara come costruire dati strutturati JSON-LD dinamici per le tue pagine di documentazione."
	/>
	<LinkCard
		href="https://starlight-examples.netlify.app/"
		title="Esempi Starlight"
		description="Una raccolta di embed StackBlitz che dimostrano modi pratici di fare cose nei siti di documentazione Starlight."
	/>
</CardGrid>

## Contenuti video

Scopri video e canali con contenuti Starlight, incluse live streaming e contenuti educativi.

import YouTubeGrid from '~/components/youtube-grid.astro';

### Video di Astro

<YouTubeGrid
	videos={[
		{
			href: 'https://www.youtube.com/watch?v=5u0Ds7wzUeI',
			title: 'Starlight by Astro',
			description: 'Guarda il video di lancio ufficiale di Starlight',
		},
		{
			href: 'https://www.youtube.com/shorts/zjOWezSzd18',
			title: '🌟 ESECUZIONE IN MENO DI 1 MINUTO',
			description:
				'Guarda Ben lanciare un nuovo sito Starlight in meno di un minuto!',
		},
	]}
/>

### Video e Streaming della Community

<YouTubeGrid
	videos={[
		{
			href: 'https://www.youtube.com/watch?v=sF6UcV3moZg',
			title: 'Costruire documentazione con Starlight e Astro',
			description:
				'Guarda Chris e Alex immergersi in Starlight su Code with CodingCat.dev',
		},
		{
			href: 'https://www.youtube.com/watch?v=sWkkHbwDeQc',
			title: 'Astro Starlight',
			description: 'Introduzione a Starlight in meno di un minuto.',
		},
		{
			href: 'https://www.youtube.com/watch?v=-Ki-1E5gNCk',
			title:
				'Template di Documentazione Astro Starlight (costruisci documentazione per app personalizzate!)',
			description: 'Metti in piedi un nuovo sito Starlight in circa 5 minuti',
		},
		{
			href: 'https://www.youtube.com/watch?v=12o7WxjAxjM',
			title:
				'Includere documentazione Starlight in un progetto Next.js con proxy',
			description:
				"Configura Starlight come progetto in una sotto-directory all'interno di un sito web Next.js",
		},
		{
			href: 'https://www.youtube.com/watch?v=5pq80drDrNs',
			title:
				'Ho Ricreato la Documentazione di Shadcn in 30 Minuti Con Questo Fantastico Strumento',
			description:
				'In questo video spiego cosa rende Starlight così cool e perché potresti volerlo provare nel tuo prossimo progetto.',
		},
		{
			href: 'https://www.youtube.com/watch?v=Q1E4Gkt63ko',
			title: 'Astro Starlight ed emoji-blast con Chris Swithinbank',
			description:
				'In cui Chris, il creatore del framework-su-framework Starlight di Astro, mi guida attraverso la sua configurazione per un nuovo sito web emoji-blast. 🌟 🎇',
		},
	]}
/>


================================================
FILE: docs/src/content/docs/it/resources/plugins.mdx
================================================
---
title: Plugin e integrazioni
description: Scopri strumenti della community come plugin e integrazioni che estendono Starlight!
sidebar:
  order: 1
---

:::tip[Aggiungi il tuo!]
Hai costruito un plugin o uno strumento per Starlight?
Apri una PR aggiungendo un link a questa pagina!
:::

## Plugins

[I plugin](/it/reference/plugins/) possono personalizzare la configurazione, interfaccia utente e comportamento di Starlight, rendendo allo stesso tempo facile la condivisione e il riutilizzo.
Estendi il tuo sito con plugin ufficiali supportati dal team Starlight e plugin della community gestiti dagli utenti Starlight.

### Plugin ufficiali

<CardGrid>
	<LinkCard
		href="/it/guides/site-search/#algolia-docsearch"
		title="Algolia DocSearch"
		description="Sostituisci Pagefind, il provider di ricerca predefinito, con Algolia DocSearch."
	/>
</CardGrid>

### Plugin della community

<CardGrid>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-links-validator"
		title="starlight-links-validator"
		description="Controlla i link rotti nelle tue pagine Starlight."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-typedoc"
		title="starlight-typedoc"
		description="Genera pagine Starlight da TypeScript usando TypeDoc."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-blog"
		title="starlight-blog"
		description="Aggiungi un blog alla tua documentazione."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-openapi"
		title="starlight-openapi"
		description="Crea pagine di documentazione dalle specificazioni OpenAPI/Swagger."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-obsidian"
		title="starlight-obsidian"
		description="Pubblica i tuoi vault Obsidian nel tuo sito Starlight."
	/>
	<LinkCard
		href="https://astro-ghostcms.xyz/intro/starlight/install/"
		title="starlight-ghostcms"
		description="Aggiungi i tuoi post del blog GhostCMS insieme alla tua documentazione Starlight."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-image-zoom"
		title="starlight-image-zoom"
		description="Aggiungi la possibilità di ingrandire le immagini della tua documentazione."
	/>
	<LinkCard
		href="https://github.com/lorenzolewis/starlight-utils"
		title="starlight-utils"
		description="Estendi Starlight con una collezione di utilità comuni."
	/>
	<LinkCard
		href="https://github.com/trueberryless/starlight-view-modes"
		title="starlight-view-modes"
		description="Aggiungi capacità di diverse modalità di visualizzazione al tuo sito di documentazione."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-versions"
		title="starlight-versions"
		description="Versiona le tue pagine di documentazione Starlight."
	/>
	<LinkCard
		href="https://inox-tools.fryuni.dev/star-warp"
		title="star-warp"
		description="Accedi ai risultati di ricerca per la tua documentazione alla velocità della luce."
	/>
</CardGrid>

### Temi della comunità

Un tema è un plugin di Starlight che modifica l'aspetto visivo di un sito con sostituzioni di componenti, CSS personalizzato o altre nuove funzionalità.

<CardGrid>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-theme-rapide"
		title="starlight-theme-rapide"
		description="Tema Starlight ispirato al tema Vitesse di Visual Studio Code."
	/>
</CardGrid>

## Strumenti e integrazioni della community

import { CardGrid, LinkCard } from '@astrojs/starlight/components';

Questi strumenti e integrazioni della community possono essere utilizzati per aggiungere funzionalità al tuo sito Starlight.

<CardGrid>
	<LinkCard
		href="https://www.feelback.dev/blog/new-astro-starlight-integration/"
		title="FeelBack"
		description="Aggiungi un sistema di feedback utente alle tue pagine di documentazione."
	/>
	<LinkCard
		href="https://github.com/val-town/notion-to-astro"
		title="notion-to-astro"
		description="Converti la tua documentazione da Notion a Starlight"
	/>
	<LinkCard
		href="https://github.com/mattjennings/astro-live-code"
		title="astro-live-code"
		description="Rendi interattivi i blocchi di codice MDX"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-i18n"
		title="starlight-i18n"
		description="Estensione di Visual Studio Code che ti aiuta a tradurre le pagine Starlight."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-package-managers"
		title="starlight-package-managers"
		description="Visualizza rapidamente i comandi relativi a npm per diversi gestori di pacchetti."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-showcases"
		title="starlight-showcases"
		description="Set di componenti Starlight per creare pagine di showcase."
	/>
</CardGrid>


================================================
FILE: docs/src/content/docs/it/resources/showcase.mdx
================================================
---
title: Vetrina Starlight
description: Scopri i siti creati con Starlight!
sidebar:
  label: Vetrina siti
---

:::tip[Aggiungi il tuo!]
Hai creato un sito con Starlight?
[Apri una PR](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md#showcase) così da aggiungere un link a questa pagina!
:::

## Siti

import ShowcaseSites from '~/components/showcase-sites.astro';

Starlight è già utilizzato in produzione. Questi sono alcuni dei siti che lo usano:

<ShowcaseSites />

Vedi tutte le [repository di progetti pubblici che usano Starlight su GitHub](https://github.com/withastro/starlight/network/dependents).


================================================
FILE: docs/src/content/docs/ja/404.md
================================================
---
title: 見つかりませんでした
template: splash
editUrl: false
lastUpdated: false
hero:
  title: '404'
  tagline: <strong>Houston、問題が生じました。</strong>ページが見つかりませんでした。<br>URLを確認するか、検索バーを使用してみてください。
  actions:
    - text: ホームに戻る
      icon: right-arrow
      link: /ja/
      variant: primary
---


================================================
FILE: docs/src/content/docs/ja/components/asides.mdx
================================================
---
title: 補足情報
description: Starlightで補足情報を使用して、ページのメインコンテンツの横に補足情報を表示する方法を学びます。
---

import { Aside } from '@astrojs/starlight/components';

ページのメインコンテンツの横に補足情報を表示するには、`<Aside>`コンポーネントを使用します。

import Preview from '~/components/component-preview.astro';

<Preview>
<Aside slot="preview">
    `<Aside>`に重要ではない補足情報を含めます。
</Aside>
</Preview>

## インポート

```tsx
import { Aside } from '@astrojs/starlight/components';
```

## 使用方法

`<Aside>`コンポーネントを使用して補足情報(「アドモニション」や「コールアウト」とも呼ばれる)を表示します。

`<Aside>`にはオプションの[`type`](#type)属性があり、これによって補足情報の色、アイコン、およびデフォルトのタイトルが制御されます。

<Preview>

````mdx
import { Aside } from '@astrojs/starlight/components';

<Aside>補足情報のコンテンツ。</Aside>

<Aside type="caution">注意が必要なコンテンツ。</Aside>

<Aside type="tip">

補足情報には他のコンテンツも対応しています。

```js
// たとえば、コードスニペットなど。
```

</Aside>

<Aside type="danger">パスワードを誰にも教えないでください。</Aside>
````

<Fragment slot="markdoc">

````markdoc
{% aside %}
補足情報のコンテンツ。
{% /aside %}

{% aside type="caution" %}
注意が必要なコンテンツ。
{% /aside %}

{% aside type="tip" %}
補足情報には他のコンテンツも対応しています。

```js
// たとえば、コードスニペットなど。
```
{% /aside %}

{% aside type="danger" %}
パスワードを誰にも教えないでください。
{% /aside %}
````

</Fragment>

<Fragment slot="preview">

    <Aside>補足情報のコンテンツ。</Aside>

    <Aside type="caution">注意が必要なコンテンツ。</Aside>

    <Aside type="tip">

    補足情報には他のコンテンツも対応しています。

    ```js
    // たとえば、コードスニペットなど。
    ```
    </Aside>

    <Aside type="danger">パスワードを誰にも教えないでください。</Aside>

</Fragment>

</Preview>

Starlightは、`<Aside>`コンポーネントの代替として、MarkdownとMDXで補足情報をレンダリングするためのカスタム構文も提供しています。
カスタム構文の詳細については、["MarkdownでのContent作成"](/ja/guides/authoring-content/#補足情報)ガイドを参照してください。

### カスタムタイトルの使用

[`title`](#title)属性を使用して、デフォルトの補足情報タイトルを上書きできます。

<Preview>

```mdx 'title="注意してください!"'
import { Aside } from '@astrojs/starlight/components';

<Aside type="caution" title="注意してください!">
	カスタムタイトル*付きの*警告補足情報。
</Aside>
```

<Fragment slot="markdoc">

```markdoc 'title="注意してください!"'
{% aside type="caution" title="注意してください!" %}
カスタムタイトル*付きの*警告補足情報。
{% /aside %}
```

</Fragment>

<Aside slot="preview" type="caution" title="注意してください!">
	カスタムタイトル*付きの*警告補足情報。
</Aside>
  
</Preview>

### カスタムアイコンの使用

[`icon`](#icon)属性を使用して、デフォルトの補足情報アイコンを上書きできます。  
値には、[Starlightの組み込みアイコン](/ja/reference/icons/#すべてのアイコン)の名前を指定します。

<Preview>

```mdx 'icon="starlight"'
import { Aside } from '@astrojs/starlight/components';

<Aside type="tip" icon="starlight">
	カスタムアイコン*付きの*ヒント補足情報。
</Aside>
```

 <Fragment slot="markdoc">

```markdoc 'icon="starlight"'
{% aside type="tip" icon="starlight" %}
カスタムアイコン*付きの*ヒント補足情報。
{% /aside %}
```

 </Fragment>

<Aside slot="preview" type="tip" icon="starlight">
	カスタムアイコン*付きの*ヒント補足情報。
</Aside>

</Preview>

## `<Aside>` プロパティ

**実装:** [`Aside.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Aside.astro)

`<Aside>`コンポーネントは以下のプロパティを受け入れます:

### `type`

**型:** `'note' | 'tip' | 'caution' | 'danger'`  
**デフォルト:** `'note'`

表示する補足情報のタイプ:

- `note`補足情報(デフォルト)は青色で、情報アイコンを表示します。
- `tip`補足情報は紫色で、ロケットアイコンを表示します。
- `caution`補足情報は黄色で、三角形の警告アイコンを表示します。
- `danger`補足情報は赤色で、八角形の警告アイコンを表示します。

### `title`

**型:** `string`

補足情報に表示するタイトル。
`title`が設定されていない場合、現在の補足情報に`type`のデフォルトタイトルが使用されます。

### `icon`

**型:** [`StarlightIcon`](/ja/reference/icons/#starlighticon-型)

補足情報に`icon`属性を設定して、[Starlightの組み込みアイコン](/ja/reference/icons/#すべてのアイコン)の名前を指定できます。


================================================
FILE: docs/src/content/docs/ja/components/badges.mdx
================================================
---
title: バッジ
description: Starlightでバッジを使用して追加の情報を表示する方法を学びましょう。
---

import { Badge } from '@astrojs/starlight/components';

ステータスやカテゴリーのような小さな情報を表示するには、`<Badge>`コンポーネントを使用します。

import Preview from '~/components/component-preview.astro';

<Preview>

<Badge slot="preview" text="新着" />

</Preview>

## インポート

```tsx
import { Badge } from '@astrojs/starlight/components';
```

## 使用方法

バッジを表示するには、`<Badge>`コンポーネントを使用し、表示したい内容を[`text`](#text)属性に渡します。

デフォルトでは、バッジはサイトのテーマのアクセントカラーを使用します。
組み込みのバッジカラーを使用するには、[`variant`](#variant)属性をサポートされている値のいずれかに設定します。

<Preview>

```mdx
import { Badge } from '@astrojs/starlight/components';

- <Badge text="ノート" variant="note" />
- <Badge text="成功" variant="success" />
- <Badge text="ヒント" variant="tip" />
- <Badge text="注意" variant="caution" />
- <Badge text="危険" variant="danger" />
```

<Fragment slot="markdoc">

```markdoc
- {% badge text="ノート" variant="note" /%}
- {% badge text="危険" variant="success" /%}
- {% badge text="ヒント" variant="tip" /%}
- {% badge text="注意" variant="caution" /%}
- {% badge text="危険" variant="danger" /%}
```

</Fragment>

<Fragment slot="preview">
	- <Badge text="ノート" variant="note" />
	- <Badge text="成功" variant="success" />
	- <Badge text="ヒント" variant="tip" />
	- <Badge text="注意" variant="caution" />
	- <Badge text="危険" variant="danger" />
</Fragment>

</Preview>

### 異なるサイズの使用

[`size`](#size)属性を使用してバッジのテキストサイズを制御します。

<Preview>

```mdx /size="\w+"/
import { Badge } from '@astrojs/starlight/components';

- <Badge text="新着" size="small" />
- <Badge text="新着かつ改良" size="medium" />
- <Badge text="新着、改良、もっと大きく" size="large" />
```

<Fragment slot="markdoc">

```markdoc /size="\w+"/
- {% badge text="新着" size="small" /%}
- {% badge text="新着かつ改良" size="medium" /%}
- {% badge text="新着、改良、もっと大きく" size="large" /%}
```

</Fragment>

<Fragment slot="preview">
	- <Badge text="新着" size="small" />
	- <Badge text="新着かつ改良" size="medium" />
	- <Badge text="新着、改良、もっと大きく" size="large" />
</Fragment>

</Preview>

### バッジのカスタマイズ

カスタムCSSを使用して、`class`や`style`などの他の`<span>`属性を使用してバッジをカスタマイズします。

<Preview>

```mdx "style={{ fontStyle: 'italic' }}"
import { Badge } from '@astrojs/starlight/components';

<Badge text="カスタム" variant="success" style={{ fontStyle: 'italic' }} />
```

<Fragment slot="markdoc">

```markdoc 'style="font-style: italic;"'
{% badge text="カスタム" variant="success" style="font-style: italic;" /%}
```

</Fragment>

<Badge
	slot="preview"
	text="カスタム"
	variant="success"
	style={{ fontStyle: 'italic' }}
/>

</Preview>

## `<Badge>` プロパティ

**実装:** [`Badge.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Badge.astro)

`<Badge>`コンポーネントは、以下のプロパティおよびその他の[`<span>`要素の属性](https://developer.mozilla.org/ja/docs/Web/HTML/Global_attributes)を受け付けます。

### `text`

**必須**  
**型:** `string`

バッジに表示するテキスト内容。

### `variant`

**型:** `'note' | 'danger' | 'success' | 'caution' | 'tip' | 'default'`  
**デフォルト:** `'default'`

使用するバッジのカラーバリアント: `note` (青), `tip` (紫), `danger` (赤), `caution` (オレンジ), `success` (緑), または `default` (テーマのアクセントカラー)。

### `size`

**型:** `'small' | 'medium' | 'large'`

表示するバッジのサイズを定義します。


================================================
FILE: docs/src/content/docs/ja/components/card-grids.mdx
================================================
---
title: カードグリッド
description: Starlightで複数のカードをグリッドにラップする方法を学びます。
sidebar:
  order: 4
---

import { Card, CardGrid, LinkCard } from '@astrojs/starlight/components';

複数の[`<Card>`](/ja/components/cards/)または[`<LinkCard>`](/ja/components/link-cards/)コンポーネントをグリッドにラップするには、`<CardGrid>`コンポーネントを使用します。

import Preview from '~/components/component-preview.astro';

<Preview>

<CardGrid slot="preview">
	<Card title="恒星" icon="star">
		シリウス、ベガ、ベテルギウス
	</Card>
	<Card title="衛星" icon="moon">
		イオ、エウロパ、ガニメデ
	</Card>
</CardGrid>

</Preview>

## インポート

```tsx
import { CardGrid } from '@astrojs/starlight/components';
```

## 使用方法

### カードをグループ化する

`<CardGrid>`コンポーネントを使用してグループ化することで、十分なスペースがある場合に複数の[`<Card>`](/ja/components/cards/)コンポーネントを並べて表示します。

<Preview>

```mdx {3,10}
import { Card, CardGrid } from '@astrojs/starlight/components';

<CardGrid>
	<Card title="これをチェック" icon="open-book">
		強調したい興味深いコンテンツ。
	</Card>
	<Card title="その他の機能" icon="information">
		共有したいその他の情報。
	</Card>
</CardGrid>
```

<Fragment slot="markdoc">

```markdoc {1,9}
{% cardgrid %}
{% card title="これをチェック" icon="open-book" %}
強調したい興味深いコンテンツ。
{% /card %}

{% card title="その他の機能" icon="information" %}
共有したいその他の情報。
{% /card %}
{% /cardgrid %}
```

</Fragment>

<CardGrid slot="preview">
	<Card title="これをチェック" icon="open-book">
		強調したい興味深いコンテンツ。
	</Card>
	<Card title="その他の機能" icon="information">
		共有したいその他の情報。
	</Card>
</CardGrid>

</Preview>

### リンクカードをグループ化する

`<CardGrid>`コンポーネントを使用してグループ化することで、十分なスペースがある場合に複数の[`<LinkCard>`](/ja/components/link-cards/)コンポーネントを並べて表示します。

<Preview>

```mdx {3,6}
import { LinkCard, CardGrid } from '@astrojs/starlight/components';

<CardGrid>
	<LinkCard title="Markdownの作成" href="/ja/guides/authoring-content/" />
	<LinkCard title="コンポーネント" href="/ja/components/using-components/" />
</CardGrid>
```

<Fragment slot="markdoc">

```markdoc {1,5}
{% cardgrid %}
{% linkcard title="Markdownの作成" href="/ja/guides/authoring-content/" /%}

{% linkcard title="コンポーネント" href="/ja/components/using-components/" /%}
{% /cardgrid %}
```

</Fragment>

<CardGrid slot="preview">
	<LinkCard title="Markdownの作成" href="/ja/guides/authoring-content/" />
	<LinkCard title="コンポーネント" href="/ja/components/using-components/" />
</CardGrid>

</Preview>

### カードをずらす

視覚的な興味を加えるために、`<CardGrid>`コンポーネントに[`stagger`](#カードをずらす)属性を追加してグリッドの2列目を垂直方向にずらします。

この属性は、プロジェクトの主要な機能を表示するホームページで便利です。

<Preview>

```mdx "stagger"
import { Card, CardGrid } from '@astrojs/starlight/components';

<CardGrid stagger>
	<Card title="これをチェック" icon="open-book">
		強調したい興味深いコンテンツ。
	</Card>
	<Card title="その他の機能" icon="information">
		共有したいその他の情報。
	</Card>
</CardGrid>
```

<Fragment slot="markdoc">

```markdoc "stagger=true"
{% cardgrid stagger=true %}
{% card title="これをチェック" icon="open-book" %}
強調したい興味深いコンテンツ。
{% /card %}

{% card title="その他の機能" icon="information" %}
共有したいその他の情報。
{% /card %}
{% /cardgrid %}
```

</Fragment>

<CardGrid slot="preview" stagger>
	<Card title="これをチェック" icon="open-book">
		強調したい興味深いコンテンツ。
	</Card>
	<Card title="その他の機能" icon="information">
		共有したいその他の情報。
	</Card>
</CardGrid>

</Preview>

## `<CardGrid>` プロパティ

**実装:** [`CardGrid.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/CardGrid.astro)

`<CardGrid>`コンポーネントは以下のプロパティを受け入れます:

### `stagger`

**型:** `boolean`

グリッド内のカードをずらすかどうかを定義します。


================================================
FILE: docs/src/content/docs/ja/components/cards.mdx
================================================
---
title: カード
description: Starlightでコンテンツをボックス内に表示するためのカードの使用方法を学びます。
sidebar:
  order: 2
---

import { Card } from '@astrojs/starlight/components';

Starlightのスタイルに合わせてコンテンツをボックス内に表示するには、`<Card>`コンポーネントを使用します。

import Preview from '~/components/component-preview.astro';

<Preview>
	<Card slot="preview" title="衛星" icon="moon">
		イオ、エウロパ、ガニメデ
	</Card>
</Preview>

## インポート

```tsx
import { Card } from '@astrojs/starlight/components';
```

## 使用方法

`<Card>`コンポーネントを使用してカードを表示し、カードの[`title`](#title)を提供します。

<Preview>

```mdx
import { Card } from '@astrojs/starlight/components';

<Card title="これをチェック">強調したい興味深いコンテンツ。</Card>
```

<Fragment slot="markdoc">

```markdoc
{% card title="これをチェック" %}
強調したい興味深いコンテンツ。
{% /card %}
```

</Fragment>

<Card slot="preview" title="これをチェック">
	強調したい興味深いコンテンツ。
</Card>

</Preview>

### カードにアイコンを追加する

[Starlightの組み込みアイコン](/ja/reference/icons/#すべてのアイコン)の名前を[`icon`](#icon)属性に設定して、カードにアイコンを含めることができます。

<Preview>

```mdx 'icon="star"'
import { Card } from '@astrojs/starlight/components';

<Card title="恒星" icon="star">
	シリウス、ベガ、ベテルギウス
</Card>
```

<Fragment slot="markdoc">

```markdoc 'icon="star"'
{% card title="恒星" icon="star" %}
シリウス、ベガ、ベテルギウス
{% /card %}
```

</Fragment>

<Card slot="preview" title="恒星" icon="star">
	シリウス、ベガ、ベテルギウス
</Card>
  
</Preview>

### カードをグループ化する

[`<CardGrid>`](/ja/components/card-grids/)コンポーネントを使用してグループ化することで、十分なスペースがある場合に複数のカードを並べて表示できます。
例については、["カードのグループ化"](/ja/components/card-grids/#カードをグループ化する)ガイドを参照してください。

## `<Card>` プロパティ

**実装:** [`Card.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Card.astro)

`<Card>`コンポーネントは以下のプロパティを受け入れます:

### `title`

**必須**  
**型:** `string`

表示するカードのタイトル。

### `icon`

**型:** `string`

カードには[Starlightの組み込みアイコン](/ja/reference/icons/#すべてのアイコン)の名前に設定された`icon`属性を含めることができます。


================================================
FILE: docs/src/content/docs/ja/components/code.mdx
================================================
---
title: コード
description: StarlightでMarkdownのコードブロックを使わずにシンタックスハイライトされたコードを表示する方法を学びましょう。
---

import { Code } from '@astrojs/starlight/components';

`<Code>`コンポーネントは、シンタックスハイライトされたコードをレンダリングします。
これは、[Markdownのコードブロック](/ja/guides/authoring-content/#コードブロック)を使用できない場合、例えば、ファイルやデータベース、APIから取得したデータを表示する場合に便利です。

import Preview from '~/components/component-preview.astro';

<Preview>

<Code
	slot="preview"
	code={`## ようこそ

**宇宙**からこんにちは!`}
lang="md"
title="example.md"
ins={3}
/>

</Preview>

## インポート

```tsx
import { Code } from '@astrojs/starlight/components';
```

## 使用方法

外部ソースから取得したコードを表示する場合などに、`<Code>`コンポーネントを使用してシンタックスハイライトされたコードをレンダリングします。

完全な使用方法と利用可能なプロパティのリストについては、[Expressive Codeの「Codeコンポーネント」ドキュメント](https://expressive-code.com/key-features/code-component/)を参照してください。

<Preview>

```mdx
import { Code } from '@astrojs/starlight/components';

export const exampleCode = `console.log('これはファイルやCMSから来る可能性がある!');`;
export const fileName = 'example.js';
export const highlights = ['ファイル', 'CMS'];

<Code code={exampleCode} lang="js" title={fileName} mark={highlights} />
```

<Fragment slot="markdoc">

```markdoc
{% code
   code="console.log('これはファイルやCMSから来る可能性がある!');"
   lang="js"
   title="example.js"
   meta="'ファイル' 'CMS'" /%}
```

</Fragment>

export const exampleCode = `console.log('これはファイルやCMSから来る可能性がある!');`;
export const fileName = 'example.js';
export const highlights = ['ファイル', 'CMS'];

<Code
	slot="preview"
	code={exampleCode}
	lang="js"
	title={fileName}
	mark={highlights}
/>

</Preview>

### インポートしたコードを表示する

MDXファイルやAstroコンポーネント内で、[Viteの`?raw`インポートサフィックス](https://ja.vite.dev/guide/assets#importing-asset-as-string)を使用して、任意のコードファイルを文字列としてインポートできます。
その後、このインポートした文字列を`<Code>`コンポーネントに渡して、ページにコードを表示することができます。

<Preview>

```mdx "?raw"
# src/content/docs/example.mdx

import { Code } from '@astrojs/starlight/components';
import importedCode from '/tsconfig.json?raw';

<Code code={importedCode} lang="json" title="tsconfig.json" />
```

import importedCode from '../../../../../../examples/basics/tsconfig.json?raw';

<Code slot="preview" code={importedCode} lang="json" title="tsconfig.json" />

</Preview>

## `<Code>` プロパティ

**実装:** [`Code.astro`](https://github.com/expressive-code/expressive-code/blob/main/packages/astro-expressive-code/components/Code.astro)

`<Code>`コンポーネントは、[Expressive Codeの「Codeコンポーネント」ドキュメント](https://expressive-code.com/key-features/code-component/#available-props)に記載されているすべてのプロパティを受け付けます。


================================================
FILE: docs/src/content/docs/ja/components/file-tree.mdx
================================================
---
title: ファイルツリー
description: Starlightでファイルアイコンや折りたたみ可能なサブディレクトリを使ってディレクトリ構造を表示する方法を学びましょう。
---

import { FileTree } from '@astrojs/starlight/components';

ファイルアイコンや折りたたみ可能なサブディレクトリを使ってディレクトリ構造を表示するには、`<FileTree>`コンポーネントを使用します。

import Preview from '~/components/component-preview.astro';

<Preview>

<FileTree slot="preview">

- astro.config.mjs **重要な**ファイル
- package.json
- README.md
- src
  - components
    - **Header.astro**
  - …
- pages/

</FileTree>

</Preview>

## インポート

```tsx
import { FileTree } from '@astrojs/starlight/components';
```

## 使用方法

`<FileTree>`コンポーネントを使用して、ファイルアイコンや折りたたみ可能なサブディレクトリを含むファイルツリーを表示します。

ファイルやディレクトリの構造を指定するには、[Markdownの箇条書きリスト](https://www.markdownguide.org/basic-syntax/#unordered-lists)を`<FileTree>`の内部で使用します。サブディレクトリを作成するには、ネストしたリストを作成するか、リスト項目の末尾に `/` を追加して、特定の内容を持たないディレクトリとして表示します。

<Preview>

```mdx
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- astro.config.mjs
- package.json
- src
  - components
    - Header.astro
    - Title.astro
  - pages/

</FileTree>
```

<Fragment slot="markdoc">

```markdoc
{% filetree %}
- astro.config.mjs
- package.json
- src
  - components
    - Header.astro
    - Title.astro
  - pages/
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- astro.config.mjs
- package.json
- src
  - components
    - Header.astro
    - Title.astro
  - pages/

</FileTree>

</Preview>

### エントリを強調表示する

ファイルやディレクトリの名前を太字にして目立たせることができます。例: `**README.md**`。

<Preview>

```mdx {7}
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src
  - components
    - **Header.astro**
    - Title.astro

</FileTree>
```

<Fragment slot="markdoc">

```markdoc {4}
{% filetree %}
- src
  - components
    - **Header.astro**
    - Title.astro
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- src
  - components
    - **Header.astro**
    - Title.astro

</FileTree>

</Preview>

### コメントを追加する

ファイルやディレクトリにコメントを追加するには、名前の後にテキストを追加します。コメントには、太字や斜体などのMarkdownのインライン形式がサポートされています。

<Preview>

```mdx {7}
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src
  - components
    - Header.astro **重要な**ファイル
    - Title.astro

</FileTree>
```

<Fragment slot="markdoc">

```markdoc {4}
{% filetree %}
- src
  - components
    - Header.astro **重要な**ファイル
    - Title.astro
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- src
  - components
    - Header.astro **重要な**ファイル
    - Title.astro

</FileTree>

</Preview>

### プレースホルダーを追加する

`...`または`…`を名前として使用することで、プレースホルダーファイルやディレクトリを追加できます。これは、フォルダがさらに多くのアイテムを含むことが期待されていることを読者に示しながら、それらをすべて明示的に指定する必要がない場合に便利です。

<Preview>

```mdx {8}
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src
  - components
    - Header.astro
    - …

</FileTree>
```

<Fragment slot="markdoc">

```markdoc {5}
{% filetree %}
- src
  - components
    - Header.astro
    - …
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- src
  - components
    - Header.astro
    - …

</FileTree>

</Preview>

## `<FileTree>` プロパティ

**実装:** [`FileTree.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/FileTree.astro)

`<FileTree>`コンポーネントはプロパティを受け付けません。


================================================
FILE: docs/src/content/docs/ja/components/icons.mdx
================================================
---
title: アイコン
description: Starlightでアイコンを表示する方法を学びましょう。
---

import { Icon } from '@astrojs/starlight/components';

Starlightの[組み込みアイコンセット](/ja/reference/icons/#すべてのアイコン)からアイコンを表示するには、`<Icon>`コンポーネントを使用します。

import Preview from '~/components/component-preview.astro';

<Preview>

<Icon
	slot="preview"
	name="open-book"
	color="var(--sl-color-text-accent)"
	size="4rem"
/>

</Preview>

## インポート

```tsx
import { Icon } from '@astrojs/starlight/components';
```

## 使用方法

`<Icon>`コンポーネントを使用してアイコンを表示します。アイコンには[`name`](#name)が必要で、これは[Starlightの組み込みアイコン](/ja/reference/icons/#すべてのアイコン)のいずれかに設定されます。また、オプションでスクリーンリーダー向けに[`label`](#label)を追加して文脈を提供することができます。

<Preview>

```mdx
import { Icon } from '@astrojs/starlight/components';

<Icon name="star" />
<Icon name="starlight" label="Starlightのロゴ" />
```

<Fragment slot="markdoc">

```markdoc
{% icon name="star" /%}
{% icon name="starlight" label="Starlightのロゴ" /%}
```

</Fragment>

<Fragment slot="preview">
	<Icon name="star" />
	<Icon name="starlight" label="Starlightのロゴ" />
</Fragment>

</Preview>

### アイコンのカスタマイズ

[`size`](#size)や[`color`](#color)属性を使用して、CSS単位やカラーバリューを使ってアイコンの外観を調整できます。また、[`class`](#class)属性を使用してカスタムCSSクラスをアイコンに追加することができます。

<Preview>

```mdx
import { Icon } from '@astrojs/starlight/components';

<Icon name="star" color="goldenrod" size="2rem" />
<Icon name="rocket" color="var(--sl-color-text-accent)" />
```

<Fragment slot="markdoc">

```markdoc
{% icon name="star" color="goldenrod" size="2rem" /%}
{% icon name="rocket" color="var(--sl-color-text-accent)" /%}
```

</Fragment>

<Fragment slot="preview">
	<Icon name="star" color="goldenrod" size="2rem" />
	<Icon name="rocket" color="var(--sl-color-text-accent)" />
</Fragment>

</Preview>

## `<Icon>` プロパティ

**実装:** [`Icon.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Icon.astro)

`<Icon>`コンポーネントは以下のプロパティを受け付けます。

### `name`

**必須**  
**型:** [`StarlightIcon`](/ja/reference/icons/#starlighticon-型)

表示するアイコンの名前を[Starlightの組み込みアイコン](/ja/reference/icons/#すべてのアイコン)の1つに設定します。

### `label`

**型:** `string`

スクリーンリーダーなどの支援技術に文脈を提供するためのオプションのラベル。

`label`が設定されていない場合、アイコンは支援技術から完全に隠されます。この場合、アイコンがなくても文脈が理解できることを確認してください。例えば、アイコンのみが含まれるリンクには、アクセシビリティを確保するために`label`属性が**必ず**含まれている必要がありますが、リンクにテキストが含まれ、アイコンが純粋に装飾的なものである場合は、`label`を省略することが理にかなっています。

### `size`

**型:** `string`

CSS単位でアイコンのサイズを指定します。

### `color`

**型:** `string`

CSSカラーバリューを使用してアイコンの色を指定します。

### `class`

**型:** `string`

アイコンにカスタムCSSクラスを追加します。


================================================
FILE: docs/src/content/docs/ja/components/link-buttons.mdx
================================================
---
title: リンクボタン
description: 視覚的に目立つコールトゥアクションリンクをStarlightで作成する方法を学びましょう。
---

import { LinkButton } from '@astrojs/starlight/components';

視覚的に目立つコールトゥアクションリンクを表示するには、`<LinkButton>`コンポーネントを使用します。

import Preview from '~/components/component-preview.astro';

<Preview>

<LinkButton slot="preview" href="/ja/getting-started/">
	ドキュメントを読む
</LinkButton>

</Preview>

## インポート

```tsx
import { LinkButton } from '@astrojs/starlight/components';
```

## 使用方法

`<LinkButton>`コンポーネントを使用して、視覚的に目立つコールトゥアクションリンクを表示します。
リンクボタンは、ユーザーを最も関連性の高いコンテンツやアクションにつなげるために便利で、ランディングページなどでよく使用されます。

`<LinkButton>`には[`href`](#href)属性が必要です。
オプションとして、[`variant`](#variant)属性を使用して、ボタンの外観をカスタマイズできます。`variant`属性には`primary`(デフォルト)、`secondary`、`minimal`のいずれかを指定できます。

<Preview>

```mdx
import { LinkButton } from '@astrojs/starlight/components';

<LinkButton href="/ja/getting-started/">始めましょう</LinkButton>
<LinkButton href="/ja/reference/configuration/" variant="secondary">
	設定リファレンス
</LinkButton>
```

<Fragment slot="markdoc">

```markdoc
{% linkbutton href="/ja/getting-started/" %}始めましょう{% /linkbutton %}

{% linkbutton href="/ja/reference/configuration/" variant="secondary" %}
設定リファレンス
{% /linkbutton %}
```

</Fragment>

<Fragment slot="preview">
	<LinkButton href="/ja/getting-started/">始めましょう</LinkButton>
	<LinkButton href="/ja/reference/configuration/" variant="secondary">
		設定リファレンス
	</LinkButton>
</Fragment>

</Preview>

### リンクボタンにアイコンを追加する

[`icon`](#icon)属性を使用して、リンクボタンにアイコンを追加できます。これは、[Starlightの組み込みアイコン](/ja/reference/icons/#すべてのアイコン)の名前を指定します。

[`iconPlacement`](#iconplacement)属性を使用すると、アイコンをテキストの前に配置することができ、デフォルトでは`end`(後ろ)ですが、`start`(前)に設定できます。

<Preview>

```mdx {6-7}
import { LinkButton } from '@astrojs/starlight/components';

<LinkButton
	href="https://docs.astro.build/ja/"
	variant="secondary"
	icon="external"
	iconPlacement="start"
>
	Astroに関連するドキュメント
</LinkButton>
```

<Fragment slot="markdoc">

```markdoc {4-5}
{% linkbutton
   href="https://docs.astro.build/ja/"
	 variant="secondary"
	 icon="external"
	 iconPlacement="start" %}
Astroに関連するドキュメント
{% /linkbutton %}
```

</Fragment>

<LinkButton
	slot="preview"
	href="https://docs.astro.build/ja/"
	variant="secondary"
	icon="external"
	iconPlacement="start"
>
	Astroに関連するドキュメント
</LinkButton>

</Preview>

## `<LinkButton>` プロパティ

**実装:** [`LinkButton.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/LinkButton.astro)

`<LinkButton>`コンポーネントは以下のプロパティを受け付け、[他の`<a>`要素の属性](https://developer.mozilla.org/ja/docs/Web/HTML/Element/a)も使用できます。

### `href`

**必須**  
**型:** `string`

リンクボタンが指すURL。

### `variant`

**型:** `'primary' | 'secondary' | 'minimal'`  
**デフォルト:** `'primary'`

リンクボタンの外観。
`primary`はテーマのアクセントカラーを使用して目立つコールトゥアクションリンクを作成し、`secondary`はそれほど目立たないリンク、`minimal`は最小限のスタイルのリンクを作成します。

### `icon`

**型:** `string`

リンクボタンにアイコンを含めるための属性。これは[Starlightの組み込みアイコン](/ja/reference/icons/#すべてのアイコン)の名前を指定します。

### `iconPlacement`

**型:** `'start' | 'end'`  
**デフォルト:** `'end'`

アイコンの配置をテキストの前後どちらにするかを指定します。


================================================
FILE: docs/src/content/docs/ja/components/link-cards.mdx
================================================
---
title: リンクカード
description: Starlightでリンクを目立つカードとして表示する方法を学びます。
sidebar:
  order: 3
---

import { LinkCard } from '@astrojs/starlight/components';

異なるページへのリンクを目立たせて表示するには、`<LinkCard>`コンポーネントを使用します。

import Preview from '~/components/component-preview.astro';

<Preview>
	<LinkCard
		slot="preview"
		title="Starlightのカスタマイズ"
		description="カスタムスタイル、フォントなどを使用して、Starlightサイトを自分のものにする方法を学びます。"
		href="/ja/guides/customization/"
	/>
</Preview>

## インポート

```tsx
import { LinkCard } from '@astrojs/starlight/components';
```

## 使用方法

`<LinkCard>`コンポーネントを使用して、リンクを目立たせて表示します。
各`<LinkCard>`には[`title`](#title)と[`href`](#href)属性が必要です。

<Preview>

```mdx
import { LinkCard } from '@astrojs/starlight/components';

<LinkCard title="Markdownの作成" href="/ja/guides/authoring-content/" />
```

<Fragment slot="markdoc">

```markdoc
{% linkcard title="Markdownの作成" href="/ja/guides/authoring-content/" /%}
```

</Fragment>

<LinkCard
	slot="preview"
	title="Markdownの作成"
	href="/ja/guides/authoring-content/"
/>
  
</Preview>

### リンクの説明を追加する

[`description`](#description)属性を使用して、リンクカードに短い説明を追加します。

<Preview>

```mdx {6}
import { LinkCard } from '@astrojs/starlight/components';

<LinkCard
	title="国際化"
	href="/ja/guides/i18n/"
	description="複数の言語をサポートするようにStarlightを設定します。"
/>
```

<Fragment slot="markdoc">

```markdoc {4}
{% linkcard
   title="国際化"
	 href="/ja/guides/i18n/"
	 description="複数の言語をサポートするようにStarlightを設定します。" /%}
```

</Fragment>

<LinkCard
	slot="preview"
	title="国際化"
	href="/ja/guides/i18n/"
	description="複数の言語をサポートするようにStarlightを設定します。"
/>
  
</Preview>

### リンクカードをグループ化する

[`<CardGrid>`](/ja/components/card-grids/)コンポーネントを使用してグループ化することで、十分なスペースがある場合に複数のリンクカードを並べて表示できます。

例については、["リンクカードのグループ化"](/ja/components/card-grids/#リンクカードをグループ化する)ガイドを参照してください。

## `<LinkCard>` プロパティ

**実装:** [`LinkCard.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/LinkCard.astro)

`<LinkCard>`コンポーネントは、以下のプロパティおよび他のすべての[`<a>`要素の属性](https://developer.mozilla.org/ja/docs/Web/HTML/Element/a)を受け入れます:

### `title`

**必須**  
**型:** `string`

表示するリンクカードのタイトル。

### `href`

**必須**  
**型:** `string`

カードが操作されたときにリンクするURL。

### `description`

**型:** `string`

タイトルの下に表示するオプションの説明。


================================================
FILE: docs/src/content/docs/ja/components/steps.mdx
================================================
---
title: ステップ
description: Starlightでタスクの番号付きリストをスタイル設定してステップバイステップのガイドを作成する方法を学びましょう。
---

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

タスクの番号付きリストをスタイル設定してステップバイステップのガイドを作成するには、`<Steps>`コンポーネントを使用します。

import Preview from '~/components/component-preview.astro';

<Preview>

<Steps slot="preview">

1. 新しいStarlightプロジェクトを作成します:

   <Tabs syncKey="pkg">

   <TabItem label="npm">

   ```sh
   npm create astro@latest -- --template starlight
   ```

   </TabItem>

   <TabItem label="pnpm">

   ```sh
   pnpm create astro --template starlight
   ```

   </TabItem>

   <TabItem label="Yarn">

   ```sh
   yarn create astro --template starlight
   ```

   </TabItem>

   </Tabs>

2. 最初のドキュメントページを書きます。

</Steps>

</Preview>

## インポート

```tsx
import { Steps } from '@astrojs/starlight/components';
```

## 使用方法

`<Steps>`コンポーネントを使用して、タスクの番号付きリストをスタイル設定します。
各ステップを明確に強調する必要がある、より複雑なステップバイステップガイドに役立ちます。

`<Steps>`で標準のMarkdownの順序付きリストを囲みます。
通常のMarkdown構文はすべて`<Steps>`内で適用されます。

<Preview>

````mdx
import { Steps } from '@astrojs/starlight/components';

<Steps>

1. コンポーネントをMDXファイルにインポートします:

   ```js
   import { Steps } from '@astrojs/starlight/components';
   ```

2. 順序付きリストのアイテムを`<Steps>`で囲みます。

</Steps>
````

<Fragment slot="markdoc">

````markdoc
{% steps %}

1. コンポーネントをMDXファイルにインポートします:

   ```js
   import { Steps } from '@astrojs/starlight/components';
   ```

2. 順序付きリストのアイテムを`<Steps>`で囲みます。

{% /steps %}
````

</Fragment>

<Steps slot="preview">

1. コンポーネントをMDXファイルにインポートします:

   ```js
   import { Steps } from '@astrojs/starlight/components';
   ```

2. 順序付きリストのアイテムを`<Steps>`で囲みます。

</Steps>

</Preview>

## `<Steps>` プロパティ

**実装:** [`Steps.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Steps.astro)

`<Steps>`コンポーネントはプロパティを受け付けません。


================================================
FILE: docs/src/content/docs/ja/components/tabs.mdx
================================================
---
title: タブ
description: Starlightで同等の情報をグループ化するためのタブインターフェースを作成する方法を学びましょう。
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

タブインターフェースを作成するには、`<Tabs>`と`<TabItem>`コンポーネントを使用します。
タブは、ユーザーが複数のオプションのうち1つだけを見る必要がある場合に、同等の情報をグループ化するのに便利です。

import Preview from '~/components/component-preview.astro';

<Preview>

<Tabs slot="preview">
	<TabItem label="星">シリウス、ベガ、ベテルギウス</TabItem>
	<TabItem label="衛星">イオ、エウロパ、ガニメデ</TabItem>
</Tabs>

</Preview>

## インポート

```tsx
import { Tabs, TabItem } from '@astrojs/starlight/components';
```

## 使用方法

`<Tabs>`と`<TabItem>`コンポーネントを使用してタブインターフェースを表示します。
各`<TabItem>`には、ユーザーに表示される[`label`](#label)が必要です。

<Preview>

```mdx
import { Tabs, TabItem } from '@astrojs/starlight/components';

<Tabs>
	<TabItem label="星">シリウス、ベガ、ベテルギウス</TabItem>
	<TabItem label="衛星">イオ、エウロパ、ガニメデ</TabItem>
</Tabs>
```

<Fragment slot="markdoc">

```markdoc
{% tabs %}
{% tabitem label="星" %}
シリウス、ベガ、ベテルギウス
{% /tabitem %}

{% tabitem label="衛星" %}
イオ、エウロパ、ガニメデ
{% /tabitem %}
{% /tabs %}
```

</Fragment>

<Tabs slot="preview">
	<TabItem label="星">シリウス、ベガ、ベテルギウス</TabItem>
	<TabItem label="衛星">イオ、エウロパ、ガニメデ</TabItem>
</Tabs>

</Preview>

### タブを同期させる

複数のタブグループを同期させるには、[`syncKey`](#synckey)属性を追加します。

ページ上のすべての`<Tabs>`に同じ`syncKey`値を設定すると、同じアクティブなラベルが表示されます。
これにより、読者は一度選択(例: オペレーティングシステムやパッケージマネージャー)すると、その選択がページを移動しても保持されます。

関連するタブを同期させるには、各`<Tabs>`コンポーネントに同じ`syncKey`プロパティを追加し、同じ`<TabItem>`ラベルを使用してください。

<Preview>

```mdx 'syncKey="constellations"'
import { Tabs, TabItem } from '@astrojs/starlight/components';

_いくつかの星:_

<Tabs syncKey="constellations">
	<TabItem label="オリオン座">ベラトリックス、リゲル、ベテルギウス</TabItem>
	<TabItem label="ふたご座">ポルックス、カストルA、カストルB</TabItem>
</Tabs>

_いくつかのエキソプラネット:_

<Tabs syncKey="constellations">
	<TabItem label="オリオン座">HD 34445 b、グリーゼ 179 b、Wasp-82 b</TabItem>
	<TabItem label="ふたご座">ポルックスb、HAT-P-24b、HD 50554 b</TabItem>
</Tabs>
```

<Fragment slot="markdoc">

```markdoc 'syncKey="constellations"'
_いくつかの星:_

{% tabs syncKey="constellations" %}
{% tabitem label="オリオン座" %}
ベラトリックス、リゲル、ベテルギウス
{% /tabitem %}

{% tabitem label="ふたご座" %}
ポルックス、カストルA、カストルB
{% /tabitem %}
{% /tabs %}

_いくつかのエキソプラネット:_

{% tabs syncKey="constellations" %}
{% tabitem label="オリオン座" %}
HD 34445 b、グリーゼ 179 b、Wasp-82 b
{% /tabitem %}

{% tabitem label="ふたご座" %}
ポルックスb、HAT-P-24b、HD 50554 b
{% /tabitem %}
{% /tabs %}
```

</Fragment>

<Fragment slot="preview">

_いくつかの星:_

<Tabs syncKey="constellations">
	<TabItem label="オリオン座">ベラトリックス、リゲル、ベテルギウス</TabItem>
	<TabItem label="ふたご座">ポルックス、カストルA、カストルB</TabItem>
</Tabs>

_いくつかのエキソプラネット:_

<Tabs syncKey="constellations">
	<TabItem label="オリオン座">HD 34445 b、グリーゼ 179 b、Wasp-82 b</TabItem>
	<TabItem label="ふたご座">ポルックスb、HAT-P-24b、HD 50554 b</TabItem>
</Tabs>

</Fragment>

</Preview>

### タブにアイコンを追加する

[`icon`](#icon)属性を使用してタブ項目にアイコンを追加し、[Starlightの組み込みアイコン](/ja/reference/icons/#すべてのアイコン)の名前を指定して、ラベルの横にアイコンを表示します。

<Preview>

```mdx /icon="\w+"/
import { Tabs, TabItem } from '@astrojs/starlight/components';

<Tabs>
	<TabItem label="星" icon="star">
		シリウス、ベガ、ベテルギウス
	</TabItem>
	<TabItem label="衛星" icon="moon">
		イオ、エウロパ、ガニメデ
	</TabItem>
</Tabs>
```

<Fragment slot="markdoc">

```markdoc /icon="\w+"/
{% tabs %}
{% tabitem label="星" icon="star" %}
シリウス、ベガ、ベテルギウス
{% /tabitem %}

{% tabitem label="衛星" icon="moon" %}
イオ、エウロパ、ガニメデ
{% /tabitem %}
{% /tabs %}
```

</Fragment>

<Tabs slot="preview">
	<TabItem label="星" icon="star">
		シリウス、ベガ、ベテルギウス
	</TabItem>
	<TabItem label="衛星" icon="moon">
		イオ、エウロパ、ガニメデ
	</TabItem>
</Tabs>

</Preview>

## `<Tabs>` プロパティ

**実装:** [`Tabs.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Tabs.astro)

`<Tabs>`コンポーネントは複数の`<TabItem>`コンポーネントをグループ化し、以下のプロパティを受け付けます。

### `syncKey`

**型:** `string`

複数のページにわたってタブグループを同期させるためのキー。

## `<TabItem>` プロパティ

**実装:** [`TabItem.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/TabItem.astro)

タブは複数のタブ項目から構成され、それぞれ以下のプロパティを持ちます。

### `label`

**必須**  
**型:** `string`

タブ項目には、タブに表示されるテキストを指定する`label`属性が必要です。

### `icon`

**型:** `string`

各タブ項目には、ラベルの横に表示される[Starlightに組み込まれたアイコン](/ja/reference/icons/#すべてのアイコン)を指定する`icon`属性を設定できます。


================================================
FILE: docs/src/content/docs/ja/components/using-components.mdx
================================================
---
title: コンポーネントの使用
description: StarlightでMDXとMarkdocにコンポーネントを組み込む。
sidebar:
  order: 1
---

コンポーネントを使用すると、UIの一部やスタイリングを一貫して簡単に再利用できます。例えば、リンクカードやYouTube埋め込みなどが挙げられます。Starlightは[MDX](https://mdxjs.com/)と[Markdoc](https://markdoc.dev/)ファイルでのコンポーネントの使用をサポートしており、またよく使う共通コンポーネントも複数提供しています。

[Astro Docsでコンポーネントの作成方法についてさらに学ぶ](https://docs.astro.build/ja/basics/astro-components/)。

## MDXでコンポーネントを使用する

コンポーネントを使用するには、MDXファイルにインポートし、JSXタグとしてレンダリングします。見た目はHTMLタグに似ていますが、`import`文で指定した名前に合わせて先頭が大文字で始まります。

```mdx
---
# src/content/docs/example.mdx
title: 私のドキュメントへようこそ
---

import { Icon } from '@astrojs/starlight/components';
import CustomCard from '../../components/CustomCard.astro';

<Icon name="open-book" />

<CustomCard>
	コンポーネントには**ネストされたコンテンツ**も含められます。
</CustomCard>
```

StarlightはAstroを基盤としているため、MDXファイルでは、[AstroがサポートしているUIフレームワーク(React、Preact、Svelte、Vue、Solid、Alpine)](https://docs.astro.build/ja/guides/framework-components/)で作成したコンポーネントを利用できます。詳しくは、Astroドキュメントの[MDXでコンポーネントを使用する](https://docs.astro.build/ja/guides/integrations-guide/mdx/#mdxでコンポーネントを使用する)を参照してください。

## Markdocでコンポーネントを使用する

[Markdocのセットアップガイド](/ja/guides/authoring-content/#markdoc)に従って、Markdocでコンテンツを作成するためのサポートを追加してください。

Starlight Markdocプリセットを使用すると、Markdocの`{% %}`タグ構文でStarlightの組み込みコンポーネントを使用できます。MDXとは異なり、Markdocではコンポーネントをインポートする必要がありません。以下の例では、MarkdocファイルでStarlightの[カードコンポーネント](/ja/components/cards/)をレンダリングしています。

```markdoc
---
# src/content/docs/example.mdoc
title: 私のドキュメントへようこそ
---

{% card title="星" icon="star" %}
シリウス、ベガ、ベテルギウス
{% /card %}
```

Markdocファイルでのコンポーネントの使用方法についての詳細は、[AstroのMarkdocインテグレーションドキュメント](https://docs.astro.build/ja/guides/integrations-guide/markdoc/#コンポーネントのレンダリング)を参照してください。

## 組み込みコンポーネント

Starlightは、一般的なドキュメントのユースケースに対応した組み込みコンポーネントを提供しています。これらのコンポーネントは、MDXファイルでは`@astrojs/starlight/components`パッケージから、Markdocファイルでは[Starlight Markdocプリセット](/ja/guides/authoring-content/#markdoc)から利用できます。

利用可能なコンポーネントの一覧と使用方法については、サイドバーを参照してください。

## Starlightのスタイルとの互換性

Starlightは、Markdownコンテンツにデフォルトのスタイリングを適用します。例えば、要素間にマージンを追加します。これらのスタイルがコンポーネントの外観と競合する場合は、`not-content`クラスをコンポーネントに設定して無効化できます。

```astro 'class="not-content"'
---
// src/components/Example.astro
---

<div class="not-content">
	<p>Starlightのデフォルトのコンテンツスタイリングの影響を受けません。</p>
</div>
```

## コンポーネントのprops

`astro/types`の[`ComponentProps`](https://docs.astro.build/ja/guides/typescript/#component-props)型を使用すると、コンポーネント自体が`Props`をエクスポートしていない場合でも、コンポーネントが受け取れる`Props`を参照できます。これは、既存のコンポーネントをラップしたり拡張したりする際に便利です。

以下の例では、`ComponentProps`を使用してStarlight組み込みの`Badge`コンポーネントが受け取るpropsの型を取得しています。

```astro
---
// src/components/Example.astro
import type { ComponentProps } from 'astro/types';
import { Badge } from '@astrojs/starlight/components';

type BadgeProps = ComponentProps<typeof Badge>;
---
```


================================================
FILE: docs/src/content/docs/ja/environmental-impact.md
================================================
---
title: 環境に優しいドキュメント
description: Starlightがどのように環境に優しいドキュメントサイトを作成し、カーボンフットプリントを減らすのに役立つかについて学びます。
---

ウェブ産業が気候に与える影響は、世界の炭素排出量の[2%][sf]から[4%][bbc]であり、航空業界の排出量にほぼ匹敵すると推定されています。ウェブサイトの生態学的影響の計算には多くの複雑な要因がありますが、このガイドではドキュメントサイトの環境への負荷を減らすためのいくつかのヒントを紹介します。

幸いなことに、Starlightを選ぶことは素晴らしいスタートです。Website Carbon Calculatorによると、このサイトは[テスト対象のウェブページの98%よりもクリーン][sl-carbon]であり、ページ訪問あたり0.01gのCO₂を生成します。

## ページの重さ

ウェブページが転送するデータが多いほど、より多くのエネルギー資源が必要になります。2023年4月現在、[HTTPアーカイブのデータ][http]によると、中央値のウェブページでは、ユーザーは2,000KB以上のデータをダウンロードする必要がありました。

Starlightは、可能な限り軽量なページを作成します。たとえば、初回訪問時にユーザーがダウンロードする圧縮データは50KB未満であり、HTTPアーカイブの中央値のわずか2.5%にすぎません。優れたキャッシュ戦略により、後続のナビゲーションのダウンロードは10KB程度に抑えられます。

### 画像

Starlightは優れたベースラインを提供しますが、ドキュメントページに追加した画像はページの重さを急速に増加させます。Starlightは、Astroの[最適化されたアセットサポート][assets]を使用して、MarkdownとMDXファイル内のローカル画像を最適化します。

### UIコンポーネント

ReactやVueなどのUIフレームワークで作成されたコンポーネントを使うと、大量のJavaScriptがページに追加される可能性があります。StarlightはAstro上に構築されており、[Astroアイランド][islands]のおかげで、このようなコンポーネントがデフォルトで**ロードするクライアントサイドJavaScriptはゼロ**となります。

### キャッシュ

キャッシュは、ブラウザがすでにダウンロードしたデータをどのくらいの期間保存して再利用するかを制御するために使用されます。優れたキャッシュ戦略は、コンテンツが変更されたときにユーザーができるだけ早く新しいコンテンツを取得することを保証し、また変更されていないときに同じコンテンツを何度も無駄にダウンロードするのを避けます。

キャッシュを設定する最も一般的な方法は、[`Cache-Control` HTTPヘッダー][cache]を使用するものです。Starlightを使用する場合、`/_astro/`ディレクトリ内のすべてに対し長めのキャッシュ時間を設定できます。このディレクトリには、CSS、JavaScript、その他のバンドルされたアセットが含まれており、安全に永続的なキャッシュを設定できるため、不要なダウンロードを減らすことができます。

```
Cache-Control: public, max-age=604800, immutable
```

キャッシュの設定方法は、ウェブホストによって異なります。たとえば、Vercelは設定不要でこのキャッシュ戦略を適用しますが、Netlifyではプロジェクトに`public/_headers`ファイルを追加することで[Netlify用カスタムヘッダー][ntl-headers]を設定できます。

```
/_astro/*
  Cache-Control: public
  Cache-Control: max-age=604800
  Cache-Control: immutable
```

[cache]: https://csswizardry.com/2019/03/cache-control-for-civilians/
[ntl-headers]: https://docs.netlify.com/routing/headers/

## 電力消費

ウェブページをどのようにビルドするかは、ユーザーのデバイス上で実行するために必要な電力に影響します。Starlightは、最小限のJavaScriptを使用することで、ユーザーの携帯電話、タブレット、そしてコンピューターがページをロードしてレンダリングするために必要な処理量を削減します。

アナリティクスのトラッキングスクリプトのような機能や、ビデオ埋め込みのようなJavaScriptを多用するコンテンツを追加すると、ページの電力消費量が増加する可能性があるため注意してください。アナリティクスが必要な場合は、[Cabin][cabin]、[Fathom][fathom]、あるいは[Plausible][plausible]のような軽量なオプションを選択することを検討してください。YouTubeやVimeoのような埋め込みは、[ユーザーの操作に応じて動画をロードする][lazy-video]ことで改善できます。[`astro-embed`][embed]のようなパッケージは、一般的なサービスに対し有効です。

:::tip[ご存知でしたか?]
JavaScriptの解析とコンパイルは、ブラウザが実行する最も高コストなタスクの1つです。同じサイズのJPEG画像をレンダリングするのに比べ、[JavaScriptの処理には30倍以上の時間がかかる][cost-of-js]ことがあります。
:::

[cabin]: https://withcabin.com/
[fathom]: https://usefathom.com/
[plausible]: https://plausible.io/
[lazy-video]: https://web.dev/iframe-lazy-loading/
[embed]: https://www.npmjs.com/package/astro-embed
[cost-of-js]: https://medium.com/dev-channel/the-cost-of-javascript-84009f51e99e

## ホスティング

ウェブページをホスティングする場所は、あなたのドキュメントサイトがどれだけ環境に優しいかどうかに大きく影響します。データセンターやサーバーファームは、高い電力消費や水の集中的な使用など、生態系に大きな影響を与える可能性があります。

再生可能エネルギーを使用するホストを選択すれば、サイトの炭素排出量を少なくできます。[Green Web Directory][gwb]は、ホスティング会社を見つけるのに役立つツールの1つです。

[gwb]: https://www.thegreenwebfoundation.org/directory/

## 比較

他のドキュメントフレームワークとの比較に興味がありますか?[Website Carbon Calculator][wcc]を用いた以下のテストでは、異なるツールで作成された類似のページを比較しています。

| フレームワーク              | ページ訪問ごとのCO₂ | レート |
| --------------------------- | ------------------- | :----: |
| [Starlight][sl-carbon]      | 0.01g               |   A+   |
| [Sphinx][sx-carbon]         | 0.01g               |   A+   |
| [Read the Docs][rtd-carbon] | 0.03g               |   A+   |
| [VitePress][vp-carbon]      | 0.04g               |   A    |
| [docsify][dy-carbon]        | 0.05g               |   A    |
| [mdBook][md-carbon]         | 0.05g               |   A    |
| [Nextra][nx-carbon]         | 0.05g               |   A    |
| [MkDocs][mk-carbon]         | 0.07g               |   A    |
| [Fumadocs][fs-carbon]       | 0.07g               |   A    |
| [Docusaurus][ds-carbon]     | 0.10g               |   B    |
| [Docus][dc-carbon]          | 0.11g               |   B    |
| [GitBook][gb-carbon]        | 0.42g               |   F    |
| [Mintlify][mt-carbon]       | 0.48g               |   F    |

<small>データは2025年8月7日に収集されたものです。リンクをクリックすると、最新の数値が表示されます。</small>

[sl-carbon]: https://www.websitecarbon.com/website/starlight-astro-build-getting-started/
[vp-carbon]: https://www.websitecarbon.com/website/vitepress-dev-guide-what-is-vitepress/
[dc-carbon]: https://www.websitecarbon.com/website/docus-dev-en-getting-started-project-structure/
[sx-carbon]: https://www.websitecarbon.com/website/sphinx-doc-org-en-master-usage-quickstart-html/
[mk-carbon]: https://www.websitecarbon.com/website/mkdocs-org-getting-started/
[md-carbon]: https://www.websitecarbon.com/website/rust-lang-github-io-mdbook/
[nx-carbon]: https://www.websitecarbon.com/website/nextra-site-docs-docs-theme-start/
[fs-carbon]: https://www.websitecarbon.com/website/fumadocs-dev-docs-ui/
[dy-carbon]: https://www.websitecarbon.com/website/docsify-js-org/
[ds-carbon]: https://www.websitecarbon.com/website/docusaurus-io-docs/
[rtd-carbon]: https://www.websitecarbon.com/website/docs-readthedocs-io-en-stable-index-html/
[gb-carbon]: https://www.websitecarbon.com/website/gitbook-com-docs/
[mt-carbon]: https://www.websitecarbon.com/website/mintlify-com-docs-quickstart/

## その他のリソース

### ツール

- [Website Carbon Calculator][wcc]
- [GreenFrame](https://greenframe.io/)
- [Ecograder](https://ecograder.com/)
- [WebPageTest Carbon Control](https://www.webpagetest.org/carbon-control/)
- [Ecoping](https://ecoping.earth/)

### 記事と講演

- [“Building a greener web”](https://youtu.be/EfPoOt7T5lg)、Michelle Barkerによる講演
- [“Sustainable Web Development Strategies Within An Organization”](https://www.smashingmagazine.com/2022/10/sustainable-web-development-strategies-organization/)、Michelle Barkerによる記事
- [“A sustainable web for everyone”](https://2021.stateofthebrowser.com/speakers/tom-greenwood/)、Tom Greenwoodによる講演
- [“How Web Content Can Affect Power Usage”](https://webkit.org/blog/8970/how-web-content-can-affect-power-usage/)、Benjamin PoulainとSimon Fraserによる記事

[sf]: https://www.sciencefocus.com/science/what-is-the-carbon-footprint-of-the-internet/
[bbc]: https://www.bbc.com/future/article/20200305-why-your-internet-habits-are-not-as-clean-as-you-think
[http]: https://httparchive.org/reports/state-of-the-web
[assets]: https://docs.astro.build/ja/guides/images/
[islands]: https://docs.astro.build/ja/concepts/islands/
[wcc]: https://www.websitecarbon.com/


================================================
FILE: docs/src/content/docs/ja/getting-started.mdx
================================================
---
title: 入門
description: AstroのStarlightで新しいドキュメントサイトを作成する方法について学びます。
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

Starlightは、[Astro](https://astro.build)の上に構築された、フル機能のドキュメント向けテーマです。このガイドは、あなたが新しいプロジェクトを始める手助けをします。既存のAstroプロジェクトにStarlightを追加するには、[手動セットアップの手順](/ja/manual-setup/)を参照してください。

## クイックスタート

### 新しいプロジェクトの作成

ターミナルで以下のコマンドを実行し、Astro + Starlightの新しいプロジェクトを作成します。

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight
```

</TabItem>
</Tabs>

これにより、サイトに必要なすべてのファイルと設定が含まれた、新しい[プロジェクトディレクトリ](/ja/guides/project-structure/)が作成されます。

:::tip[試してみよう]
Starlightをブラウザで試すには、[StackBlitzでテンプレートを開きます](https://stackblitz.com/github/withastro/starlight/tree/main/examples/basics)。
:::

### 開発用サーバーの起動

ローカルで作業する場合、[Astroの開発サーバー](https://docs.astro.build/ja/reference/cli-reference/#astro-dev)により作業内容のプレビューができ、また変更を加えるとブラウザが自動的に更新されます。

プロジェクトのディレクトリ内で以下のコマンドを実行して、開発サーバーを起動します。

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm run dev
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dev
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dev
```

</TabItem>
</Tabs>

ターミナルにローカルプレビューのURLが表示されます。このURLを開くと、サイトを閲覧できます。

### コンテンツの追加

Starlightに新しいコンテンツを追加したり、既存のファイルを追加したりする準備ができました!

`src/content/docs/`ディレクトリにMarkdownファイルを作成することで、サイトに新しいページを追加できます。

ファイルベースのルーティングや、MDXとMarkdocファイルのサポートについて、詳しくは[「ページ」](/ja/guides/pages/)ガイドを参照してください。

### 次のステップ

- **設定:** [「Starlightのカスタマイズ」](/ja/guides/customization/)で、よく使われるオプションについて学びましょう。
- **ナビゲーション:** [「サイドバーのナビゲーション」](/ja/guides/sidebar/)ガイドで、サイドバーを設定しましょう。
- **コンポーネント:** [「コンポーネント」](/ja/components/using-components/)ガイドで、カードやタブなどの組み込みコンポーネントを確認しましょう。
- **拡張:** [「プラグイン」](/ja/resources/plugins/)や[「テーマ」](/ja/resources/themes/)のカタログで、コミュニティ製のアドオンを探してみましょう。
- **デプロイ:** Astroドキュメントの[「サイトのデプロイ」](https://docs.astro.build/ja/guides/deploy/)ガイドを参考に、あなたの作品を公開しましょう。

## Starlightを更新する

:::tip[ヒント]
Starlightはベータ版のソフトウェアであるため、頻繁に更新や改善がおこなわれます。Starlightを定期的に更新してください!
:::

StarlightはAstroインテグレーションです。ターミナルで以下のコマンドを実行すると、他のAstroパッケージと一緒にStarlightを更新できます。

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npx @astrojs/upgrade
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dlx @astrojs/upgrade
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dlx @astrojs/upgrade
```

</TabItem>
</Tabs>

[Starlightのチェンジログ](https://github.com/withastro/starlight/blob/main/packages/starlight/CHANGELOG.md)から、各リリースでおこなわれた変更の全リストを確認できます。

## Starlightのトラブルシューティング

[プロジェクト設定](/ja/reference/configuration/)と[個別ページのフロントマターの設定](/ja/reference/frontmatter/)のリファレンスページを確認して、Starlightサイトが正しく設定され、正常に動作していることを確認してください。コンテンツの追加やStarlightサイトのカスタマイズについては、サイドバーにあるガイドを参照してください。

これらのドキュメントで答えが見つからない場合は、Astroに関してより詳細に記述されている[Astroドキュメント](https://docs.astro.build)を参照してください。Starlightテーマの下でAstroがどのように動作しているかを理解することで、疑問が解消されるかもしれません。

また、[GitHub上でStarlightのIssue](https://github.com/withastro/starlight/issues)を確認したり、[AstroのDiscord](https://astro.build/chat/)で活発でフレンドリーなコミュニティに助けを求めることもできます!`#support`フォーラムに「starlight」タグを付けて質問を投稿したり、`#starlight`専用のチャンネルにアクセスして、現在の開発などについて議論しましょう!


================================================
FILE: docs/src/content/docs/ja/guides/authoring-content.mdx
================================================
---
title: Markdownでのコンテンツ作成
description: StarlightがサポートするMarkdown構文の概要。
---

Starlightでは、`.md`ファイルにおいて[Markdown](https://daringfireball.net/projects/markdown/)構文のすべての機能を利用できます。また、タイトルや説明文(description)などのメタデータを定義するためのフロントマター[YAML](https://dev.to/paulasantamaria/introduction-to-yaml-125f)もサポートしています。

MDXやMarkdocを使用する場合、サポートされるMarkdownの機能や使用方法が異なることがあるため、[MDXドキュメント](https://mdxjs.com/docs/what-is-mdx/#markdown)や[Markdocドキュメント](https://markdoc.dev/docs/syntax)を必ず確認してください。

## フロントマター

フロントマターに値を設定して、Starlightの個々のページをカスタマイズできます。フロントマターは、ファイル先頭の`---`によって区切られた区間に設定します。

```md title="src/content/docs/example.md"
---
title: ページのタイトル
---

ページのコンテンツは、2つ目の`---`の後に続きます。
```

すべてのページには、少なくとも`title`が必要です。利用可能なすべてのフィールドと、カスタムフィールドの追加方法については、[フロントマターのリファレンス](/ja/reference/frontmatter/)を参照してください。

## インラインスタイル

テキストは**太字**、_斜体_、または~~取り消し線~~にできます。

```md
テキストは**太字**、_斜体_、または~~取り消し線~~にできます。
```

[別のページにリンク](/ja/getting-started/)できます。

```md
[別のページにリンク](/ja/getting-started/)できます。
```

バックティックで`インラインコード`を強調できます。

```md
バックティックで`インラインコード`を強調できます。
```

## 画像

Starlightは、[Astro組み込みのアセット最適化機能](https://docs.astro.build/ja/guides/images/)を使用して画像を表示します。

MarkdownとMDXは、スクリーンリーダーや支援技術のための代替テキストを含む画像を表示するためのMarkdown構文をサポートしています。

![「astro」という単語を中心に据えた惑星と恒星のイラスト](https://raw.githubusercontent.com/withastro/docs/main/public/default-og-image.png)

```md
![「astro」という単語を中心に据えた惑星と恒星のイラスト](https://raw.githubusercontent.com/withastro/docs/main/public/default-og-image.png)
```

プロジェクトにローカルに保存されている画像についても、相対パスを使用して表示できます。

```md
// src/content/docs/page-1.md

![宇宙空間に浮かぶロケット](../../assets/images/rocket.svg)
```

## 見出し

見出しによりコンテンツを構造化できます。Markdownの見出しは、行の先頭にある`#`の数で示されます。

### ページコンテンツを構造化する方法

Starlightは、ページタイトルをトップレベルの見出しとして自動的に使用し、また各ページの目次の先頭に「概要」という見出しを含めます。各ページを通常のテキストコンテンツで開始し、ページ上の見出しは`<h2>`以下を使用することをおすすめします。

```md
---
title: Markdownガイド
description: StarlightでのMarkdownの使い方
---

このページでは、StarlightでMarkdownを使用する方法について説明します。

## インラインスタイル

## 見出し
```

### 見出しの自動アンカーリンク

Markdownで見出しを使用するとアンカーリンクが自動的に付与されるため、ページの特定のセクションに直接リンクできます。

```md
---
title: 私のページコンテンツ
description: Starlightの組み込みアンカーリンクの使い方
---

## はじめに

同じページの下部にある[結論](#結論)にリンクできます。

## 結論

`https://my-site.com/page1/#はじめに`は、「はじめに」に直接移動します。
```

レベル2(`<h2>`)とレベル3(`<h3>`)の見出しは、ページの目次に自動的に表示されます。

Astroが見出しの`id`をどのように処理するかについて、詳しくは[Astroドキュメント](https://docs.astro.build/ja/guides/markdown-content/#見出しid)を参照してください。

## 補足情報

補足情報(「警告」や「吹き出し」とも呼ばれます)は、ページのメインコンテンツと並べて補助的な情報を表示するのに便利です。

Starlightは、補足情報をレンダリングするためのカスタムMarkdown構文を提供しています。補足情報のブロックは、コンテンツを囲む3つのコロン`:::`によって示し、`note`(注釈)、`tip`(ヒント)、`caution`(注意)、`danger`(危険)というタイプに設定できます。

他のMarkdownコンテンツを補足情報の中にネストできますが、補足情報は短く簡潔なコンテンツに最も適しています。

### 注釈

:::note
Starlightは、[Astro](https://astro.build/)製のドキュメントサイト用ツールキットです。次のコマンドではじめられます。

```sh
npm create astro@latest -- --template starlight
```

:::

````md
:::note
Starlightは、[Astro](https://astro.build/)製のドキュメントサイト用ツールキットです。次のコマンドではじめられます。

```sh
npm create astro@latest -- --template starlight
```

:::
````

### カスタムのタイトル

補足情報のカスタムタイトルを、補足情報のタイプの後ろに角括弧で囲んで指定できます。たとえば`:::tip[ご存知でしたか?]`のようにできます。

:::tip[ご存知でしたか?]
Astroでは[「アイランドアーキテクチャ」](https://docs.astro.build/ja/concepts/islands/)を使用して、より高速なWebサイトを構築できます。
:::

```md
:::tip[ご存知でしたか?]
Astroでは[「アイランドアーキテクチャ」](https://docs.astro.build/ja/concepts/islands/)を使用して、より高速なWebサイトを構築できます。
:::
```

### カスタムの補足アイコン

補足情報のタイプまたは[カスタムタイトル](#カスタムのタイトル)の後ろに波括弧でカスタムアイコンを指定できます。たとえば`:::tip{icon="heart"}`や`:::tip[ご存知でしたか?]{icon="heart"}`のようにできます。アイコン名は、[Starlightの組み込みアイコン](/ja/reference/icons/#すべてのアイコン)の名前に設定する必要があります。

:::tip{icon="heart"}
Astroでは[「アイランドアーキテクチャ」](https://docs.astro.build/ja/concepts/islands/)を使用して、高速なWebサイトを構築できます。
:::

```md
:::tip{icon="heart"}
Astroでは[「アイランドアーキテクチャ」](https://docs.astro.build/ja/concepts/islands/)を使用して、高速なWebサイトを構築できます。
:::
```

### その他のタイプ

注意(Caution)と危険(Danger)の補足は、ユーザーがつまずく可能性のある細かい点に注意を向けさせるのに役立ちます。もしこれらを多用しているとすれば、それはあなたがドキュメントを書いている対象の設計を見直す余地があることのサインかもしれません。

:::caution
もしあなたが素晴らしいドキュメントサイトを望んでいないのであれば、[Starlight](/ja/)は不要かもしれません。
:::

:::danger
Starlightの便利な機能のおかげで、ユーザーはより生産的になり、プロダクトはより使いやすくなるかもしれません。

- わかりやすいナビゲーション
- ユーザーが設定可能なカラーテーマ
- [国際化機能](/ja/guides/i18n/)

:::

```md
:::caution
もしあなたが素晴らしいドキュメントサイトを望んでいないのであれば、[Starlight](/ja/)は不要かもしれません。
:::

:::danger
Starlightの便利な機能のおかげで、ユーザーはより生産的になり、プロダクトはより使いやすくなるかもしれません。

- わかりやすいナビゲーション
- ユーザーが設定可能なカラーテーマ
- [国際化機能](/ja/guides/i18n/)

:::
```

## 引用

> これは引用です。他の人の言葉やドキュメントを引用するときによく使われます。
>
> 引用は、各行の先頭に`>`を付けることで示されます。

```md
> これは引用です。他の人の言葉やドキュメントを引用するときによく使われます。
>
> 引用は、各行の先頭に`>`を付けることで示されます。
```

## コードブロック

コードのブロックは、先頭と末尾に3つのバックティック<code>```</code>を持つブロックで示されます。コードブロックを開始するバックティックの後ろに、使用されているプログラミング言語を指定できます。

```js
// シンタックスハイライトされたJavascriptコード。
var fun = function lang(l) {
	dateformat.i18n = require('./lang/' + l);
	return true;
};
```

````md
```js
// シンタックスハイライトされたJavascriptコード。
var fun = function lang(l) {
	dateformat.i18n = require('./lang/' + l);
	return true;
};
```
````

### Expressive Codeの機能

Starlightは、コードブロックのフォーマットを拡張するために[Expressive Code](https://expressive-code.com/)を使用しています。Expressive Codeのテキストマーカーとウィンドウフレームプラグインはデフォルトで有効になっています。コードブロックのレンダリングは、Starlightの[`expressiveCode`設定オプション](/ja/reference/configuration/#expressivecode)により設定できます。

#### テキストマーカー

[Expressive Codeのテキストマーカー](https://expressive-code.com/key-features/text-markers/)をコードブロックの先頭で使うことで、コードブロックの特定の行や部分をハイライトできます。波括弧(`{ }`)を使って行全体をハイライトし、引用符を使ってテキストの文字列をハイライトします。

ハイライトのスタイルは3つあります。コードに注意を向けるための中立的なスタイル、挿入されたコードを示す緑色のスタイル、削除されたコードを示す赤色のスタイルです。テキストと行全体の両方を、デフォルトのマーカー、または`ins=`と`del=`を組み合わせてマークし、目的のハイライトを生成できます。

Expressive Codeには、コードサンプルの外観をカスタマイズするためのさまざまなオプションが用意されています。これらの多くは組み合わせることができ、非常に明快なコードサンプルを作成できます。利用可能な多くのオプションについては、[Expressive Codeのドキュメント](https://expressive-code.com/key-features/text-markers/#configuration)を確認してください。最も一般的な例をいくつか以下に示します。

- [行全体と行の範囲を`{ }`マーカーを使ってマークする](https://expressive-code.com/key-features/text-markers/#marking-full-lines--line-ranges):

  ```js {2-3}
  function demo() {
  	// この行(2行目)と次の行はハイライトされます
  	return 'このスニペットの3行目です';
  }
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```js {2-3}
  function demo() {
  	// この行(2行目)と次の行はハイライトされます
  	return 'このスニペットの3行目です';
  }
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```js {% meta="{2-3}" %}
  function demo() {
  	// この行(2行目)と次の行はハイライトされます
  	return 'このスニペットの3行目です';
  }
  ```
  ````

  </TabItem>

  </Tabs>

- [`" "`マーカーまたは正規表現を使って選択されたテキストをマークする](https://expressive-code.com/key-features/text-markers/#marking-individual-text-inside-lines):

  ```js "個別の用語" /正規表現.*います/
  // 個別の用語もハイライトできます
  function demo() {
  	return '正規表現もサポートされています';
  }
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```js "個別の用語" /正規表現.*います/
  // 個別の用語もハイライトできます
  function demo() {
  	return '正規表現もサポートされています';
  }
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```js {% meta="'個別の用語' /正規表現.*います/" %}
  // 個別の用語もハイライトできます
  function demo() {
  	return '正規表現もサポートされています';
  }
  ```
  ````

  </TabItem>

  </Tabs>

- [追加、削除されたテキストや行を、`ins`と`del`でマークする](https://expressive-code.com/key-features/text-markers/#selecting-inline-marker-types-mark-ins-del):

  ```js "return true;" ins="挿入" del="削除"
  function demo() {
  	console.log('これらは挿入と削除のマーカーです');
  	// return文はデフォルトのマーカータイプを使用します
  	return true;
  }
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```js "return true;" ins="挿入" del="削除"
  function demo() {
  	console.log('これらは挿入と削除のマーカーです');
  	// return文はデフォルトのマーカータイプを使用します
  	return true;
  }
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```js {% meta="'return true;' ins='挿入' del='削除'" %}
  function demo() {
  	console.log('これらは挿入と削除のマーカーです');
  	// return文はデフォルトのマーカータイプを使用します
  	return true;
  }
  ```
  ````

  </TabItem>

  </Tabs>

- [構文ハイライトと`diff`風の構文を組み合わせる](https://expressive-code.com/key-features/text-markers/#combining-syntax-highlighting-with-diff-like-syntax):

  ```diff lang="js"
    function thisIsJavaScript() {
      // このブロック全体はJavaScriptとしてハイライトされますが、
      // diffマーカーの追加も可能です!
  -   console.log('削除される古いコード')
  +   console.log('新しいキラキラコード!')
    }
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```diff lang="js"
    function thisIsJavaScript() {
      // このブロック全体はJavaScriptとしてハイライトされますが、
      // diffマーカーの追加も可能です!
  -   console.log('削除される古いコード')
  +   console.log('新しいキラキラコード!')
    }
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```diff {% meta="lang='js'" %}
    function thisIsJavaScript() {
      // このブロック全体はJavaScriptとしてハイライトされますが、
      // diffマーカーの追加も可能です!
  -   console.log('削除される古いコード')
  +   console.log('新しいキラキラコード!')
    }
  ```
  ````

  </TabItem>

  </Tabs>

#### フレームとタイトル

コードブロックをウィンドウのようなフレームの中にレンダリングできます。シェルスクリプト言語(`bash`や`sh`など)には、ターミナルウィンドウのようなフレームが使用されます。その他の言語は、タイトルを含んでいる場合、コードエディタスタイルのフレーム内に表示されます。

`title="..."`属性を、コードブロックの開始を表わすバックティックと言語識別子の後ろに続けて記述するか、コードの最初の行にファイル名コメントを記述することで、コードブロックにオプションでタイトルを設定できます。

- [コメントによりファイル名タブを追加する](https://expressive-code.com/key-features/frames/#code-editor-frames)

  ```js
  // my-test-file.js
  console.log('Hello World!');
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```js
  // my-test-file.js
  console.log('Hello World!');
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````md
  ```js
  // my-test-file.js
  console.log('Hello World!');
  ```
  ````

  </TabItem>

  </Tabs>

- [Terminalウィンドウにタイトルを追加する](https://expressive-code.com/key-features/frames/#terminal-frames)

  ```bash title="依存関係のインストール中…"
  npm install
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```bash title="依存関係のインストール中…"
  npm install
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```bash {% title="依存関係のインストール中…" %}
  npm install
  ```
  ````

  </TabItem>

  </Tabs>

- [`frame="none"`によりウィンドウフレームを無効化する](https://expressive-code.com/key-features/frames/#overriding-frame-types)

  ```bash frame="none"
  echo "bash言語を使用していますが、これはターミナルとしてレンダリングされません"
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```bash frame="none"
  echo "bash言語を使用していますが、これはターミナルとしてレンダリングされません"
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```bash {% frame="none" %}
  echo "bash言語を使用していますが、これはターミナルとしてレンダリングされません"
  ```
  ````

  </TabItem>

  </Tabs>

## Details

Details(「ディスクロージャー」や「アコーディオン」とも呼ばれます)は、すぐには必要ないコンテンツを非表示にするのに便利です。ユーザーは短い要約をクリックして、コンテンツ全体を展開・表示できます。

Markdownコンテンツ内で標準のHTML要素[`<details>`](https://developer.mozilla.org/ja/docs/Web/HTML/Element/details)と[`<summary>`](https://developer.mozilla.org/ja/docs/Web/HTML/Element/summary)を使用して、ディスクロージャーウィジェットを作成できます。

`<details>`要素の中には、他のMarkdown構文をネストできます。

<details>
<summary>アンドロメダ座が最もよく見えるのはいつ、どこ?</summary>

[アンドロメダ座](https://ja.wikipedia.org/wiki/アンドロメダ座)は、北緯`+90°`から南緯`-40°`の間の緯度で、11月の夜空に最もよく見えます。

</details>

```md
<details>
<summary>アンドロメダ座が最もよく見えるのはいつ、どこ?</summary>

[アンドロメダ座](https://ja.wikipedia.org/wiki/アンドロメダ座)は、北緯`+90°`から南緯`-40°`の間の緯度で、11月の夜空に最もよく見えます。

</details>
```

## 脚注

[脚注](https://www.markdownguide.org/extended-syntax/#footnotes)は、コンテンツの流れを中断することなく、簡潔な参照や補足を追加するのに便利です。脚注は、ページの下部に集められた参照テキストへジャンプする、番号付きの上付きリンクとして表示されます。

脚注は、角括弧とキャレット、番号付き参照を使用して定義します。

```md
ここに脚注[^1]があり、その後にテキストが続きます。

[^1]: 参照内容。
```

## その他の一般的なMarkdown機能

Starlightは、リストやテーブルなど、その他のMarkdown記法をすべてサポートしています。Markdownのすべての構文要素の概要については、[The Markdown GuideのMarkdownチートシート](https://www.markdownguide.org/cheat-sheet/)を参照してください。

## 高度なMarkdownとMDXの設定

Starlightは、remarkとrehypeをベースとした、AstroのMarkdown・MDXレンダラーを使用しています。Astroの設定ファイルに`remarkPlugins`または`rehypePlugins`を追加することで、カスタム構文や動作をサポートできます。詳しくは、Astroドキュメントの[「Markdownプラグイン」](https://docs.astro.build/ja/guides/markdown-content/#markdown-plugins)を参照してください。

## Markdoc

Starlightは、実験的な[Astro Markdoc統合](https://docs.astro.build/ja/guides/integrations-guide/markdoc/)とStarlight Markdocプリセットを使用して、Markdocでのコンテンツ作成をサポートしています。

### Markdocで新しいプロジェクトを作成する

`create astro`を使用して、Markdocが事前設定された新しいStarlightプロジェクトを開始します。

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight/markdoc
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight/markdoc
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight/markdoc
```

</TabItem>
</Tabs>

### 既存のプロジェクトにMarkdocを追加する

既にStarlightサイトがあり、Markdocを追加したい場合は、以下の手順に従ってください。

<Steps>

1.  AstroのMarkdoc統合を追加します。

    <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npx astro add markdoc
    ```

    </TabItem>

    <TabItem label="pnpm">

    ```sh
    pnpm astro add markdoc
    ```

    </TabItem>

    <TabItem label="Yarn">

    ```sh
    yarn astro add markdoc
    ```

    </TabItem>

    </Tabs>

2.  Starlight Markdocプリセットをインストールします。

    <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npm install @astrojs/starlight-markdoc
    ```

    </TabItem>

    <TabItem label="pnpm">

    ```sh
    pnpm add @astrojs/starlight-markdoc
    ```

    </TabItem>

    <TabItem label="Yarn">

    ```sh
    yarn add @astrojs/starlight-markdoc
    ```

    </TabItem>

    </Tabs>

3.  `markdoc.config.mjs`にMarkdoc設定ファイルを作成し、Starlight Markdocプリセットを使用します。

    ```js
    import { defineMarkdocConfig } from '@astrojs/markdoc/config';
    import starlightMarkdoc from '@astrojs/starlight-markdoc';

    export default defineMarkdocConfig({
    	extends: [starlightMarkdoc()],
    });
    ```

</Steps>

Markdocの構文と機能についてさらに学ぶには、[Markdocのドキュメント](https://markdoc.dev/docs/syntax)または[Astro Markdoc統合ガイド](https://docs.astro.build/ja/guides/integrations-guide/markdoc/)を参照してください。

### Markdocプリセットの設定

`starlightMarkdoc()`プリセットは、以下の設定オプションを受け付けます。

#### `headingLinks`

**type:** `boolean`  
**default:** `true`

見出しにクリック可能なアンカーリンクを付けてレンダリングするかどうかを制御します。MarkdownおよびMDXファイルに適用される[`markdown.headingLinks`](/ja/reference/configuration/#markdown)オプションと同等です。

```js "headingLinks: false"
export default defineMarkdocConfig({
	// デフォルトの見出しアンカーリンクのサポートを無効にする
	extends: [starlightMarkdoc({ headingLinks: false })],
});
```


================================================
FILE: docs/src/content/docs/ja/guides/css-and-tailwind.mdx
================================================
---
title: CSSとスタイリング
description: カスタムCSSやTailwind CSSを使用して、Starlightサイトをスタイリングする方法を学びます。
---

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

カスタムCSSファイルやStarlightのTailwindプラグインを使用して、Starlightサイトをスタイリングできます。

サイトのデフォルトスタイルを手軽に変更するには、[コミュニティテーマ](/ja/resources/themes/)を確認してください。

## カスタムCSSスタイル

Starlightサイトに適用されるスタイルをカスタマイズするには、追加のCSSファイルを作成し、Starlightのデフォルトスタイルを変更または拡張します。

<Steps>

1. `src/`ディレクトリにCSSファイルを追加します。たとえば、以下ではデフォルトのカラム幅を広げ、ページタイトルのテキストサイズを大きくしています。

   ```css
   /* src/styles/custom.css */
   :root {
   	--sl-content-width: 50rem;
   	--sl-text-5xl: 3.5rem;
   }
   ```

2. `astro.config.mjs`で、Starlightの`customCss`配列にCSSファイルへのパスを追加します。

   ```diff lang="js"
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'カスタムCSSを設定したドキュメント',
   			customCss: [
   +				// カスタムCSSファイルへの相対パス
   +				'./src/styles/custom.css',
   			],
   		}),
   	],
   });
   ```

</Steps>

[GitHub上の`props.css`ファイル](https://github.com/withastro/starlight/blob/main/packages/starlight/style/props.css)で、サイトをカスタマイズするために設定可能な、Starlightが使用しているすべてのカスタムCSSプロパティを確認できます。

### カスケードレイヤー

Starlightは内部で[カスケードレイヤー](https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks/Cascade_layers)を使用して、スタイルの適用順序を管理しています。これにより、CSSの適用順序が予測可能になり、またスタイルの上書きが容易になります。レイヤーに属さないカスタムCSSは、Starlightのスタイルを上書きします。

カスケードレイヤーを使用する場合は、カスタムCSSで[`@layer`](https://developer.mozilla.org/ja/docs/Web/CSS/@layer)を使用して、`starlight`レイヤーのスタイルに対する各レイヤーの優先順位を定義できます。

```css "starlight"
/* src/styles/custom.css */
@layer my-reset, starlight, my-overrides;
```

上の例では、`my-reset`というカスタムレイヤーはすべてのStarlightレイヤーの前に適用され、`my-overrides`というカスタムレイヤーはすべてのStarlightレイヤーの後に適用されます。`my-overrides`レイヤー内のスタイルはStarlightのスタイルよりも優先されますが、`my-reset`レイヤーに設定されたスタイルはStarlightによって変更される可能性があります。

## Tailwind CSS

AstroプロジェクトでのTailwind CSS v4のサポートは、[TailwindのViteプラグイン](https://tailwindcss.com/docs/installation/using-vite)によって提供されています。また、Starlightは、Starlightのスタイルとの互換性を保ちつつTailwindを設定するのに役立つ、補完的なCSSを提供しています。

StarlightのTailwind CSSは、以下の設定を適用します。

- Tailwindの`dark:`バリアントをStarlightのダークモードと連携するように設定します。
- StarlightのUIでTailwindの[テーマカラーとフォント](#starlightをtailwindでスタイリングする)を使用します。
- TailwindのPreflightリセットスタイルのうち、必要な部分を復元します。

### Tailwindを使用して新しいプロジェクトを作成する

`create astro`を使用して、Tailwind CSSが組み込まれた新しいStarlightプロジェクトを開始します。

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight/tailwind
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight/tailwind
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight/tailwind
```

</TabItem>
</Tabs>

### Tailwindを既存のプロジェクトに追加する

既存のStarlightサイトにTailwind CSSを追加する場合は、以下の手順に従ってください。

<Steps>

1.  以下のコマンドを実行し、ターミナルの指示に従って、プロジェクトにTailwindをセットアップします。

    <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npx astro add tailwind
    ```

    </TabItem>

    <TabItem label="pnpm">

    ```sh
    pnpm astro add tailwind
    ```

    </TabItem>

    <TabItem label="Yarn">

    ```sh
    yarn astro add tailwind
    ```

    </TabItem>

    </Tabs>

2.  StarlightのTailwind互換パッケージをインストールします。

    <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npm install @astrojs/starlight-tailwind
    ```

    </TabItem>

    <TabItem label="pnpm">

    ```sh
    pnpm add @astrojs/starlight-tailwind
    ```

    </TabItem>

    <TabItem label="Yarn">

    ```sh
    yarn add @astrojs/starlight-tailwind
    ```

    </TabItem>

    </Tabs>

3.  Astroによって生成された`src/styles/global.css`ファイルの内容を、Starlightとの互換性のために以下のように置き換えます。

    ```css
    /* src/styles/global.css */
    @layer base, starlight, theme, components, utilities;

    @import '@astrojs/starlight-tailwind';
    @import 'tailwindcss/theme.css' layer(theme);
    @import 'tailwindcss/utilities.css' layer(utilities);
    ```

    このTailwindテーマの設定は、Starlightの[カスケードレイヤー](#カスケードレイヤー)の順序を定義し、StarlightのTailwind補完CSSをインポートし、Tailwindのテーマとユーティリティスタイルをインポートします。プロジェクトで追加のTailwindの設定が必要な場合は、[「Tailwindの設定を複数使用する」](#tailwindの設定を複数使用する)セクションを参照してください。

4.  Starlightの設定を更新して、`customCss`配列の最初のアイテムとしてTailwind CSSのファイルを追加します。

    ```js ins={11-12}
    // astro.config.mjs
    import { defineConfig } from 'astro/config';
    import starlight from '@astrojs/starlight';
    import tailwindcss from '@tailwindcss/vite';

    export default defineConfig({
    	integrations: [
    		starlight({
    			title: 'Tailwindを使ったドキュメント',
    			customCss: [
    				// Tailwindのベーススタイルへのパス
    				'./src/styles/global.css',
    			],
    		}),
    	],
    	vite: { plugins: [tailwindcss()] },
    });
    ```

</Steps>

### StarlightをTailwindでスタイリングする

[Tailwindを使用して新しいStarlightプロジェクトを作成した](#tailwindを使用して新しいプロジェクトを作成する)場合、または[既存のStarlightプロジェクトにTailwindを追加した](#tailwindを既存のプロジェクトに追加する)場合、Starlightは`src/styles/global.css`ファイルにある[Tailwindテーマの設定値](https://tailwindcss.com/docs/theme)を使用してUIをスタイリングします。

以下のCSSカスタムプロパティが設定されている場合、Starlightのデフォルトスタイルが上書きされます。

- `--color-accent-*` — リンクと現在のアイテムのハイライトに使用されます
- `--color-gray-*` — 背景色とボーダーに使用されます
- `--font-sans` — UIとコンテンツのテキストに使用されます
- `--font-mono` — コード例に使用されます

```css {9,11,13,25}
/* src/styles/global.css */
@layer base, starlight, theme, components, utilities;

@import '@astrojs/starlight-tailwind';
@import 'tailwindcss/theme.css' layer(theme);
@import 'tailwindcss/utilities.css' layer(utilities);

@theme {
	/* 好みのテキストフォント。Starlightはデフォルトでシステムフォントスタックを使用します。 */
	--font-sans: 'Atkinson Hyperlegible';
	/* 好みのコードフォント。Starlightはデフォルトでシステムの等幅フォントを使用します。 */
	--font-mono: 'IBM Plex Mono';
	/* 好みのアクセントカラー。インディゴはStarlightのデフォルトに最も近い色です。 */
	--color-accent-50: var(--color-indigo-50);
	--color-accent-100: var(--color-indigo-100);
	--color-accent-200: var(--color-indigo-200);
	--color-accent-300: var(--color-indigo-300);
	--color-accent-400: var(--color-indigo-400);
	--color-accent-500: var(--color-indigo-500);
	--color-accent-600: var(--color-indigo-600);
	--color-accent-700: var(--color-indigo-700);
	--color-accent-800: var(--color-indigo-800);
	--color-accent-900: var(--color-indigo-900);
	--color-accent-950: var(--color-indigo-950);
	/* 好みのグレースケール。ZincはStarlightのデフォルトに最も近い色です。 */
	--color-gray-50: var(--color-zinc-50);
	--color-gray-100: var(--color-zinc-100);
	--color-gray-200: var(--color-zinc-200);
	--color-gray-300: var(--color-zinc-300);
	--color-gray-400: var(--color-zinc-400);
	--color-gray-500: var(--color-zinc-500);
	--color-gray-600: var(--color-zinc-600);
	--color-gray-700: var(--color-zinc-700);
	--color-gray-800: var(--color-zinc-800);
	--color-gray-900: var(--color-zinc-900);
	--color-gray-950: var(--color-zinc-950);
}
```

### Tailwindの設定を複数使用する

Tailwindの設定を複数使用することで、サイトの各部分に異なるスタイルを適用できます。[Starlightをサブパスで使用する](/ja/manual-setup/#サブパスへのstarlightの追加)場合や、サイトに[カスタムページ](/ja/guides/pages/#カスタムページ)を追加する場合などに便利です。たとえば、カスタムページではTailwindのPreflightリセットスタイルを使用しつつ、StarlightページにはStarlightの互換レイヤーを適用したい場合があるでしょう。

以下のTailwind CSSの設定は、プラグインや追加設定なしでTailwindをセットアップするもので、非Starlightのページの出発点として使用できます。

```css title="src/styles/custom-pages-tailwind.css"
/* StarlightのCSSなしでTailwindを読み込む */
@import 'tailwindcss';
```

<Steps>

1. Starlightページには、[「Tailwindを既存のプロジェクトに追加する」](#tailwindを既存のプロジェクトに追加する)に従って、好みのTailwind CSSの設定を適用します。

2. その他のページには、好みのTailwind CSSの設定をインポートして適用します。これは通常、レイアウトコンポーネントで行われ、そのレイアウトを共有するすべてのページでTailwindのスタイルを使用できるようになります。
   ```astro
   ---
   // src/layouts/CustomPageLayout.astro
   import '../styles/custom-pages-tailwind.css';
   ---
   ```

</Steps>

Tailwindテーマの設定について詳しくは、[Tailwind CSSのドキュメント](https://tailwindcss.com/docs/theme)を参照してください。

## テーマの設定

Starlightのカラーテーマは、デフォルトのカスタムプロパティを上書きしてコントロールできます。これらの変数はUI全体で使用されます。テキストと背景色にはグレーシェードが使用され、リンクとナビゲーションの現在のアイテムをハイライトするためにはアクセントカラーが使用されます。

### テーマカラーエディタ

以下のスライダーを使用して、Starlightのアクセントカラーとグレーカラーのパレットを変更してみましょう。ダークとライトのプレビューエリアには、結果となる色の組み合わせが表示されます。また、このページ自体も合わせて更新されるため、変更内容をプレビューできます。

コントラストレベルオプションで、WCAGによる[色のコントラスト基準](https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable/Color_contrast)から満たしたいものを指定します。

変更内容に満足できたら、以下のCSSまたはTailwindコードをコピーしてプロジェクトで使用します。

import ThemeDesigner from '~/components/theme-designer.astro';

<ThemeDesigner
	labels={{
		presets: {
			label: 'プリセット',
			ocean: 'オーシャン',
			forest: 'フォレスト',
			oxide: 'オキシド',
			nebula: 'ネビュラ',
			default: 'デフォルト',
			random: 'ランダム',
		},
		contrast: {
			label: 'コントラストレベル',
		},
		editor: {
			accentColor: 'アクセント',
			grayColor: 'グレー',
			hue: '色相',
			chroma: '彩度',
			pickColor: '色の選択',
		},
		preview: {
			darkMode: 'ダークモード',
			lightMode: 'ライトモード',
			bodyText:
				'本文は背景とのコントラストが高いグレーシェードで表示されます。',
			linkText: 'リンクは色付けされます。',
			dimText: '目次などの一部のテキストは、コントラストが低くなります。',
			inlineCode: 'インラインコードは独自の背景色をもちます。',
		},
	}}
>
	<Fragment slot="css-docs">
		以下のCSSを[カスタムCSSファイル](#カスタムcssスタイル)に追加して、このテーマをサイトに適用します。
	</Fragment>
	<Fragment slot="tailwind-docs">
		以下のCSS変数を[Tailwind
		CSSファイル](#starlightをtailwindでスタイリングする)の`@theme`ブロックに追加して、このテーマをサイトに適用します。
	</Fragment>
</ThemeDesigner>


================================================
FILE: docs/src/content/docs/ja/guides/customization.mdx
================================================
---
title: Starlightのカスタマイズ
description: Starlightサイトをカスタマイズして、ロゴ、カスタムフォント、ランディングページのデザインなどを追加する方法について学びます。
---

import { Tabs, TabItem, FileTree, Steps } from '@astrojs/starlight/components';

Starlightには標準的なスタイルと機能がデフォルトで用意されているため、設定不要ですぐに使い始めることができますが、Starlightサイトの見た目をカスタマイズしたくなった場合は、このガイドを参照してください。

## ロゴを追加する

カスタムロゴをサイトヘッダーに設定して、Starlightサイトに個別のブランディングを追加することができます。

<Steps>

1. ロゴ画像のファイルを`src/assets/`ディレクトリに追加します。

   <FileTree>

   - src/
     - assets/
       - **my-logo.svg**
     - content/
   - astro.config.mjs

   </FileTree>

2. `astro.config.mjs`で、Starlightの[`logo.src`](/ja/reference/configuration/#logo)オプションにロゴのパスを指定します。

   ```diff lang="js"
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'ロゴを設定したドキュメント',
   			logo: {
   +				src: './src/assets/my-logo.svg',
   			},
   		}),
   	],
   });
   ```

</Steps>

デフォルトでは、ロゴはサイトの`title`と一緒に表示されます。ロゴ画像にサイトタイトルが含まれている場合は、`replacesTitle`オプションを設定して、タイトルテキストを非表示にすることができます。`title`テキストはスクリーンリーダーのために残されるので、ヘッダーはアクセシブルなままです。

```js {5}
starlight({
  title: 'ロゴを設定したドキュメント',
  logo: {
    src: './src/assets/my-logo.svg',
    replacesTitle: true,
  },
}),
```

### ライトモードとダークモード

ライトモードとダークモードで異なるバージョンのロゴを表示することができます。

<Steps>

1. `src/assets/`に各バージョンの画像ファイルを追加します。

   <FileTree>

   - src/
     - assets/
       - **light-logo.svg**
       - **dark-logo.svg**
     - content/
   - astro.config.mjs

   </FileTree>

2. `astro.config.mjs`で、`src`ではなく`light`と`dark`オプションにロゴのパスを指定します。

   ```diff lang="js"
   starlight({
     title: 'ロゴを設定したドキュメント',
     logo: {
   +    light: './src/assets/light-logo.svg',
   +    dark: './src/assets/dark-logo.svg',
     },
   }),
   ```

</Steps>

## サイトマップを有効化する

Starlightにはサイトマップ生成機能が組み込まれています。`astro.config.mjs`の`site`にURLを設定すると、サイトマップの生成が有効になります。

```js {4}
// astro.config.mjs

export default defineConfig({
	site: 'https://stargazers.club',
	integrations: [starlight({ title: 'サイトマップを設定したサイト' })],
});
```

Astroドキュメントで[`robots.txt`にサイトマップへのリンクを追加する方法](https://docs.astro.build/ja/guides/integrations-guide/sitemap/#sitemap-link-in-robotstxt)について確認してください。

## ページレイアウト

Starlightのページはデフォルトで、グローバルなナビゲーションサイドバーと、現在のページの見出しを表示する目次を配置したレイアウトを使用します。

ページのフロントマターで[`template: splash`](/ja/reference/frontmatter/#template)を設定することで、サイドバーのない、より広いページレイアウトを適用できます。これはランディングページに特に適しており、[このサイトのホームページ](/ja/)で確認することができます。

```md {5}
---
# src/content/docs/index.md

title: ランディングページ
template: splash
---
```

## 目次

Starlightは、目当ての見出しに読者が簡単にジャンプできるように、各ページに目次を表示します。目次は、Starlightインテグレーションでグローバルにカスタマイズ・無効化できます。また、フロントマターでページごとの設定も可能です。

デフォルトでは、目次には`<h2>`と`<h3>`の見出しが含まれます。目次に含める見出しレベルをサイト全体で変更するには、[グローバルな`tableOfContents`](/ja/reference/configuration/#tableofcontents)の`minHeadingLevel`と`maxHeadingLevel`オプションを使用します。個々のページでこれらのデフォルト値を上書きするには、対応する[フロントマターの`tableOfContents`](/ja/reference/frontmatter/#tableofcontents)プロパティを追加します。

<Tabs syncKey="config-type">
  <TabItem label="フロントマター">

```md {4-6}
---
# src/content/docs/example.md
title: 目次にH2のみを表示するページ
tableOfContents:
  minHeadingLevel: 2
  maxHeadingLevel: 2
---
```

  </TabItem>
  <TabItem label="グローバルな設定">

```js {7}
// astro.config.mjs

defineConfig({
	integrations: [
		starlight({
			title: '目次の設定をカスタマイズしたドキュメント',
			tableOfContents: { minHeadingLevel: 2, maxHeadingLevel: 2 },
		}),
	],
});
```

  </TabItem>
</Tabs>

`tableOfContents`オプションを`false`に設定することで、目次を完全に無効にできます。

<Tabs syncKey="config-type">
  <TabItem label="フロントマター">

```md {4}
---
# src/content/docs/example.md
title: 目次のないページ
tableOfContents: false
---
```

  </TabItem>
  <TabItem label="グローバルな設定">

```js {7}
// astro.config.mjs

defineConfig({
	integrations: [
		starlight({
			title: '目次をグローバルに無効にしたドキュメント',
			tableOfContents: false,
		}),
	],
});
```

  </TabItem>
</Tabs>

## ソーシャルリンク

Starlightは、Starlightインテグレーションの[`social`](/ja/reference/configuration/#social)オプションを使用して、サイトヘッダーにソーシャルメディアアカウントへのリンクを追加する機能を備えています。

`social`配列の各エントリは、以下の3つのプロパティをもつオブジェクトです。

- `icon`: Starlightの[組み込みアイコン](/ja/reference/icons/)のいずれか。たとえば`"github"`。
- `label`: リンクのアクセシブルなラベル。たとえば`"GitHub"`。
- `href`: リンクのURL。たとえば`"https://github.com/withastro/starlight"`。

以下の例では、AstroのDiscordチャットとStarlightのGitHubリポジトリへのリンクを追加しています。

```js {9-16}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'ソーシャルリンクを設定したドキュメント',
			social: [
				{ icon: 'discord', label: 'Discord', href: 'https://astro.build/chat' },
				{
					icon: 'github',
					label: 'GitHub',
					href: 'https://github.com/withastro/starlight',
				},
			],
		}),
	],
});
```

## 編集リンク

Starlightは、各ページのフッターに「ページを編集」リンクを表示できます。これにより読者は、ドキュメントを改善するために編集すべきファイルを簡単に見つけられます。特にオープンソースプロジェクトでは、コミュニティからの貢献を促すのに役立ちます。

編集リンクを有効にするには、Starlightインテグレーションの設定で、[`editLink.baseUrl`](/ja/reference/configuration/#editlink)をリポジトリの編集に使用するURLに設定します。`editLink.baseUrl`の値は現在のページへのパスの先頭に追加されて、最終的な編集リンクを形成します。

よくあるパターンは以下の通りです。

- GitHub: `https://github.com/USER_NAME/REPO_NAME/edit/BRANCH_NAME/`
- GitLab: `https://gitlab.com/USER_NAME/REPO_NAME/-/edit/BRANCH_NAME/`

Starlightプロジェクトがリポジトリのルートにない場合は、ベースURLの末尾にプロジェクトへのパスを含めます。

以下の例では、GitHub上にある`withastro/starlight`リポジトリの`main`ブランチの`docs/`サブディレクトリに置かれている、Starlightドキュメントの編集リンクを設定しています。

```js {9-11}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: '編集リンクを設定したドキュメント',
			editLink: {
				baseUrl: 'https://github.com/withastro/starlight/edit/main/docs/',
			},
		}),
	],
});
```

## カスタム404ページ

Starlightサイトは、デフォルトでシンプルな404ページを表示します。これは、`src/content/docs/`ディレクトリに`404.md`(または`404.mdx`)ファイルを追加することでカスタマイズできます。

<FileTree>

- src/
  - content/
    - docs/
      - **404.md**
      - index.md
- astro.config.mjs

</FileTree>

404ページでは、Starlightのページレイアウトとカスタマイズ機能をすべて使用できます。たとえば、デフォルトの404ページは、フロントマターで[`splash`テンプレート](#ページレイアウト)と[`hero`](/ja/reference/frontmatter/#hero)コンポーネントを使用しています。

```md {4,6-8}
---
# src/content/docs/404.md
title: '404'
template: splash
editUrl: false
hero:
  title: '404'
  tagline: ページが見つかりませんでした。URLを確認するか、検索バーを使用してみてください。
---
```

### デフォルトの404ページを無効にする

完全にカスタマイズされた404レイアウトがプロジェクトに必要な場合は、`src/pages/404.astro`ルートを作成し、Starlightのデフォルトルートを無効にするために[`disable404Route`](/ja/reference/configuration/#disable404route)オプションを設定します。

```js {9}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: '404をカスタマイズしたドキュメント',
			disable404Route: true,
		}),
	],
});
```

## カスタムフォント

デフォルトでは、Starlightはユーザーのローカルデバイスで利用可能なサンセリフフォントをすべてのテキストに使用します。これにより、大きなフォントファイルをダウンロードするための余分な帯域幅を必要とせず、各ユーザーに馴染みのあるフォントでドキュメントを高速に読み込むことができます。

Starlightサイトにカスタムフォントを追加する必要がある場合は、カスタムCSSファイルまたは他の[Astroのスタイリング手法](https://docs.astro.build/ja/guides/styling/)により使用するフォントを設定できます。

### フォントの設定

フォントファイルがすでに手元にある場合は、[ローカルの設定ガイド](#ローカルフォントファイルの設定)に従ってください。Google Fontsを使用するには、[Fontsourceの設定ガイド](#fontsourceフォントの設定)に従ってください。

#### ローカルフォントファイルの設定

<Steps>

1. `src/fonts/`ディレクトリにフォントファイルを追加し、空の`font-face.css`ファイルを作成します。

   <FileTree>

   - src/
     - content/
     - fonts/
       - **CustomFont.woff2**
       - **font-face.css**
   - astro.config.mjs

   </FileTree>

2. `src/fonts/font-face.css`に、各フォントの[`@font-face`宣言](https://developer.mozilla.org/ja/docs/Web/CSS/@font-face)を追加します。`url()`関数にフォントファイルへの相対パスを指定します。

   ```css
   /* src/fonts/font-face.css */

   @font-face {
   	font-family: 'カスタムフォント';
   	/* ローカルフォントファイルへの相対パスを`url()`で指定します。 */
   	src: url('./CustomFont.woff2') format('woff2');
   	font-weight: normal;
   	font-style: normal;
   	font-display: swap;
   }
   ```

3. `astro.config.mjs`で、Starlightの`customCss`配列に`font-face.css`ファイルへのパスを追加します。

   ```diff lang="js"
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'カスタムフォントを設定したドキュメント',
   			customCss: [
   +				// @font-face CSSファイルへの相対パス
   +				'./src/fonts/font-face.css',
   			],
   		}),
   	],
   });
   ```

</Steps>

#### Fontsourceフォントの設定

[Fontsource](https://fontsource.org/)プロジェクトは、Google Fontsやその他のオープンソースフォントの使用を容易にします。使いたいフォントのnpmモジュールをインストールすることができ、プロジェクトに追加するためのCSSファイルも用意されています。

<Steps>

1.  [Fontsourceのカタログ](https://fontsource.org/)で使用したいフォントを見つけます。この例では、[IBM Plex Serif](https://fontsource.org/fonts/ibm-plex-serif)を使用します。

2.  使いたいフォントのパッケージをインストールします。Fontsourceのフォントページで「Install」をクリックすると、パッケージ名が表示されます。

         <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npm install @fontsource/ibm-plex-serif
    ```

           </TabItem>

        <TabItem label="pnpm">

    ```sh
    pnpm add @fontsource/ibm-plex-serif
    ```

           </TabItem>

        <TabItem label="Yarn">

    ```sh
    yarn add @fontsource/ibm-plex-serif
    ```

           </TabItem>

      </Tabs>

3.  `astro.config.mjs`で、FontsourceのCSSファイルをStarlightの`customCss`配列に追加します。

    ```diff lang="js"
    // astro.config.mjs
    import { defineConfig } from 'astro/config';
    import starlight from '@astrojs/starlight';

    export default defineConfig({
    	integrations: [
    		starlight({
    			title: 'カスタムフォントを設定したドキュメント',
    			customCss: [
    +				// 標準とセミボールドのフォントウェイト用のFontsourceファイル。
    +				'@fontsource/ibm-plex-serif/400.css',
    +				'@fontsource/ibm-plex-serif/600.css',
    			],
    		}),
    	],
    });
    ```

    Fontsourceは、各フォント用に複数のCSSファイルを同梱しています。異なるウェイトやスタイルを含める方法については、[Fontsourceのドキュメント](https://fontsource.org/docs/getting-started/install#4-weights-and-styles)を参照してください。

</Steps>

### フォントを使う

設定したフォントをサイトに適用するには、選択したフォントの名前を[カスタムCSSファイル](/ja/guides/css-and-tailwind/#カスタムcssスタイル)で指定します。たとえば、Starlightのデフォルトフォントをすべての場所で上書きするには、`--sl-font`カスタムプロパティを設定します。

```css
/* src/styles/custom.css */

:root {
	--sl-font: 'IBM Plex Serif', serif;
}
```

フォントをもっと部分的に適用したい場合は、よりターゲットを絞ったCSSを書くこともできます。たとえば、メインコンテンツにのみフォントを設定し、サイドバーには設定しない場合は、次のようにします。

```css
/* src/styles/custom.css */

main {
	font-family: 'IBM Plex Serif', serif;
}
```

サイトにスタイルを追加するには、[カスタムCSSの導入手順](/ja/guides/css-and-tailwind/#カスタムcssスタイル)に従ってください。


================================================
FILE: docs/src/content/docs/ja/guides/i18n.mdx
================================================
---
title: 国際化(i18n)
description: 複数言語をサポートするためにStarlightサイトを設定する方法について学びます。
---

import { FileTree, Steps } from '@astrojs/starlight/components';

Starlightは、ルーティング、フォールバックコンテンツ、右横書き(right-to-left、RTL)言語へのフルサポートなど、複数言語サイトを構築するための機能を組み込みで提供します。

## i18nの設定

<Steps>

1. [`locales`](/ja/reference/configuration/#locales)と[`defaultLocale`](/ja/reference/configuration/#defaultlocale)をStarlightインテグレーションに渡すことで、サポートする言語についてStarlightに伝えます。

   ```js {9-26}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'My Docs',
   			// このサイトのデフォルト言語として英語を設定します。
   			defaultLocale: 'en',
   			locales: {
   				// 英語のドキュメントは`src/content/docs/en/`に置きます。
   				en: {
   					label: 'English',
   				},
   				// 簡体字中国語のドキュメントは`src/content/docs/zh-cn/`に置きます。
   				'zh-cn': {
   					label: '简体中文',
   					lang: 'zh-CN',
   				},
   				// アラビア語のドキュメントは`src/content/docs/ar/`に置きます。
   				ar: {
   					label: 'العربية',
   					dir: 'rtl',
   				},
   			},
   		}),
   	],
   });
   ```

   `defaultLocale`はフォールバックコンテンツとUIラベルに使用されるため、コンテンツを最初に書く可能性が最も高い言語、またはすでにコンテンツがある言語を選択してください。

2. `src/content/docs/`に各言語のディレクトリを作成します。たとえば上で示した構成に対しては、以下のフォルダを作成します。

   <FileTree>

   - src/
     - content/
       - docs/
         - ar/
         - en/
         - zh-cn/

   </FileTree>

3. これで各言語のディレクトリにコンテンツ用のファイルを追加できるようになりました。言語間でページを関連付けるために、同じページには同じファイル名を使用してください。フォールバックコンテンツや翻訳に関する通知など、Starlightのi18n機能をフル活用しましょう。

   たとえば、`ar/index.md`と`en/index.md`は、アラビア語版と英語版のホームページをそれぞれ表わします。

</Steps>

より高度なi18nシナリオの場合、[Astroの`i18n`設定](https://docs.astro.build/ja/guides/internationalization/#configure-i18n-routing)オプションを使用した国際化の設定も可能です。

### ルートロケールを使用する

「ルート」ロケールを使用すると、パスにi18nプレフィックスを付けずにある言語を提供できます。たとえば英語をルートロケールとすると、英語のページパスは`/en/about`ではなく`/about`のようになります。

ルートロケールを設定するには、`locales`の`root`キーを使用します。ルートロケールがコンテンツのデフォルトロケールでもある場合は、`defaultLocale`を削除するか、`'root'`に設定します。

```js {9,11-14}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'My Docs',
			defaultLocale: 'root', // 任意
			locales: {
				root: {
					label: 'English',
					lang: 'en', // langはルートロケールに必要です
				},
				'zh-cn': {
					label: '简体中文',
					lang: 'zh-CN',
				},
			},
		}),
	],
});
```

`root`ロケールを使用する場合は、言語専用のフォルダではなく、`src/content/docs/`にその言語のページを直接保存します。たとえば上記の設定を使用した場合、英語と中国語のホームページ用ファイルは次のようになります。

<FileTree>

- src/
  - content/
    - docs/
      - **index.md**
      - zh-cn/
        - **index.md**

</FileTree>

#### 単一言語のサイト

デフォルトでは、Starlightは単一言語(英語)のサイトです。他の言語で単一言語のサイトを作成するには、その言語を`locales`において`root`に設定します。

```diff lang="js" {10-13}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: '私のドキュメント',
			locales: {
				root: {
					label: '简体中文',
					lang: 'zh-CN',
				},
			},
		}),
	],
});
```

これにより、言語選択機能などの他の国際化機能は有効化せずに、Starlightのデフォルト言語を上書きできます。

## フォールバックコンテンツ

Starlightは、すべての言語で同等のページが作成されることを想定しています。たとえば`en/about.md`ファイルがある場合、サポートする他の言語でもそれぞれ`about.md`を作成してください。これにより、まだ翻訳されていないページに対して、Starlightが自動的にフォールバックコンテンツを提供できるようになります。

ある言語の翻訳がまだである場合、Starlightはそのページのコンテンツを(`defaultLocale`で設定する)デフォルト言語で表示します。たとえば、概要(about)ページのフランス語版をまだ作成していない場合、デフォルト言語が英語であれば、`/fr/about`を訪れた人には未翻訳であるという通知とともに英語のコンテンツが表示されます。これにより、まずデフォルト言語にコンテンツを追加し、そして翻訳者が時間を掛けて徐々に翻訳していくことが可能となります。

## サイトタイトルを翻訳する

デフォルトでは、Starlightはすべての言語で同じサイトタイトルを使用します。各ロケールのタイトルをカスタマイズする必要がある場合は、Starlightのオプションで[`title`](/ja/reference/configuration/#title必須)にオブジェクトを渡すことができます。

```diff lang="js"
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
-			title: 'My Docs',
+			title: {
+				en: 'My Docs',
+				'zh-CN': '我的文档',
+			},
			defaultLocale: 'en',
			locales: {
				en: { label: 'English' },
				'zh-cn': { label: '简体中文', lang: 'zh-CN' },
			},
		}),
	],
});
```

## StarlightのUIを翻訳する

import LanguagesList from '~/components/languages-list.astro';
import UIStringsList from '~/components/ui-strings-list.astro';

Starlightでは、読者が選択した言語でサイト全体を体験できるように、翻訳されたコンテンツファイルをホストするだけでなく、デフォルトUIの文字列(たとえば目次に表示されている「目次」という見出し)も翻訳できるようになっています。

{/* prettier-ignore */}
<LanguagesList startsSentence />の翻訳済みUI文字列がすでに用意されていますが、[デフォルト言語をさらに追加するための貢献](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md)も歓迎します。

`18n`データコレクションを使用すると、サポートしたい言語の翻訳を追加したり、デフォルトのラベルを上書きしたりできます。

<Steps>

1. 現状が未設定の場合は、`src/content.config.ts`で`i18n`データコレクションを設定します。

   ```diff lang="js" ins=/, (i18nLoader|i18nSchema)/
   // src/content.config.ts
   import { defineCollection } from 'astro:content';
   import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
   import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';

   export const collections = {
   	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
   +	i18n: defineCollection({ loader: i18nLoader(), schema: i18nSchema() }),
   };
   ```

2. UI文字列を追加で翻訳したいロケールごとに、`src/content/i18n/`にJSONファイルを作成します。たとえば、以下ではアラビア語と簡体字中国語の翻訳ファイルを追加しています。

   <FileTree>

   - src/
     - content/
       - i18n/
         - ar.json
         - zh-CN.json

   </FileTree>

3. 翻訳したいキーに対応する翻訳を、JSONファイルに追加します。キーは英語のままとし、値のみを翻訳します(例: `"search.label": "Buscar"`)。

   以下は、Starlightが英語版のデフォルトとして使用している文字列です。

   <UIStringsList />

   Starlightのコードブロックは、[Expressive Code](https://expressive-code.com/)ライブラリによって動作しています。`expressiveCode`キーを使用して、同じJSONファイルでUI文字列の翻訳について設定できます。

   ```json
   {
   	"expressiveCode.copyButtonCopied": "Copied!",
   	"expressiveCode.copyButtonTooltip": "Copy to clipboard",
   	"expressiveCode.terminalWindowFallbackTitle": "Terminal window"
   }
   ```

   Starlightの検索モーダルは、[Pagefind](https://pagefind.app/)ライブラリによって動作しています。PagefindのUIの翻訳は、`pagefind`キーを使用して同じJSONファイルに設定できます。

   ```json
   {
   	"pagefind.clear_search": "Clear",
   	"pagefind.load_more": "Load more results",
   	"pagefind.search_label": "Search this site",
   	"pagefind.filters_label": "Filters",
   	"pagefind.zero_results": "No results for [SEARCH_TERM]",
   	"pagefind.many_results": "[COUNT] results for [SEARCH_TERM]",
   	"pagefind.one_result": "[COUNT] result for [SEARCH_TERM]",
   	"pagefind.alt_search": "No results for [SEARCH_TERM]. Showing results for [DIFFERENT_TERM] instead",
   	"pagefind.search_suggestion": "No results for [SEARCH_TERM]. Try one of the following searches:",
   	"pagefind.searching": "Searching for [SEARCH_TERM]..."
   }
   ```

</Steps>

### 翻訳スキーマを拡張する

`i18nSchema()`オプションの`extend`を設定することで、サイトの翻訳辞書にカスタムキーを追加できます。以下の例では、オプションの`custom.label`キーが新たにデフォルトのキーに追加されています。

```diff lang="js"
// src/content.config.ts
import { defineCollection, z } from 'astro:content';
import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';

export const collections = {
	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
	i18n: defineCollection({
		loader: i18nLoader(),
		schema: i18nSchema({
+			extend: z.object({
+				'custom.label': z.string().optional(),
+			}),
		}),
	}),
};
```

コンテンツコレクションのスキーマについて詳しくは、Astroドキュメントの[「コレクションスキーマの定義」](https://docs.astro.build/ja/guides/content-collections/#defining-the-collection-schema)を参照してください。

## UI翻訳を使用する

Starlightの[組み込みUI文字列](/ja/guides/i18n/#starlightのuiを翻訳する)、[ユーザー定義のUI文字列](/ja/guides/i18n/#翻訳スキーマを拡張する)、および[プラグインが提供するUI文字列](/ja/reference/plugins/#injecttranslations)には、[i18next](https://www.i18next.com/)を利用した共通のAPIを通じてアクセスできます。この共通のAPIは、[文字列補間](https://www.i18next.com/translation-function/interpolation)や[複数形対応](https://www.i18next.com/translation-function/plurals)などの機能もサポートしています。

Astroコンポーネントにおいて、この共通のAPIは[グローバル`Astro`オブジェクト](https://docs.astro.build/ja/reference/api-reference/#locals)の一部として`Astro.locals.t`から利用できます。

```astro title="example.astro"
<p dir={Astro.locals.t.dir()}>
	{Astro.locals.t('404.text')}
</p>
```

[エンドポイント](https://docs.astro.build/ja/guides/endpoints/)でもこの共通のAPIを使用できます。`locals`オブジェクトは[エンドポイントコンテキスト](https://docs.astro.build/ja/reference/api-reference/#locals)の一部として利用できます。

```ts title="src/pages/404.ts"
export const GET = (context) => {
	return new Response(context.locals.t('404.text'));
};
```

Starlightプラグインのコンテキストでは、[`useTranslations()`](/ja/reference/plugins/#usetranslations)ヘルパーを使用して、特定の言語に対するこの共通のAPIにアクセスできます。詳しくは、[プラグインリファレンス](/ja/reference/plugins/)を参照してください。

### UI文字列をレンダリングする

`locals.t()`関数を使用してUI文字列をレンダリングします。これはi18nextの`t()`関数のインスタンスで、最初の引数としてUI文字列のキーを受け取り、現在の言語に対応する翻訳を返します。

たとえば、以下の内容のカスタム翻訳ファイルがあるとします。

```json title="src/content/i18n/en.json"
{
	"link.astro": "Astro documentation",
	"link.astro.custom": "Astro documentation for {{feature}}"
}
```

最初のUI文字列は、`t()`関数に`'link.astro'`を渡すことでレンダリングできます。

```astro {3}
<!-- src/components/Example.astro -->
<a href="https://docs.astro.build/">
	{Astro.locals.t('link.astro')}
</a>
<!-- レンダリング結果: <a href="...">Astro documentation</a> -->
```

2番目のUI文字列は、`{{feature}}`のプレースホルダーにi18nextの[補間構文](https://www.i18next.com/translation-function/interpolation)を使用しています。`feature`の値は、`t()`の第2引数として渡すオプションオブジェクトで設定する必要があります。

```astro {3}
<!-- src/components/Example.astro -->
<a href="https://docs.astro.build/en/guides/astro-db/">
	{Astro.locals.t('link.astro.custom', { feature: 'Astro DB' })}
</a>
<!-- レンダリング結果: <a href="...">Astro documentation for Astro DB</a> -->
```

補間やフォーマットなどの`t()`関数の使い方について詳しくは、[i18nextのドキュメント](https://www.i18next.com/overview/api#t)を参照してください。

### 高度なAPI

#### `t.all()`

`locals.t.all()`関数は、現在のロケールで利用可能なすべてのUI文字列を含むオブジェクトを返します。

```astro
---
// src/components/Example.astro
const allStrings = Astro.locals.t.all();
//    ^
//    {
//      "skipLink.label": "Skip to content",
//      "search.label": "Search",
//      …
//    }
---
```

#### `t.exists()`

翻訳キーが存在するかどうかを確認するには、`locals.t.exists()`関数の最初の引数に翻訳キーを渡します。特定のロケールに対する翻訳が存在するかどうかを確認する必要がある場合は、オプションの第2引数を渡します。

```astro
---
// src/components/Example.astro
const keyExists = Astro.locals.t.exists('a.key');
//    ^ true
const keyExistsInFrench = Astro.locals.t.exists('other.key', { lngs: ['fr'] });
//    ^ false
---
```

詳しくは、[i18nextドキュメントの`exists()`リファレンス](https://www.i18next.com/overview/api#exists)を参照してください。

#### `t.dir()`

`locals.t.dir()`関数は、現在のロケールまたは指定したロケールのテキスト方向を返します。

```astro
---
// src/components/Example.astro
const currentDirection = Astro.locals.t.dir();
//    ^
//    'ltr'
const arabicDirection = Astro.locals.t.dir('ar');
//    ^
//    'rtl'
---
```

詳しくは、[i18nextドキュメントの`dir()`リファレンス](https://www.i18next.com/overview/api#dir)を参照してください。

## 現在のロケールにアクセスする

`.astro`コンポーネントで現在のロケールを読み取るためには、[`Astro.currentLocale`](https://docs.astro.build/ja/reference/api-reference/#currentlocale)を使用できます。

以下の例では、現在のロケールを読み取り、[`getRelativeLocaleUrl()`](https://docs.astro.build/ja/reference/modules/astro-i18n/#getrelativelocaleurl)ヘルパーと組み合わせて、現在の言語での概要ページへのリンクを生成しています。

```astro
---
// src/components/AboutLink.astro
import { getRelativeLocaleUrl } from 'astro:i18n';
---

<a href={getRelativeLocaleUrl(Astro.currentLocale ?? 'en', 'about')}>About</a>
```


================================================
FILE: docs/src/content/docs/ja/guides/overriding-components.mdx
================================================
---
title: コンポーネントのオーバーライド
description: Starlightの組み込みコンポーネントをオーバーライドして、ドキュメントサイトのUIにカスタム要素を追加する方法を学びます。
---

import { Steps } from '@astrojs/starlight/components';

StarlightのデフォルトのUIと設定オプションは、柔軟に設計されており、さまざまなコンテンツで機能します。Starlightのデフォルトの見た目の大部分は、[CSS](/ja/guides/css-and-tailwind/)と[設定オプション](/ja/guides/customization/)によりカスタマイズできます。

デフォルトの内容に満足できない場合には、デフォルトのコンポーネントを拡張したり、オーバーライドしたり(完全に置き換えたり)するためのカスタムコンポーネントを作成することも可能です。

## いつオーバーライドするか

以下の場合、Starlightのデフォルトコンポーネントをオーバーライドすると便利です。

- [カスタムCSS](/ja/guides/css-and-tailwind/)では不可能な方法で、StarlightのUIの見た目を部分的に変更したい場合。
- StarlightのUIの動作を部分的に変更したい場合。
- Starlightの既存のUIに別のUIを追加したい場合。

## オーバーライドの方法

<Steps>

1. オーバーライドしたいStarlightコンポーネントを選択します。コンポーネントの完全なリストは、[オーバーライドリファレンス](/ja/reference/overrides/)にあります。

   :::tip
   どのコンポーネントをオーバーライドすればいいかわからない場合は、[Starlight Overrides Map](https://starlight-overrides-map.netlify.app/)を使用して、StarlightのUIコンポーネントの名前をインタラクティブに調べることができます。
   :::

   この例では、ページのナビゲーションバーに表示される、Starlightの[`SocialIcons`](/ja/reference/overrides/#socialicons)コンポーネントをオーバーライドします。

2. Starlightのコンポーネントを置き換えるAstroコンポーネントを作成します。この例では、連絡先のリンクをレンダリングします。

   ```astro
   ---
   // src/components/EmailLink.astro

   const email = 'houston@example.com';
   ---

   <a href=`mailto:${email}`>メールしてね</a>
   ```

3. `astro.config.mjs`の[`components`](/ja/reference/configuration/#components)設定オプションで、カスタムコンポーネントを使用するようStarlightに指示します。

   ```js {9-12}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'オーバーライドを設定したドキュメント',
   			components: {
   				// デフォルトの`SocialIcons`コンポーネントをオーバーライドします。
   				SocialIcons: './src/components/EmailLink.astro',
   			},
   		}),
   	],
   });
   ```

</Steps>

## 組み込みコンポーネントを再利用する

StarlightのデフォルトのUIコンポーネントを、自分で作ったものと同じように使うことができます。これにより、Starlightの基本的なUIをデザインとしてすべて保持しながら、そこに別のUIを追加することができます。

以下の例は、デフォルトの`SocialIcons`コンポーネントと一緒に、メールリンクをレンダリングするカスタムコンポーネントです。

```astro {3,7}
---
// src/components/EmailLink.astro
import Default from '@astrojs/starlight/components/SocialIcons.astro';
---

<a href="mailto:houston@example.com">メールしてね</a>
<Default><slot /></Default>
```

カスタムコンポーネント内で組み込みコンポーネントをレンダリングする場合は、デフォルトコンポーネント内に[`<slot />`](https://docs.astro.build/ja/basics/astro-components/#スロット)を追加します。これにより、コンポーネントに子要素が渡された場合、Astroがそれらをどこにレンダリングするかを知ることができます。

[名前付きスロット](https://docs.astro.build/ja/basics/astro-components/#名前付きスロット)を含む[`PageFrame`](/ja/reference/overrides/#pageframe)や[`TwoColumnContent`](/ja/reference/overrides/#twocolumncontent)コンポーネントを再利用する場合は、これらのスロットを[受け渡す](https://docs.astro.build/ja/basics/astro-components/#スロットの受け渡し)必要があります。

以下の例は、受け渡しが必要な`right-sidebar`という名前付きスロットを含む`TwoColumnContent`コンポーネントを再利用するカスタムコンポーネントです。

```astro {8}
---
// src/components/CustomContent.astro
import Default from '@astrojs/starlight/components/TwoColumnContent.astro';
---

<Default>
	<slot />
	<slot name="right-sidebar" slot="right-sidebar" />
</Default>
```

## ページデータを使用する

Starlightコンポーネントをオーバーライドすると、現在のページのすべてのデータを含むグローバルな[`starlightRoute`オブジェクト](/ja/guides/route-data/)にアクセスできます。これらの値を使用して、コンポーネントテンプレートのレンダリング方法を制御することができます。

以下の例では、[`PageTitle`](/ja/reference/overrides/#pagetitle)の代替コンポーネントが、コンテンツのフロントマターに設定された現在のページのタイトルを表示します。

```astro {4} "{title}"
---
// src/components/Title.astro

const { title } = Astro.locals.starlightRoute.entry.data;
---

<h1 id="_top">{title}</h1>

<style>
	h1 {
		font-family: 'Comic Sans';
	}
</style>
```

利用可能なすべてのプロパティについて、詳しくは[ルートデータリファレンス](/ja/reference/route-data/)を参照してください。

### 特定ページのみでのオーバーライド

コンポーネントのオーバーライドはすべてのページに適用されます。ただし、`starlightRoute`の値を使用して条件に応じてレンダリングすることで、カスタムUIを表示するタイミング、StarlightのデフォルトUIを表示するタイミング、あるいはまったく別のものを表示するタイミングを決定することができます。

以下は、Starlightの[`Footer`](/ja/reference/overrides/#footer)をオーバーライドするコンポーネントの例です。ホームページでのみ「Starlightで作成 🌟」と表示し、それ以外のすべてのページではデフォルトのフッターを表示します。

```astro
---
// src/components/ConditionalFooter.astro
import Default from '@astrojs/starlight/components/Footer.astro';

const isHomepage = Astro.locals.starlightRoute.id === '';
---

{
	isHomepage ? (
		<footer>Starlightで作成 🌟</footer>
	) : (
		<Default>
			<slot />
		</Default>
	)
}
```

条件付きレンダリングについて、詳しくは[Astroのテンプレート構文ガイド](https://docs.astro.build/ja/basics/astro-syntax/#動的html)を参照してください。


================================================
FILE: docs/src/content/docs/ja/guides/pages.mdx
================================================
---
title: ページ
description: Starlightでドキュメントサイトのページを作成し管理する方法を学びます。
sidebar:
  order: 1
tableOfContents:
  maxHeadingLevel: 4
---

Starlightは、Markdownのフロントマターにより提供される柔軟なオプションを使用して、コンテンツに基づいてサイトのHTMLページを生成します。さらにStarlightプロジェクトは、[Astroの強力なページ生成ツール](https://docs.astro.build/ja/basics/astro-pages/)に完全にアクセスできます。このガイドでは、Starlightのページ生成の仕組みについて説明します。

## コンテンツページ

### ファイルフォーマット

Starlightは、設定なしでMarkdownとMDXによってコンテンツを作成できます。Markdocのサポートを追加するには、[Markdocガイド](/ja/guides/authoring-content/#markdoc)に従ってください。

### ページの追加

`.md`または`.mdx`ファイルを`src/content/docs/`に作成することで、サイトに新しいページを追加できます。サブフォルダを使用してファイルを整理し、複数のパスセグメントを作成できます。

たとえば次のファイル構造は、`example.com/hello-world`と`example.com/reference/faq`にページを生成します。

import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src/
  - content/
    - docs/
      - hello-world.md
      - reference/
        - faq.md

</FileTree>

### 型安全なフロントマター

すべてのStarlightページは、ページの表示方法を制御するためのカスタマイズ可能な[共通のフロントマタープロパティ](/ja/reference/frontmatter/)を共有しています。

```md
---
title: こんにちは、世界!
description: これは私のStarlight製サイトのページです
---
```

何か重要なことを忘れてしまっていても、Starlightがあなたに教えてくれるでしょう。

## カスタムページ

発展的なユースケースとしては、`src/pages/`ディレクトリを作成しておこなうカスタムページの追加があります。`src/pages/`ディレクトリは[Astroのファイルベースルーティング](https://docs.astro.build/ja/basics/astro-pages/#ファイルベースルーティング)を使用しており、他のページフォーマットに加えて`.astro`ファイルをサポートしています。これは、完全にカスタムのレイアウトでページを作成したり、異なるデータソースからページを生成する必要がある場合に役立ちます。

たとえば以下のプロジェクトは、`src/content/docs/`のMarkdownコンテンツと、`src/pages/`のAstroとHTMLルートを混在させています。

<FileTree>

- src/
  - content/
    - docs/
      - hello-world.md
  - pages/
    - custom.astro
    - archived.html

</FileTree>

詳しくは[Astroドキュメントの「ページ」ガイド](https://docs.astro.build/ja/basics/astro-pages/)を参照してください。

### カスタムページでStarlightのデザインを使用する

カスタムページでStarlightのデザインを使用するには、ページコンテンツを[`<StarlightPage>`コンポーネント](#starlightpageコンポーネント)でラップします。これは、コンテンツを動的に生成したいものの、Starlightのデザインも使用したいような場合に役立ちます。

StarlightのMarkdownアンカーリンクのスタイルと同じアンカーリンクを見出しに追加するには、カスタムページで[`<AnchorHeading>`コンポーネント](#anchorheadingコンポーネント)を使用します。

```astro
---
// src/pages/custom-page/example.astro
import StarlightPage from '@astrojs/starlight/components/StarlightPage.astro';
import AnchorHeading from '@astrojs/starlight/components/AnchorHeading.astro';
import CustomComponent from './CustomComponent.astro';
---

<StarlightPage frontmatter={{ title: '私のカスタムページ' }}>
	<p>これはカスタムコンポーネントを用いたカスタムページです:</p>
	<CustomComponent />

	<AnchorHeading level="2" id="learn-more">詳しく学ぶ</AnchorHeading>
	<p>
		<a href="https://starlight.astro.build/">
			Starlightのドキュメントで詳しく読む
		</a>
	</p>
</StarlightPage>
```

#### `<StarlightPage>`コンポーネント

`<StarlightPage />`コンポーネントは、Starlightのレイアウトとスタイルを使用してページ全体のコンテンツをレンダリングします。

```astro
---
import StarlightPage from '@astrojs/starlight/components/StarlightPage.astro';
---

<StarlightPage frontmatter={{ title: '私のカスタムページ' }}>
	<!-- カスタムページのコンテンツ -->
</StarlightPage>
```

`<StarlightPage />`コンポーネントは以下のpropsを受け付けます。

##### `frontmatter`

**必須**  
**type:** `StarlightPageFrontmatter`

ページの[フロントマタープロパティ](/ja/reference/frontmatter/)を設定します。これは、Markdownページのフロントマターと同様です。[`title`](/ja/reference/frontmatter/#title必須)プロパティは必須ですが、その他のプロパティは任意です。

以下のプロパティはMarkdownのフロントマターと異なります。

- [`slug`](/ja/reference/frontmatter/#slug)プロパティはサポートされておらず、カスタムページのURLに基づいて自動的に設定されます。
- [`editUrl`](/ja/reference/frontmatter/#editurl)オプションは、編集リンクを表示するためのURLが必要です。
- [自動生成されるリンクグループ](/ja/reference/configuration/#sidebar)にページを表示する方法をカスタマイズするための[`sidebar`](/ja/reference/frontmatter/#sidebar)フロントマタープロパティは利用できません。`<StarlightPage />`コンポーネントを使用するページはコレクションの一部ではなく、自動生成されるサイドバーグループには追加できません。
- [`draft`](/ja/reference/frontmatter/#draft)オプションは、ページがドラフトであることを[通知](/ja/reference/overrides/#draftcontentnotice)するだけで、自動的に本番ビルドから除外されるわけではありません。

##### `sidebar`

**type:** [`SidebarItem[]`](/ja/reference/configuration/#sidebaritem)  
**default:** [グローバルな`sidebar`設定値](/ja/reference/configuration/#sidebar)に基づき生成されるサイドバー

ページにカスタムのサイトナビゲーションサイドバーを設定します。未設定の場合、ページはデフォルトのグローバルサイドバーを使用します。

たとえば以下のページは、ホームページへのリンクとその他のカスタムページへのリンクグループにより、デフォルトのサイドバーをオーバーライドします。

```astro {3-13}
<StarlightPage
	frontmatter={{ title: 'オリオン座' }}
	sidebar={[
		{ label: 'ホーム', link: '/' },
		{
			label: '星座',
			items: [
				{ label: 'アンドロメダ座', link: '/andromeda/' },
				{ label: 'オリオン座', link: '/orion/' },
				{ label: 'こぐま座', link: '/ursa-minor/', badge: 'スタブ' },
			],
		},
	]}
>
	何らかのコンテンツ。
</StarlightPage>
```

サイドバーをカスタマイズするための利用可能なオプションについては、[「サイドバーのナビゲーション」](/ja/guides/sidebar/)ガイドを参照してください。

##### `hasSidebar`

**type:** `boolean`  
**default:** [`frontmatter.template`](/ja/reference/frontmatter/#template)が`'splash'`の場合は`false`、それ以外の場合は`true`

ページにサイドバーを表示するかどうかを制御します。

##### `headings`

**type:** `{ depth: number; slug: string; text: string }[]`  
**default:** `[]`

ページのすべての見出しの配列を指定します。指定された場合、Starlightはこれらの見出しからページの目次を生成します。

##### `dir`

**type:** `'ltr' | 'rtl'`  
**default:** 現在のロケールの記述方向

ページのコンテンツを記述する方向を設定します。

##### `lang`

**type:** `string`  
**default:** 現在のロケールの言語

`en`や`zh-CN`、`pt-BR`など、ページのBCP-47言語タグを設定します。

##### `isFallback`

**type:** `boolean`  
**default:** `false`

現在の言語に対する翻訳がない結果、ページが[フォールバックコンテンツ](/ja/guides/i18n/#フォールバックコンテンツ)を使用しているかどうかを示します。

#### `<AnchorHeading>`コンポーネント

`<AnchorHeading />`コンポーネントは、StarlightのMarkdownスタイルと同じクリック可能なアンカーリンク付きのHTML見出し要素をレンダリングします。

```astro
---
import AnchorHeading from '@astrojs/starlight/components/AnchorHeading.astro';
---

<AnchorHeading level="2" id="sub-heading">小見出し</AnchorHeading>
```

このコンポーネントは、以下のpropsに加えて、任意の有効な[グローバルHTML属性](https://developer.mozilla.org/ja/docs/Web/HTML/Global_attributes)を受け付けます。

##### `level`

**必須**  
**type:** `1 | 2 | 3 | 4 | 5 | 6`

レンダリングする見出しレベルを指定します。たとえば、`level="1"`は`<h1>`要素をレンダリングします。

##### `id`

**必須**  
**type:** `string`

この見出しのユニークなIDを指定します。レンダリングされる見出しの`id`属性として使用され、アンカーアイコンはこのIDにリンクします。


================================================
FILE: docs/src/content/docs/ja/guides/project-structure.mdx
================================================
---
title: ディレクトリ構成
description: Starlightプロジェクトでファイルをどのように配置するかについて学びます。
---

このガイドでは、Starlightプロジェクトの構成と、プロジェクト内のさまざまなファイルの役割について説明します。

Starlightプロジェクトは、基本的に他のAstroプロジェクトと同じファイル・ディレクトリ構成に従います。詳細については、[Astroのディレクトリ構成のドキュメント](https://docs.astro.build/ja/basics/project-structure/)を参照してください。

## ファイルとディレクトリ

- `astro.config.mjs` — Astroの設定ファイルで、ここにStarlightのインテグレーションや設定を記述します。
- `src/content.config.ts` — コンテンツコレクションの設定ファイルで、Starlightのフロントマタースキーマをプロジェクトに追加します。
- `src/content/docs/` — コンテンツのファイルが置かれます。Starlightは、このディレクトリ内の各`.md`、`.mdx`、`.mdoc`ファイルを、サイトのページへと変換します。
- `src/content/i18n/`(任意) — [国際化](/ja/guides/i18n/)をサポートするための翻訳データが置かれます。
- `src/` — プロジェクトの他のソースコードやファイル(コンポーネント、スタイル、画像など)が置かれます。
- `public/` — Astroによって処理されない静的アセット(フォント、ファビコン、PDFなど)が置かれます。

## プロジェクトの中身の例

Starlightプロジェクトのディレクトリは、次のようになります。

import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- public/
  - favicon.svg
- src/
  - assets/
    - logo.svg
    - screenshot.jpg
  - components/
    - CustomButton.astro
    - InteractiveWidget.jsx
  - content/
    - docs/
      - guides/
        - 01-getting-started.md
        - 02-advanced.md
      - index.mdx
  - content.config.ts
- astro.config.mjs
- package.json
- tsconfig.json

</FileTree>


================================================
FILE: docs/src/content/docs/ja/guides/route-data.mdx
================================================
---
title: ルートデータ
description: Starlight のページデータモデルがどのようにページをレンダリングするか、またそのカスタマイズ方法について学びましょう。
---

import { Steps } from '@astrojs/starlight/components';

Starlight がドキュメント内のページをレンダリングするとき、まずそのページ上の内容を表すルートデータオブジェクトを作成します。  
このガイドでは、ルートデータがどのように生成され、どのように使用されるか、また Starlight の既定の動作を変更するためにカスタマイズする方法を説明します。

利用可能なすべてのプロパティ一覧については、[「ルートデータリファレンス」](/ja/reference/route-data/) を参照してください。

## ルートデータとは?

Starlight のルートデータは、1 ページをレンダリングするために必要なすべての情報を含むオブジェクトです。  
これは、現在のページに関する情報に加え、Starlight の設定から生成されるデータも含みます。

## ルートデータの使用方法

Starlight のすべてのコンポーネントは、ルートデータを使用して各ページで何をレンダリングするかを決定します。  
たとえば、[`siteTitle`](/ja/reference/route-data/#sitetitle) 文字列はサイトタイトルの表示に使用され、[`sidebar`](/ja/reference/route-data/#sidebar) 配列はグローバルサイドバーのナビゲーションをレンダリングするために使用されます。

このデータは Astro コンポーネント内で `Astro.locals.starlightRoute` グローバルからアクセスできます。

```astro title="example.astro" {2}
---
const { siteTitle } = Astro.locals.starlightRoute;
---

<p>このサイトのタイトルは「{siteTitle}」です。</p>
```

これは、表示内容をカスタマイズするために [コンポーネントのオーバーライド](/ja/guides/overriding-components/) を作成するときなどに便利です。

## ルートデータのカスタマイズ

Starlight のルートデータは、設定なしでそのまま動作します。  
しかし、高度なユースケースでは、サイトの表示方法を変更するために一部またはすべてのページでルートデータをカスタマイズしたい場合があります。

これは [コンポーネントのオーバーライド](/ja/guides/overriding-components/) と似た概念ですが、Starlight がデータを「どのように」レンダリングするかを変更する代わりに、Starlight が「レンダリングするデータ自体」を変更します。

### ルートデータをカスタマイズすべき場合

既存の設定オプションでは実現できない形で、Starlight がデータを処理する方法を変更したい場合にルートデータのカスタマイズが役立ちます。

たとえば、サイドバー項目をフィルタリングしたり、特定のページのタイトルをカスタマイズしたりできます。  
このような変更は、Starlight の既定コンポーネントを変更することなく、これらのコンポーネントに渡すデータを修正するだけで実現できます。

### ルートデータをカスタマイズする方法

ルートデータは特別な形式の「ミドルウェア」を使ってカスタマイズできます。  
これは Starlight がページをレンダリングするたびに呼び出され、ルートデータオブジェクト内の値を変更できる関数です。

<Steps>

1. Starlight の `defineRouteMiddleware()` ユーティリティを使って、`onRequest` 関数をエクスポートする新しいファイルを作成します。

   ```ts
   // src/routeData.ts
   import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

   export const onRequest = defineRouteMiddleware(() => {});
   ```

2. `astro.config.mjs` で、ルートデータミドルウェアファイルの場所を Starlight に指定します。

   ```js ins={9}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'カスタムルートデータのページ',
   			routeMiddleware: './src/routeData.ts',
   		}),
   	],
   });
   ```

3. `onRequest` 関数を更新してルートデータを変更します。

   ミドルウェアが最初に受け取る引数は [Astro の `context` オブジェクト](https://docs.astro.build/ja/reference/api-reference/) です。  
   これには、現在のページレンダリングに関するすべての情報(現在の URL や `locals` など)が含まれています。

   次の例では、すべてのページタイトルの末尾に感嘆符を追加して、ドキュメントを少し楽しくします。

   ```ts
   // src/routeData.ts
   import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

   export const onRequest = defineRouteMiddleware((context) => {
   	// このページのコンテンツコレクションエントリを取得
   	const { entry } = context.locals.starlightRoute;
   	// タイトルの末尾に感嘆符を追加
   	entry.data.title = entry.data.title + '!';
   });
   ```

</Steps>

#### 複数のルートミドルウェア

Starlight は複数のミドルウェアもサポートしています。  
複数のハンドラーを追加する場合は、`routeMiddleware` にパスの配列を設定します。

```js {9}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: '複数のミドルウェアのページ',
			routeMiddleware: ['./src/middleware-one.ts', './src/middleware-two.ts'],
		}),
	],
});
```

#### 後続のルートミドルウェアを待機する

スタック内の後続ミドルウェアが実行されるのを待ってからコードを実行したい場合、ミドルウェア関数の第 2 引数として渡される `next()` コールバックを `await` することができます。  
これは、たとえばプラグインのミドルウェアが実行された後に変更を加えたい場合に便利です。

```ts "next" "await next();"
// src/routeData.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

export const onRequest = defineRouteMiddleware(async (context, next) => {
	// 後続のミドルウェアが実行されるのを待つ
	await next();
	// ルートデータを変更
	const { entry } = context.locals.starlightRoute;
	entry.data.title = entry.data.title + '!';
});
```


================================================
FILE: docs/src/content/docs/ja/guides/sidebar.mdx
================================================
---
title: サイドバーのナビゲーション
description: Starlightサイトのサイドバーのナビゲーションリンクを設定・カスタマイズする方法を学びます。
---

import { FileTree } from '@astrojs/starlight/components';
import SidebarPreview from '~/components/sidebar-preview.astro';

サイドバーはユーザーがサイト内を移動するための主要な方法の1つであるため、サイドバーを整理することは良いドキュメントの鍵となります。Starlightでは、サイドバーのレイアウトとコンテンツをカスタマイズするためのオプション一式を提供しています。

## デフォルトのサイドバー

Starlightはデフォルトで、ドキュメントのファイルシステム構造に基づいてサイドバーを自動的に生成します。その際、各ファイルの`title`プロパティをサイドバーのエントリとして使用します。

たとえば以下のファイル構造があるとします。

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - andromeda.md
        - orion.md
      - stars/
        - betelgeuse.md

</FileTree>

すると以下のサイドバーが自動的に生成されます。

<SidebarPreview
	config={[
		{
			label: '星座',
			items: [
				{ label: 'アンドロメダ座', link: '' },
				{ label: 'オリオン座', link: '' },
			],
		},
		{
			label: '星',
			items: [{ label: 'ベテルギウス', link: '' }],
		},
	]}
/>

自動生成されるサイドバーについては、[自動生成されるグループ](#自動生成されるグループ)のセクションで詳しく説明します。

## リンクとリンクグループを追加する

サイドバーのリンクと(折りたたみ可能なヘッダー内の)リンクグループを設定するには、`astro.config.mjs`で[`starlight.sidebar`](/ja/reference/configuration/#sidebar)プロパティを使用します。

リンクとグループを組み合わせることで、さまざまなサイドバーレイアウトを作成できます。

### 内部リンク

`slug`プロパティをもつオブジェクトを使用して、`src/content/docs/`内のページへのリンクを追加します。デフォルトでは、リンク先ページのタイトルがラベルとして使用されます。

たとえば、以下の設定があるとします。

```js "slug:"
starlight({
	sidebar: [
		{ slug: 'constellations/andromeda' },
		{ slug: 'constellations/orion' },
	],
});
```

そして以下のファイル構造であるとします。

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - andromeda.md
        - orion.md

</FileTree>

すると以下のサイドバーが生成されます。

<SidebarPreview
	config={[
		{ label: 'アンドロメダ座', link: '' },
		{ label: 'オリオン座', link: '' },
	]}
/>

リンク先ページのフロントマターから推測される値をオーバーライドするには、`label`、[`translations`](#国際化)、[`attrs`](#カスタムhtml属性)プロパティを追加します。

ページのフロントマターからサイドバーの表示を制御する方法について、詳しくは[「自動生成されるリンクのカスタマイズ」](#自動生成されるリンクをフロントマターでカスタマイズする)を参照してください。

#### 内部リンクの省略記法

内部リンクは、ページのスラグを文字列として渡すだけの省略記法でも指定できます。

たとえば、以下の設定は上記の`slug`を使用した設定と同等です。

```js "slug:"
starlight({
	sidebar: ['constellations/andromeda', 'constellations/orion'],
});
```

### その他のリンク

`label`と`link`プロパティをもつオブジェクトを使用して、外部ページやドキュメント以外のページへのリンクを追加します。

```js "label:" "link:"
starlight({
	sidebar: [
		// サイト内のドキュメント以外のページへのリンク。
		{ label: '流星商店', link: '/shop/' },
		// NASAのウェブサイトへの外部リンク。
		{ label: 'NASA', link: 'https://www.nasa.gov/' },
	],
});
```

上の設定により、以下のサイドバーが生成されます。

<SidebarPreview
	config={[
		{ label: '流星商店', link: '' },
		{ label: 'NASA', link: 'https://www.nasa.gov/' },
	]}
/>

### グループ

折りたたみ可能な見出しの下に関連するリンクをグループ化することで、サイドバーに構造を追加できます。グループには、リンクと他のサブグループを含められます。

`label`と`items`プロパティをもつオブジェクトを使用して、グループを追加します。`label`はグループの見出しとして使用されます。`items`配列にリンクまたはサブグループを追加します。

```js /^\s*(label:|items:)/
starlight({
	sidebar: [
		// 「星座」というラベルのリンクグループ。
		{
			label: '星座',
			items: [
				'constellations/carina',
				'constellations/centaurus',
				// 季節の星座の入れ子になったリンクグループ。
				{
					label: '季節の星座',
					items: [
						'constellations/andromeda',
						'constellations/orion',
						'constellations/ursa-minor',
					],
				},
			],
		},
	],
});
```

上の設定により、以下のサイドバーが生成されます。

<SidebarPreview
	config={[
		{
			label: '星座',
			items: [
				{ label: 'りゅうこつ座', link: '' },
				{ label: 'ケンタウルス座', link: '' },
				{
					label: '季節の星座',
					items: [
						{ label: 'アンドロメダ座', link: '' },
						{ label: 'オリオン座', link: '' },
						{ label: 'こぐま座', link: '' },
					],
				},
			],
		},
	]}
/>

### 自動生成されるグループ

Starlightはドキュメントのディレクトリに基づいて、サイドバーのグループを自動的に生成できます。これはグループ内のサイドバー項目を手動で入力したくない場合に便利です。

デフォルトでは、ページはファイルの[`slug`](/ja/reference/route-data/#slug)に従ってアルファベット順に並べ替えられます。

`label`と`autogenerate`プロパティをもつオブジェクトを使用して、自動生成されるグループを追加します。`autogenerate`の設定には、サイドバーのエントリに使用する`directory`を指定する必要があります。たとえば、以下のように設定したとします。

```js "label:" "autogenerate:"
starlight({
	sidebar: [
		{
			label: '星座',
			// constellationsディレクトリのリンクグループを自動生成します。
			autogenerate: { directory: 'constellations' },
		},
	],
});
```

そして以下のファイル構造があるとします。

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - carina.md
        - centaurus.md
        - seasonal/
          - andromeda.md

</FileTree>

すると以下のサイドバーが生成されます。

<SidebarPreview
	config={[
		{
			label: '星座',
			items: [
				{ label: 'りゅうこつ座', link: '' },
				{ label: 'ケンタウルス座', link: '' },
				{
					label: 'seasonal',
					items: [{ label: 'アンドロメダ座', link: '' }],
				},
			],
		},
	]}
/>

## 自動生成されるリンクをフロントマターでカスタマイズする

個々のページで[`sidebar`フロントマターフィールド](/ja/reference/frontmatter/#sidebar)を使用して、自動生成されるリンクをカスタマイズできます。

フロントマターのサイドバーオプションにより、[カスタムラベル](/ja/reference/frontmatter/#label)の設定、[カスタム属性](/ja/reference/frontmatter/#attrs)の使用、リンクへの[バッジ](/ja/reference/frontmatter/#badge)の追加、サイドバーのリンクの[非表示](/ja/reference/frontmatter/#hidden)、[独自のソート順](/ja/reference/frontmatter/#order)の定義が可能です。

```md "sidebar:"
---
title: 私のページ
sidebar:
  # このリンクのカスタムラベルを設定します
  label: カスタムサイドバーラベル
  # このリンクの順番をカスタマイズします(数字が小さいほど上に表示されます)
  order: 2
  # このリンクにバッジを追加します
  badge:
    text: 新規
    variant: tip
---
```

上記のフロントマターを設定したページと一緒に自動生成されるグループは、以下のサイドバーを生成します。

<SidebarPreview
	config={[
		{
			label: 'ガイド',
			items: [
				{ label: 'ページ', link: '' },
				{
					label: 'カスタムサイドバーラベル',
					link: '',
					badge: { text: '新規', variant: 'tip' },
				},
				{ label: '別のページ', link: '' },
			],
		},
	]}
/>

:::note
`sidebar`フロントマターの設定は、自動生成されるグループ内のリンクと`slug`プロパティで定義されたドキュメントリンクにのみ使用されます。`link`プロパティで定義されたリンクには適用されません。
:::

## バッジ

リンク、グループ、自動生成されるグループには、ラベルの横にバッジを表示するための`badge`プロパティも含められます。

```js {9,16}
starlight({
	sidebar: [
		{
			label: '星',
			items: [
				// 「超巨星」バッジ付きのリンク。
				{
					slug: 'stars/persei',
					badge: '超巨星',
				},
			],
		},
		// 「要更新」バッジ付きの自動生成されるグループ。
		{
			label: '衛星',
			badge: '要更新',
			autogenerate: { directory: 'moons' },
		},
	],
});
```

上の設定により、以下のサイドバーが生成されます。

<SidebarPreview
	config={[
		{
			label: '星',
			items: [
				{
					label: 'ペルセウス座',
					link: '',
					badge: { text: '超巨星', variant: 'default' },
				},
			],
		},
		{
			label: '衛星',
			badge: { text: '要更新', variant: 'default' },
			items: [
				{
					label: 'イオ',
					link: '',
				},
				{
					label: 'エウロパ',
					link: '',
				},
				{
					label: 'ガニメデ',
					link: '',
				},
			],
		},
	]}
/>

### バッジのバリアントとカスタムスタイル

`text`と`variant`、`class`プロパティをもつオブジェクトを使用して、バッジのスタイルをカスタマイズできます。

`text`は表示するコンテンツ、たとえば「新規」などを表わします。デフォルトでは、バッジにはサイトのアクセントカラーが使用されます。組み込みのバッジスタイルを使用するには、`variant`プロパティを`note`、`tip`、`danger`、`caution`、`success`のいずれかに設定します。

また、`class`プロパティにCSSクラス名を設定することで、カスタムバッジスタイルを作成することも可能です。

```js {9}
starlight({
	sidebar: [
		{
			label: '星',
			items: [
				// 「準備中」バッジ付きのリンク。
				{
					slug: 'stars/sirius',
					badge: { text: '準備中', variant: 'caution' },
				},
			],
		},
	],
});
```

上の設定により、以下のサイドバーが生成されます。

<SidebarPreview
	config={[
		{
			label: '星',
			items: [
				{
					label: 'シリウス',
					link: '',
					badge: { text: '準備中', variant: 'caution' },
				},
			],
		},
	]}
/>

詳しくは、[バッジの使用とカスタマイズ](/ja/components/badges/#使用方法)を参照してください。

## カスタムHTML属性

リンク要素にカスタムのHTML属性を追加するには、`attrs`プロパティを使用します。

以下の例では、リンクが新しいタブで開かれるよう、`attrs`を使用して`target="_blank"`属性を追加しています。また、リンクのラベルにカスタムの`style`属性を適用して斜体にします。

```js {10}
starlight({
	sidebar: [
		{
			label: 'リソース',
			items: [
				// 新しいタブで開かれる、NASAのウェブサイトへの外部リンク。
				{
					label: 'NASA',
					link: 'https://www.nasa.gov/',
					attrs: { target: '_blank', style: 'font-style: italic' },
				},
			],
		},
	],
});
```

上の設定により、以下のサイドバーが生成されます。

<SidebarPreview
	config={[
		{
			label: 'リソース',
			items: [
				{
					label: 'NASA',
					link: 'https://www.nasa.gov/',
					attrs: {
						target: '_blank',
						style: 'font-style: italic',
					},
				},
			],
		},
	]}
/>

### 自動生成されるリンクのカスタムHTML属性

`autogenerate`設定で`attrs`プロパティを定義することで、[自動生成されるグループ](#自動生成されるグループ)内のすべてのリンクのHTML属性をカスタマイズできます。個々のページでは[`sidebar.attrs`フロントマターフィールド](/ja/reference/frontmatter/#attrs)を使用してカスタム属性を指定でき、これは`autogenerate.attrs`設定とマージされます。

たとえば、以下の設定があるとします。

```js {9}
starlight({
	sidebar: [
		{
			label: '星座',
			autogenerate: {
				// 'constellations'ディレクトリのリンクグループを自動生成します。
				directory: 'constellations',
				// このグループ内のすべてのリンクラベルを斜体にします。
				attrs: { style: 'font-style: italic' },
			},
		},
	],
});
```

そして以下のファイル構造があるとします。

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - carina.md
        - centaurus.md
        - seasonal/
          - andromeda.md

</FileTree>

すると、自動生成されるすべてのリンクが斜体になった以下のサイドバーが生成されます。

<SidebarPreview
	config={[
		{
			label: '星座',
			items: [
				{
					label: 'りゅうこつ座',
					link: '',
					attrs: { style: 'font-style: italic' },
				},
				{
					label: 'ケンタウルス座',
					link: '',
					attrs: { style: 'font-style: italic' },
				},
				{
					label: 'seasonal',
					items: [
						{
							label: 'アンドロメダ座',
							link: '',
							attrs: { style: 'font-style: italic' },
						},
					],
				},
			],
		},
	]}
/>

## 国際化

リンクやグループのラベルをサポート対象の言語向けに翻訳するには、リンクやグループのエントリに`translations`プロパティを使用します。[BCP-47](https://www.w3.org/International/questions/qa-choosing-language-tags)の言語タグ、たとえば`"en"`、`"ar"`、`"zh-CN"`をキーとして、翻訳されたラベルを値として指定します。`label`プロパティは、デフォルトのロケールと、翻訳がない言語に対して使用されます。

```js {5-7,11-13,18-20}
starlight({
	sidebar: [
		{
			label: '星座',
			translations: {
				'pt-BR': 'Constelações',
			},
			items: [
				{
					label: 'アンドロメダ座',
					translations: {
						'pt-BR': 'Andrômeda',
					},
					slug: 'constellations/andromeda',
				},
				{
					label: 'さそり座',
					translations: {
						'pt-BR': 'Escorpião',
					},
					slug: 'constellations/scorpius',
				},
			],
		},
	],
});
```

ブラジルポルトガル語でドキュメントを閲覧すると、以下のサイドバーが生成されます。

<SidebarPreview
	config={[
		{
			label: 'Constelação',
			items: [
				{ label: 'Andrômeda', link: '' },
				{ label: 'Escorpião', link: '' },
			],
		},
	]}
/>

### 内部リンクの国際化

[内部リンク](#内部リンク)は、デフォルトでコンテンツのフロントマターの翻訳されたページタイトルを自動的に使用します。

```js {9-10}
starlight({
	sidebar: [
		{
			label: '星座',
			translations: {
				'pt-BR': 'Constelações',
			},
			items: [
				{ slug: 'constellations/andromeda' },
				{ slug: 'constellations/scorpius' },
			],
		},
	],
});
```

ブラジルポルトガル語でドキュメントを閲覧すると、以下のサイドバーが生成されます。

<SidebarPreview
	config={[
		{
			label: 'Constelações',
			items: [
				{ label: 'Andrômeda', link: '' },
				{ label: 'Escorpião', link: '' },
			],
		},
	]}
/>

多言語サイトでは、`slug`の値にURLの言語部分は含まれません。たとえば、`en/intro`と`pt-br/intro`にページがある場合、サイドバーを設定する際のスラグは`intro`となります。

### バッジの国際化

[バッジ](#バッジ)の`text`プロパティは、文字列か、多言語サイトの場合はロケールごとの値をもつオブジェクトを指定できます。オブジェクト形式を使用する場合、キーは[BCP-47](https://www.w3.org/International/questions/qa-choosing-language-tags)タグ(`en`、`ar`、`zh-CN`など)である必要があります。

```js {11-16}
starlight({
	sidebar: [
		{
			label: '星座',
			translations: {
				'pt-BR': 'Constelações',
			},
			items: [
				{
					slug: 'constellations/andromeda',
					badge: {
						text: {
							ja: '新規',
							'pt-BR': 'Novo',
						},
					},
				},
			],
		},
	],
});
```

ブラジルポルトガル語でドキュメントを閲覧すると、以下のサイドバーが生成されます。

<SidebarPreview
	config={[
		{
			label: 'Constelações',
			items: [
				{
					label: 'Andrômeda',
					link: '',
					badge: { text: 'Novo', variant: 'default' },
				},
			],
		},
	]}
/>

## グループを折りたたむ

`collapsed`プロパティを`true`に設定することで、リンクのグループをデフォルトで折りたためます。

```js {5-6}
starlight({
	sidebar: [
		{
			label: '星座',
			// デフォルトでグループを折りたたみます。
			collapsed: true,
			items: ['constellations/andromeda', 'constellations/orion'],
		},
	],
});
```

上の設定により、以下のサイドバーが生成されます。

<SidebarPreview
	config={[
		{
			label: '星座',
			collapsed: true,
			items: [
				{ label: 'アンドロメダ座', link: '' },
				{ label: 'オリオン座', link: '' },
			],
		},
	]}
/>

[自動生成されるグループ](#自動生成されるグループ)は、親グループの`collapsed`値に従います。

```js {5-6}
starlight({
	sidebar: [
		{
			label: 'Constellations',
			// デフォルトでグループと自動生成されるサブグループを折りたたみます。
			collapsed: true,
			autogenerate: { directory: 'constellations' },
		},
	],
});
```

上の設定により、以下のサイドバーが生成されます。

<SidebarPreview
	config={[
		{
			label: '星座',
			collapsed: true,
			items: [
				{ label: 'りゅうこつ座', link: '' },
				{ label: 'ケンタウルス座', link: '' },
				{
					label: 'seasonal',
					collapsed: true,
					items: [{ label: 'アンドロメダ座', link: '' }],
				},
			],
		},
	]}
/>

この動作は、`autogenerate.collapsed`プロパティを定義することで上書きできます。

```js {5-7} "collapsed: true"
starlight({
	sidebar: [
		{
			label: '星座',
			// 「星座」グループは折りたたみませんが、自動生成されるサブグループは折りたたみます。
			collapsed: false,
			autogenerate: { directory: 'constellations', collapsed: true },
		},
	],
});
```

上の設定により、以下のサイドバーが生成されます。

<SidebarPreview
	config={[
		{
			label: '星座',
			items: [
				{ label: 'りゅうこつ座', link: '' },
				{ label: 'ケンタウルス座', link: '' },
				{
					label: 'seasonal',
					collapsed: true,
					items: [{ label: 'アンドロメダ座', link: '' }],
				},
			],
		},
	]}
/>


================================================
FILE: docs/src/content/docs/ja/guides/site-search.mdx
================================================
---
title: サイト内検索
description: Starlight組み込みのサイト内検索機能と、そのカスタマイズ方法について学びます。
tableOfContents:
  maxHeadingLevel: 4
---

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

Starlightサイトには、デフォルトで[Pagefind](https://pagefind.app/)による全文検索機能が組み込まれています。Pagefindは、静的サイト向けの高速で通信量が少ない検索ツールです。

検索機能を有効にするための設定は必要ありません。サイトをビルドしてデプロイすれば、サイトヘッダーの検索バーを使ってコンテンツを検索できます。

## 検索結果からコンテンツを隠す

### ページを除外する

検索インデックスからページを除外するには、ページのフロントマターに[`pagefind: false`](/ja/reference/frontmatter/#pagefind)を追加します。

```md title="src/content/docs/not-indexed.md" ins={3}
---
title: 検索結果から隠したいコンテンツ
pagefind: false
---
```

### ページの一部を除外する

Pagefindは、[`data-pagefind-ignore`](https://pagefind.app/docs/indexing/#removing-individual-elements-from-the-index)属性をもつ要素内のコンテンツを無視します。

以下の例では、最初の段落は検索結果に表示されますが、`<div>`の中身は表示されません。

```md title="src/content/docs/partially-indexed.md" ins="data-pagefind-ignore"
---
title: 部分的にインデックスされるページ
---

このテキストは検索で見つかります。

<div data-pagefind-ignore>

このテキストは検索結果から隠されます。

</div>
```

## その他の検索プロバイダ

### Algolia DocSearch

[AlgoliaのDocSearchプログラム](https://docsearch.algolia.com/)にアクセスでき、Pagefindの代わりにそれを使いたい場合は、公式のStarlight DocSearchプラグインを使うことができます。

<Steps>

1. `@astrojs/starlight-docsearch`をインストールします。

   <Tabs syncKey="pkg">

   <TabItem label="npm">

   ```sh
   npm install @astrojs/starlight-docsearch
   ```

   </TabItem>

   <TabItem label="pnpm">

   ```sh
   pnpm add @astrojs/starlight-docsearch
   ```

   </TabItem>

   <TabItem label="Yarn">

   ```sh
   yarn add @astrojs/starlight-docsearch
   ```

   </TabItem>

   </Tabs>

2. `astro.config.mjs`でStarlightの[`plugins`](/ja/reference/configuration/#plugins)設定にDocSearchを追加し、Algoliaの`appId`、`apiKey`、`indexName`を渡します。

   ```js ins={4,10-16}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';
   import starlightDocSearch from '@astrojs/starlight-docsearch';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'DocSearchを使ったサイト',
   			plugins: [
   				starlightDocSearch({
   					appId: 'YOUR_APP_ID',
   					apiKey: 'YOUR_SEARCH_API_KEY',
   					indexName: 'YOUR_INDEX_NAME',
   				}),
   			],
   		}),
   	],
   });
   ```

</Steps>

このように設定を更新すると、サイトの検索バーはデフォルトの検索モーダルではなく、Algoliaのモーダルを開きます。

#### DocSearchの設定

Starlight DocSearchプラグインでは、以下のインラインオプションによりDocSearchコンポーネントをカスタマイズできます。

- `maxResultsPerGroup`: 各検索グループに表示される結果の最大数を制限します。デフォルトは`5`です。
- `disableUserPersonalization`: DocSearchがユーザーの最近の検索やお気に入りをローカルストレージに保存しないようにします。デフォルトは`false`です。
- `insights`: Algolia Insightsプラグインを有効にし、DocSearchインデックスに検索イベントを送信します。デフォルトは`false`です。
- `searchParameters`: [Algoliaの検索パラメータ](https://www.algolia.com/doc/api-reference/search-api-parameters/)をカスタマイズするオブジェクトです。

##### その他のDocSearchオプション

`transformItems()`や`resultsFooterComponent()`などの関数オプションをDocSearchコンポーネントに渡すには、別の設定ファイルが必要です。

<Steps>

1. DocSearchの設定をエクスポートするTypeScriptファイルを作成します。

   ```ts
   // src/config/docsearch.ts
   import type { DocSearchClientOptions } from '@astrojs/starlight-docsearch';

   export default {
   	appId: 'YOUR_APP_ID',
   	apiKey: 'YOUR_SEARCH_API_KEY',
   	indexName: 'YOUR_INDEX_NAME',
   	getMissingResultsUrl({ query }) {
   		return `https://github.com/algolia/docsearch/issues/new?title=${query}`;
   	},
   	// ...
   } satisfies DocSearchClientOptions;
   ```

2. `astro.config.mjs`で、Starlight DocSearchプラグインに設定ファイルのパスを渡します。

   ```js {11-13}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';
   import starlightDocSearch from '@astrojs/starlight-docsearch';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'DocSearchを使ったサイト',
   			plugins: [
   				starlightDocSearch({
   					clientOptionsModule: './src/config/docsearch.ts',
   				}),
   			],
   		}),
   	],
   });
   ```

</Steps>

サポートされているすべてのオプションについては、[DocSearchのJavaScriptクライアントAPIリファレンス](https://docsearch.algolia.com/docs/api/)を参照してください。

#### DocSearch UIを翻訳する

DocSearchはデフォルトで英語のUI文字列のみを提供しています。Starlightの組み込みの[国際化の仕組み](/ja/guides/i18n/#starlightのuiを翻訳する)を使って、モーダルのUIを翻訳できます。

<Steps>

1. `src/content.config.ts`で、Starlightの`i18n`コンテンツコレクション定義をDocSearchスキーマにより拡張します。

   ```js ins={5} ins=/{ extend: .+ }/
   // src/content.config.ts
   import { defineCollection } from 'astro:content';
   import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
   import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';
   import { docSearchI18nSchema } from '@astrojs/starlight-docsearch/schema';

   export const collections = {
   	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
   	i18n: defineCollection({
   		loader: i18nLoader(),
   		schema: i18nSchema({ extend: docSearchI18nSchema() }),
   	}),
   };
   ```

2. `src/content/i18n/`のJSONファイルに翻訳を追加します。

   以下はDocSearchで使われる英語のデフォルトです。

   ```json title="src/content/i18n/en.json"
   {
   	"docsearch.searchBox.resetButtonTitle": "Clear the query",
   	"docsearch.searchBox.resetButtonAriaLabel": "Clear the query",
   	"docsearch.searchBox.cancelButtonText": "Cancel",
   	"docsearch.searchBox.cancelButtonAriaLabel": "Cancel",
   	"docsearch.searchBox.searchInputLabel": "Search",

   	"docsearch.startScreen.recentSearchesTitle": "Recent",
   	"docsearch.startScreen.noRecentSearchesText": "No recent searches",
   	"docsearch.startScreen.saveRecentSearchButtonTitle": "Save this search",
   	"docsearch.startScreen.removeRecentSearchButtonTitle": "Remove this search from history",
   	"docsearch.startScreen.favoriteSearchesTitle": "Favorite",
   	"docsearch.startScreen.removeFavoriteSearchButtonTitle": "Remove this search from favorites",

   	"docsearch.errorScreen.titleText": "Unable to fetch results",
   	"docsearch.errorScreen.helpText": "You might want to check your network connection.",

   	"docsearch.footer.selectText": "to select",
   	"docsearch.footer.selectKeyAriaLabel": "Enter key",
   	"docsearch.footer.navigateText": "to navigate",
   	"docsearch.footer.navigateUpKeyAriaLabel": "Arrow up",
   	"docsearch.footer.navigateDownKeyAriaLabel": "Arrow down",
   	"docsearch.footer.closeText": "to close",
   	"docsearch.footer.closeKeyAriaLabel": "Escape key",
   	"docsearch.footer.searchByText": "Search by",

   	"docsearch.noResultsScreen.noResultsText": "No results for",
   	"docsearch.noResultsScreen.suggestedQueryText": "Try searching for",
   	"docsearch.noResultsScreen.reportMissingResultsText": "Believe this query should return results?",
   	"docsearch.noResultsScreen.reportMissingResultsLinkText": "Let us know."
   }
   ```

</Steps>

### コミュニティ製の検索プロバイダ

[コミュニティ製プラグイン](/ja/resources/plugins/#コミュニティ製プラグイン)により、Starlight組み込みのPagefind検索プロバイダの代替を利用することもできます。

#### Typesense DocSearch

[Starlight DocSearch Typesense](https://starlight-docsearch.typesense.org/)コミュニティプラグインは、[DocSearch](https://github.com/typesense/typesense-docsearch.js)インターフェースと[Typesense](https://typesense.org/)バックエンドを統合した、オープンソースでセルフホスト可能な代替手段を提供します。

プロジェクトでの使用方法については、Starlight DocSearch Typesenseドキュメントの[「Getting Started」](https://starlight-docsearch.typesense.org/getting-started/)ガイドを参照してください。


================================================
FILE: docs/src/content/docs/ja/index.mdx
================================================
---
title: Starlight 🌟 Astroでドキュメントサイトを作る
head:
  - tag: title
    content: Starlight 🌟 Astroでドキュメントサイトを作る
description: Starlightは、Astroを使った美しく高性能なドキュメントサイトの構築を支援します。
template: splash
editUrl: false
lastUpdated: false
hero:
  title: Starlightでドキュメントを輝かせる
  tagline: 最高のドキュメントサイトを作るために必要なものがすべて揃っています。高速でアクセシブル、しかも使いやすさも備えます。
  image:
    file: ~/assets/hero-star.webp
  actions:
    - text: はじめる
      icon: right-arrow
      link: /ja/getting-started/
    - text: GitHubで見る
      icon: external
      variant: minimal
      link: https://github.com/withastro/starlight
---

import { CardGrid, Card } from '@astrojs/starlight/components';
import AboutAstro from '~/components/about-astro.astro';
import TestimonialGrid from '~/components/testimonial-grid.astro';
import Testimonial from '~/components/testimonial.astro';

<CardGrid stagger>
	<Card title="心躍るドキュメント" icon="open-book">
		サイトナビゲーション、検索、国際化、SEO、読みやすいタイポグラフィ、コードハイライト、ダークモードなどを内蔵しています。
	</Card>
	<Card title="Astro製" icon="rocket">
		Astroのパワーとパフォーマンスを最大限に活用できます。お気に入りのAstroインテグレーションやライブラリで、Starlightを拡張できます。
	</Card>
	<Card title="Markdown、Markdoc、MDX" icon="document">
		お好みのマークアップ言語を使えます。Starlightは、TypeScriptの型安全性を活かしたフロントマターのバリデーションを組み込みで提供します。
	</Card>
	<Card title="独自のUIコンポーネントの利用" icon="puzzle">
		Starlightは、特定のフレームワークに依存しない、ドキュメント向けの完全なソリューションとして提供されています。React、Vue、Svelte、Solidなどで拡張可能です。
	</Card>
</CardGrid>

<TestimonialGrid title="人々の声">
  <Testimonial
    name="Rachel"
    handle="rachelnabors"
    cite="https://twitter.com/astrodotbuild/status/1724934718745915558"
  >
    Astroチームは、ドキュメントの作成方法を進化させました。Starlightプロジェクトには、必要なものがすべて揃っています。
  </Testimonial>
  <Testimonial
    name="Flavio"
    handle="flaviocopes"
    cite="https://twitter.com/flaviocopes/status/1738237658717905108"
  >
    Astro公式のスターターキットであるStarlightは、ドキュメントサイトを構築するための本当に素晴らしいツールです。
  </Testimonial>
  <Testimonial
    name="Tomek"
    handle="sulco"
    cite="https://twitter.com/sulco/status/1735610348730802342"
  >
    Starlightは、素晴らしいDXの典型例です。速度、使いやすさ、そして細部へのこだわりは感動的です。技術面とデザインの両方をケアしてくれるので、コンテンツに集中できます 👏

    StackBlitzチームもとても気に入っています!

  </Testimonial>
  <Testimonial
    name="Roberto"
    handle="RmeetsH"
    cite="https://twitter.com/RmeetsH/status/1735783992018760090"
  >
    Starlightによりコンテンツ作成に集中できるようになりました。私にとってゲームチェンジャーです。

    直感的な設計により、ワークフローが効率化されるだけでなく、オープンソース開発者のオンボーディング時間も短縮されています。

  </Testimonial>
  <Testimonial
    name="Joel"
    handle="jhooks"
    cite="https://twitter.com/jhooks/status/1727405160547418405"
  >
    Course BuilderのドキュメントにStarlightを使ってみていますが、素晴らしい体験です。細部まで気が利いており、サイトをいじったりすることなくMarkdownの執筆に集中できます。
  </Testimonial>
  <Testimonial
    name="Rick"
    handle="rick_viscomi"
    cite="https://twitter.com/rick_viscomi/status/1665867447910510593"
  >
    Starlightを使い始めました。何もしなくてもパフォーマンスが素晴らしいのには驚きました。

    💯💯💯💯

  </Testimonial>
  <Testimonial
    name="Nicolas"
    handle="beaussan"
    cite="https://twitter.com/beaussan/status/1735625189583466893"
  >
    Starlightはドキュメントを作成するのにベストな選択肢です。Astroのパワーとスピード、そしてStarlightのツールが組み合わさることで、天国のような体験が得られます。

    しばらく使っていますが、ずっと変わらず愛用しています!

  </Testimonial>
  <Testimonial
    name="Sylwia"
    handle="SylwiaVargas"
    cite="https://x.com/SylwiaVargas/status/1726556825741578286"
  >
    前職でStarlightを使っており、とても気に入っていました。素晴らしいコンポーネント、直感的なデザイン、そして非常にレスポンシブなコミュニティ(誰かが何かを必要とすると、すぐに対応してくれたり、回避策を教えてくれたりしました)。とても気持ちの良い体験でした。
  </Testimonial>
  <Testimonial
    name="Lou Cyx"
    handle="loucyx"
    cite="https://elk.zone/m.webtoo.ls/@loucyx@mastodon.social/111587380021362284"
  >
    Starlightのおかげで、私のモノレポサイトのドキュメントがより素晴らしいものとなりました。Astroのパワーはそのままに、非常に使いやすくなっています。開発してくれてありがとう!
  </Testimonial>
  <Testimonial
    name="BowTiedWebReaper"
    handle="BowTiedWebReapr"
    cite="https://twitter.com/BowTiedWebReapr/status/1735633399501697517"
  >
    Starlightは、ドキュメント作成に最適なツールです。既存のAstroサイトにドキュメントを追加するのがとても簡単になりました。他のツールを使うためのサブドメインが不要になりました。
  </Testimonial>
  <Testimonial
    name="Jeff"
    handle="J_Everhart383"
    cite="https://twitter.com/J_Everhart383/status/1691900590048292908"
  >
    WPEngine Atlas Platformのドキュメントを作り直しています。Starlightには、A+のドキュメントプラットフォームを作るために必要なものがすべて揃っています 🙌
  </Testimonial>
  <Testimonial
    name="Chloe"
    handle="solelychloe"
    cite="https://twitter.com/solelychloe/status/1695115277602628082"
  >
    Starlightを試してみてください!

    私はいくつかのサイトで使っていますが、素晴らしいですよ。

  </Testimonial>
</TestimonialGrid>

<AboutAstro title="提供:">
Astroは、速度を重視して設計されたオールインワンのウェブフレームワークです。お気に入りのUIコンポーネントやライブラリを使って、どこからでもコンテンツを取得し、どこにでもデプロイできます。

[Astroについて](https://astro.build/)

</AboutAstro>


================================================
FILE: docs/src/content/docs/ja/manual-setup.mdx
================================================
---
title: 手動セットアップ
description: 既存のAstroプロジェクトにStarlightを追加するために、Starlightを手動で設定する方法を学びます。
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

[入門](/ja/getting-started/#新しいプロジェクトの作成)で述べたように、新しいStarlightサイトを作成する最も簡単な方法は、`create astro`を使用することです。このガイドでは、既存のAstroプロジェクトにStarlightを追加する方法について説明します。

## Starlightをセットアップする

このガイドを進めるには、既存のAstroプロジェクトが必要です。

### Starlightインテグレーションの追加

Starlightは[Astroのインテグレーション](https://docs.astro.build/ja/guides/integrations-guide/)です。プロジェクトのルートディレクトリで`astro add`コマンドを実行してサイトに追加します。

<Tabs syncKey="pkg">
    <TabItem label="npm">
        ```sh
        npx astro add starlight
        ```

    </TabItem>
    <TabItem label="pnpm">
        ```sh
        pnpm astro add starlight
        ```
    </TabItem>
    <TabItem label="Yarn">
        ```sh
        yarn astro add starlight
        ```
    </TabItem>

</Tabs>

これにより、必要な依存関係がインストールされ、Astro設定ファイルの`integrations`配列にStarlightが追加されます。

### インテグレーションの設定

Starlightインテグレーションの設定は、`astro.config.mjs`ファイルでおこないます。

まずは`title`を追加してみましょう。

```js ins={8}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: '私の楽しいドキュメントサイト',
		}),
	],
});
```

他の利用可能なオプションについては、[Starlightの設定リファレンス](/ja/reference/configuration/)を参照してください。

### コンテンツコレクションの設定

StarlightはAstroの[コンテンツコレクション](https://docs.astro.build/ja/guides/content-collections/)の上に構築されています。この設定は`src/content.config.ts`ファイルでおこないます。

コンテンツの設定ファイルを作成または更新し、Starlightの[`docsLoader`](/ja/reference/configuration/#docsloader)と[`docsSchema`](/ja/reference/configuration/#docsschema)を使用する`docs`コレクションを追加します。

```js ins={3-4,7}
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
};
```

Starlightは、コレクションがレガシーなコンテンツコレクションの実装で処理される[`legacy.collections`フラグ](https://docs.astro.build/ja/reference/legacy-flags/)もサポートしています。既存のAstroプロジェクトがあり、現時点ではローダーを使用するためにコレクションを変更できない場合に便利です。

### コンテンツの追加

以上でStarlightの設定は完了し、コンテンツを追加する準備が整いました!

`src/content/docs/`ディレクトリを作成し、`index.md`ファイルを追加します。これが新しいサイトのホームページになります。

```md
---
# src/content/docs/index.md
title: 私のドキュメント
description: Starlightで作成されたこのドキュメントサイトで、私のプロジェクトについてもっと学びましょう。
---

ようこそ私のプロジェクトへ!
```

Starlightはファイルベースのルーティングを使用しています。そのため、`src/content/docs/`にあるMarkdown、MDX、Markdocファイルはすべて、サイトのページへと変換されます。フロントマターのメタデータ(上記の例では`title`と`description`フィールド)により、各ページの表示方法を変更できます。利用可能なオプションについては、[フロントマターのリファレンス](/ja/reference/frontmatter/)を参照してください。

## 既存サイトのためのヒント

既存のAstroプロジェクトがある場合は、Starlightを使用して、サイトにドキュメントセクションを迅速に追加できます。

### サブパスへのStarlightの追加

Starlightのすべてのページをサブパスに追加するには、ドキュメントのコンテンツを`src/content/docs/`のサブディレクトリに配置します。

たとえば、Starlightのページがすべて`/guides/`で始まる場合は、コンテンツを`src/content/docs/guides/`ディレクトリに追加します。

import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src/
  - content/
    - docs/
      - **guides/**
        - guide.md
        - index.md
  - pages/
- astro.config.mjs

</FileTree>

将来的には、`src/content/docs/`内にネストされたディレクトリを必要としないよう、このユースケースに対するサポートを改善する予定です。

### StarlightとSSR

SSRを有効にするには、Astroドキュメントの「[オンデマンドレンダリングアダプター](https://docs.astro.build/ja/guides/on-demand-rendering/)」ガイドに従い、Starlightプロジェクトにサーバーアダプターを追加します。

Starlightによって生成されるドキュメントページは、プロジェクトの出力モードに関係なくデフォルトでプリレンダリングされます。Starlightページのプリレンダリングを無効にするには、[`prerender`設定オプション](/ja/reference/configuration/#prerender)を`false`に設定します。


================================================
FILE: docs/src/content/docs/ja/reference/configuration.mdx
================================================
---
title: 設定方法
description: Starlightがサポートするすべての設定オプションの概要。
---

## `starlight`インテグレーションの設定

Starlightは[Astro](https://astro.build)ウェブフレームワークの上に構築されたインテグレーションです。`astro.config.mjs`設定ファイル内でプロジェクトの設定をおこないます。

```js
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: '私の楽しいドキュメントサイト',
		}),
	],
});
```

以下のオプションを`starlight`インテグレーションに設定できます。

### `title`(必須)

**type:** `string | Record<string, string>`

ウェブサイトのタイトルを設定します。メタデータとブラウザのタブのタイトルに使用されます。

文字列を設定できますが、多言語サイトの場合は、異なるロケールごとの値をもつオブジェクトも使用できます。オブジェクト形式を使用する場合、キーはBCP-47タグ(`en`、`ar`、`zh-CN`など)である必要があります。

```ts
starlight({
	title: {
		en: 'My delightful docs site',
		de: 'Meine bezaubernde Dokumentationsseite',
	},
});
```

### `description`

**type:** `string`

ウェブサイトの説明を設定します。`description`がページのフロントマターに設定されていない場合、`<meta name="description">`タグで検索エンジンに共有するメタデータとして使用されます。

### `logo`

**type:** [`LogoConfig`](#logoconfig)

ナビゲーションバーにサイトタイトルと並べて、またはその代わりとして表示するロゴ画像を設定します。単一の`src`プロパティを設定するか、`light`と`dark`用に別々の画像ソースを設定できます。

```js
starlight({
	logo: {
		src: './src/assets/my-logo.svg',
	},
});
```

#### `LogoConfig`

```ts
type LogoConfig = { alt?: string; replacesTitle?: boolean } & (
	| { src: string }
	| { light: string; dark: string }
);
```

### `tableOfContents`

**type:** `false | { minHeadingLevel?: number; maxHeadingLevel?: number }`  
**default:** `{ minHeadingLevel: 2, maxHeadingLevel: 3 }`

各ページの右側に表示される目次を設定します。デフォルトでは、`<h2>`と`<h3>`の見出しがこの目次に含まれます。

### `editLink`

**type:** `{ baseUrl: string }`

`editLink.baseUrl`を設定すると、「ページを編集」リンクが有効になります。最終的なリンクは、`editLink.baseUrl` + 現在のページのパスになります。たとえば、GitHubの`withastro/starlight`リポジトリのページを編集するには以下のようにします。

```js
starlight({
	editLink: {
		baseUrl: 'https://github.com/withastro/starlight/edit/main/',
	},
});
```

この設定により、`/introduction`ページには`https://github.com/withastro/starlight/edit/main/src/content/docs/introduction.md`を指す編集リンクが表示されます。

### `sidebar`

**type:** [`SidebarItem[]`](#sidebaritem)

サイトのサイドバーのナビゲーション項目を設定します。

サイドバーはリンクとリンクのグループの配列です。`slug`を使用する場合を除き、各項目は`label`と以下のプロパティのいずれかが必要です。

- `link` — 特定のURL、たとえば`'/home'`や`'https://example.com'`などへの単一のリンク。

- `slug` — たとえば`'guides/getting-started'`など、内部ページへの参照。

- `items` — サイドバーの複数のリンクとサブグループを含む配列。

- `autogenerate` — リンクのグループを自動的に生成するために、ドキュメントのディレクトリを指定するオブジェクト。

内部リンクは、`slug`プロパティをもつオブジェクトの代わりに文字列として指定することもできます。

```js
starlight({
	sidebar: [
		// 「ホーム」というラベルのついた単一のリンク。
		{ label: 'ホーム', link: '/' },
		// 4つのリンクを含む、「ここから始める」というラベルのついたグループ。
		{
			label: 'ここから始める',
			items: [
				// 内部リンクに`slug`を使用する。
				{ slug: 'intro' },
				{ slug: 'installation' },
				// 内部リンクのための省略形を使用する。
				'tutorial',
				'next-steps',
			],
		},
		// referenceディレクトリのすべてのページにリンクするグループ。
		{
			label: 'リファレンス',
			autogenerate: { directory: 'reference' },
		},
	],
});
```

#### 並び順

自動生成されたサイドバーグループは、ファイル名のアルファベット順に並べ替えられます。たとえば、`astro.md`から生成されたページは、`starlight.md`というページの上に表示されます。

#### グループの折りたたみ

リンクのグループはデフォルトで展開されます。`collapsed`プロパティを`true`に設定して、この動作を変更できます。

自動生成されたサブグループは、デフォルトでは親グループの`collapsed`プロパティに従います。`autogenerate.collapsed`プロパティを設定して、これを上書きできます。

```js {5,13}
sidebar: [
  // 折りたたまれたリンクのグループ。
  {
    label: '折りたたまれたリンク',
    collapsed: true,
    items: ['intro', 'next-steps'],
  },
  // 自動生成される折りたたまれたサブグループを含む展開されたグループ。
  {
    label: '参照',
    autogenerate: {
      directory: 'reference',
      collapsed: true,
    },
  },
],
```

#### ラベルの翻訳

多言語対応が必要なサイトの場合、各項目の`label`はデフォルトのロケールのものとみなされます。サポート対象の言語のラベルを提供するには、`translations`プロパティを設定します。

```js {5,9,14}
sidebar: [
  // ブラジルポルトガル語に翻訳されたラベルをもつサイドバーの例。
  {
    label: 'ここから始める',
    translations: { 'pt-BR': 'Comece Aqui' },
    items: [
      {
        label: '開始する',
        translations: { 'pt-BR': 'Introdução' },
        link: '/getting-started',
      },
      {
        label: 'プロジェクトの構造',
        translations: { 'pt-BR': 'Estrutura de Projetos' },
        link: '/structure',
      },
    ],
  },
],
```

#### `SidebarItem`

```ts
type SidebarItem =
	| string
	| ({
			translations?: Record<string, string>;
			badge?: string | BadgeConfig;
	  } & (
			| {
					// リンク
					link: string;
					label: string;
					attrs?: Record<string, string | number | boolean | undefined>;
			  }
			| {
					// 内部リンク
					slug: string;
					label?: string;
					attrs?: Record<string, string | number | boolean | undefined>;
			  }
			| {
					// リンクのグループ
					label: string;
					items: SidebarItem[];
					collapsed?: boolean;
			  }
			| {
					// 自動生成されたリンクのグループ
					label: string;
					autogenerate: {
						directory: string;
						collapsed?: boolean;
						attrs?: Record<string, string | number | boolean | undefined>;
					};
					collapsed?: boolean;
			  }
	  ));
```

#### `BadgeConfig`

```ts
interface BadgeConfig {
	text: string;
	variant?: 'note' | 'tip' | 'caution' | 'danger' | 'success' | 'default';
	class?: string;
}
```

### `locales`

**type:** <code>\{ \[dir: string\]: [LocaleConfig](#localeconfig) \}</code>

[サイトの国際化(i18n)をおこなうには](/ja/guides/i18n/)、サポート対象の`locales`を設定します。

各エントリは、その言語のファイルが保存されているディレクトリ名をキーとして使用する必要があります。

```js
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'My Site',
			// このサイトのデフォルト言語を英語に設定します。
			defaultLocale: 'en',
			locales: {
				// 英語のドキュメントは`src/content/docs/en/`にあります。
				en: {
					label: 'English',
				},
				// 簡体字中国語のドキュメントは`src/content/docs/zh-cn/`にあります。
				'zh-cn': {
					label: '简体中文',
					lang: 'zh-CN',
				},
				// アラビア語のドキュメントは`src/content/docs/ar/`にあります。
				ar: {
					label: 'العربية',
					dir: 'rtl',
				},
			},
		}),
	],
});
```

#### `LocaleConfig`

```ts
interface LocaleConfig {
	label: string;
	lang?: string;
	dir?: 'ltr' | 'rtl';
}
```

各ロケールに対し以下のオプションを設定できます。

##### `label`(必須)

**type:** `string`

たとえば言語の切替機能などでユーザーに表示する、この言語を表わすラベルです。ほとんどの場合、このラベルは、その言語を使用するユーザーが読みたいと思う言語の名前にすることが望ましいでしょう。たとえば、`"English"`、`"العربية"`、`"简体中文"`などです。

##### `lang`

**type:** `string`

この言語のBCP-47タグです。たとえば`"en"`、`"ar"`、`"zh-CN"`などです。設定されていない場合、デフォルトでは言語のディレクトリ名が使用されます。`"pt-BR"`や`"en-US"`のように地域タグが含まれる言語タグは、その地域専用の翻訳が見つからない場合、ベース言語の組み込みUI翻訳が使用されます。

##### `dir`

**type:** `'ltr' | 'rtl'`

この言語を記述する方向です。左から右へ(デフォルト)は`"ltr"`を、右から左へは`"rtl"`を設定します。

#### ルートロケール

`root`ロケールを設定することで、`/lang/`ディレクトリなしでデフォルト言語を提供できます。

```js {3-6}
starlight({
	locales: {
		root: {
			label: 'English',
			lang: 'en',
		},
		fr: {
			label: 'Français',
		},
	},
});
```

この設定により、たとえば`/getting-started/`を英語のルートとし、対応するフランス語のページを`/fr/getting-started/`として提供することができます。

### `defaultLocale`

**type:** `string`

このサイトのデフォルト言語を設定します。この値は、[`locales`](#locales)オブジェクトのキーのいずれかと一致する必要があります。(デフォルト言語が[ルートロケール](#ルートロケール)の場合は、この設定をスキップできます。)

翻訳がない場合には、デフォルトロケールがフォールバックコンテンツとして使用されます。

### `social`

**type:** <code>{`Array<{ label: string; icon: `}[StarlightIcon](/ja/reference/icons/){`; href: string }>`}</code>

このサイトのソーシャルメディアアカウントに関する任意の項目です。各エントリは、サイトヘッダーにアイコンリンクとして表示されます。

```js
starlight({
	social: [
		{ icon: 'codeberg', label: 'Codeberg', href: 'https://codeberg.org/knut' },
		{ icon: 'discord', label: 'Discord', href: 'https://astro.build/chat' },
		{ icon: 'github', label: 'GitHub', href: 'https://github.com/withastro' },
		{ icon: 'gitlab', label: 'GitLab', href: 'https://gitlab.com/delucis' },
		{ icon: 'mastodon', label: 'Mastodon', href: 'https://m.webtoo.ls/@astro' },
	],
}),
```

### `customCss`

**type:** `string[]`

Starlightサイトの見た目をカスタマイズするためのCSSファイルを設定します。

プロジェクトのルートからの相対パスで指定したローカルのCSSファイル(`'./src/custom.css'`など)と、npmモジュールとしてインストールしたCSS(`'@fontsource/roboto'`など)に対応しています。

```js
starlight({
	customCss: ['./src/custom-styles.css', '@fontsource/roboto'],
});
```

### `markdown`

**type:** `{ headingLinks?: boolean; processedDirs?: string[] }`  
**default:** `{ headingLinks: true, processedDirs: [] }`

StarlightのMarkdown処理を設定します。

#### `headingLinks`

**type:** `boolean`  
**default:** `true`

見出しにクリック可能なアンカーリンクを付けてレンダリングするかどうかを制御します。

```js
starlight({
	markdown: {
		// Starlightのクリック可能な見出しアンカーリンクを無効にする。
		headingLinks: false,
	},
}),
```

#### `processedDirs`

**type:** `string[]`  
**default:** `[]`

StarlightのMarkdownパイプラインで処理される追加のディレクトリを定義します。デフォルトでは、Starlightの[`docsLoader()`](/ja/reference/configuration/#docsloader)を使用して読み込まれたMarkdownおよびMDXコンテンツのみが処理されます。プロジェクトのルートからの相対パスでローカルディレクトリを指定できます(例: `'./src/data/comments/'`)。

Starlightの処理には、[クリック可能な見出しアンカーリンク](#headinglinks)、[補足情報のMarkdownディレクティブ構文](/ja/guides/authoring-content/#補足情報)、およびコードブロックのRTLサポートが含まれます。このオプションは、[カスタムページ](/ja/guides/pages/#カスタムページ)で`<StarlightPage>`コンポーネントを使用してカスタムコンテンツコレクションのコンテンツをレンダリングしており、そのコンテンツにもStarlightのMarkdown処理を適用したい場合に便利です。

```js
starlight({
	markdown: {
		// `src/data/reviews/`ディレクトリにある`reviews`コンテンツコレクションの
		// Markdownファイルを処理する。
		processedDirs: ['./src/data/reviews/'],
	},
}),
```

### `expressiveCode`

**type:** `StarlightExpressiveCodeOptions | boolean`  
**default:** `true`

Starlightは、[Expressive Code](https://expressive-code.com)を使用して、コードブロックのレンダリングやコード例の一部のハイライト、コードブロックへのファイル名の追加などをおこなっています。MarkdownやMDXのコンテンツでExpressive Code構文を使用する方法については、[「コードブロック」ガイド](/ja/guides/authoring-content/#コードブロック)を参照してください。

[Expressive Code標準の設定オプション](https://expressive-code.com/reference/configuration/)はすべて使用できます。また、Starlightの`expressiveCode`オプションを設定することで、Starlight固有のプロパティも使用できます。たとえば、Expressive Codeの`styleOverrides`オプションを設定して、デフォルトのCSSを上書きできます。これにより、コードブロックに角丸を付けるなどのカスタマイズが可能になります。

```js ins={2-4}
starlight({
	expressiveCode: {
		styleOverrides: { borderRadius: '0.5rem' },
	},
});
```

Expressive Codeを無効にするには、Starlightの設定で`expressiveCode: false`を設定します。

```js ins={2}
starlight({
	expressiveCode: false,
});
```

標準のExpressive Codeオプションに加えて、`expressiveCode`の設定に以下のStarlight固有のプロパティを追加することで、コードブロックのテーマの動作をさらにカスタマイズできます。

#### `themes`

**type:** `Array<string | ThemeObject | ExpressiveCodeTheme>`  
**default:** `['starlight-dark', 'starlight-light']`

コードブロックのスタイルに使用するテーマを設定します。サポートされているテーマのフォーマットの詳細については、[Expressive Codeの`themes`ドキュメント](https://expressive-code.com/guides/themes/)を参照してください。

Starlightは、デフォルトでSarah Drasnerの[Night Owlテーマ](https://github.com/sdras/night-owl-vscode-theme)のダークとライトのバリアントを使用します。

ダークテーマとライトテーマを少なくとも1つずつ提供すると、Starlightは自動的にアクティブなコードブロックのテーマを現在のサイトテーマと同期します。この動作は[`useStarlightDarkModeSwitch`](#usestarlightdarkmodeswitch)オプションから設定できます。

#### `useStarlightDarkModeSwitch`

**type:** `boolean`  
**default:** `true`

`true`の場合、サイトテーマが変更されると、コードブロックは自動的にライトテーマとダークテーマを切り替えます。`false`の場合、複数のテーマの切り替えをおこなうために、手動でCSSを追加する必要があります。

:::note
`themes`を設定する場合、Starlightのダークモードスイッチが機能するように、ダークテーマとライトテーマを少なくとも1つずつ設定する必要があります。
:::

#### `useStarlightUiThemeColors`

**type:** `boolean`  
**default:** `themes`が設定されていない場合は`true`、それ以外の場合は`false`

`true`の場合、コードブロックのUI要素(背景、ボタン、シャドウなど)の色にStarlightのCSS変数が使用され、[サイトのカラーテーマ](/ja/guides/css-and-tailwind/#テーマの設定)と一致させます。`false`の場合、これらの要素には、アクティブなシンタックスハイライトのテーマから提供される色が使用されます。

:::note
カスタムテーマを使用し、かつこの値を`true`に設定する場合、適切な色のコントラストを確保するために、ダークテーマとライトテーマを少なくとも1つずつ提供する必要があります。
:::

### `pagefind`

**type:** <code>boolean | <a href="#pagefindoptions">PagefindOptions</a></code>  
**default:** `true`

Starlightのデフォルトのサイト検索プロバイダである[Pagefind](https://pagefind.app/)を設定します。

`false`に設定すると、Pagefindによるサイトのインデックス作成はおこなわれません。また、デフォルトの検索UIを使用している場合は、これも非表示になります。

[`prerender`](#prerender)オプションが`false`に設定されている場合、Pagefindを有効にすることはできません。

Pagefindの検索クライアントを設定するには、`pagefind`にオブジェクトを設定します。

- 検索結果のランキングの計算方法を制御する`pagefind.ranking`オプションの使用方法については、Pagefindドキュメントの[「Customize Pagefind's result ranking」](https://pagefind.app/docs/ranking/)を参照してください。
- 複数サイトの検索方法を制御する`pagefind.mergeIndex`オプションの使用方法については、Pagefindドキュメントの[「Searching multiple sites」](https://pagefind.app/docs/multisite/)を参照してください。

#### `PagefindOptions`

```ts
interface PagefindOptions {
	ranking?: {
		pageLength?: number;
		termFrequency?: number;
		termSaturation?: number;
		termSimilarity?: number;
	};
	indexWeight?: number;
	mergeIndex?: Array<{
		bundlePath: string;
		indexWeight?: number;
		basePath?: string;
		baseUrl?: string;
		mergeFilter?: Record<string, string | string[]>;
		language?: string;
		ranking?: {
			pageLength?: number;
			termFrequency?: number;
			termSaturation?: number;
			termSimilarity?: number;
		};
	}>;
}
```

### `prerender`

**type:** `boolean`  
**default:** `true`

Starlightページが静的HTMLに事前レンダリングされるか、[SSRアダプター](https://docs.astro.build/ja/guides/on-demand-rendering/)によってオンデマンドでレンダリングされるかを設定します。

Starlightページはデフォルトで事前レンダリングされます。SSRアダプターを使用してStarlightページをオンデマンドでレンダリングしたい場合は、`prerender: false`に設定します。

### `head`

**type:** [`HeadConfig[]`](#headconfig)

Starlightサイトの`<head>`にカスタムタグを追加します。アナリティクスやその他のサードパーティのスクリプトやリソースを追加するのに便利です。

```js
starlight({
	head: [
		// Fathomのアナリティクススクリプトタグを追加する例。
		{
			tag: 'script',
			attrs: {
				src: 'https://cdn.usefathom.com/script.js',
				'data-site': 'MY-FATHOM-ID',
				defer: true,
			},
		},
	],
});
```

`head`のエントリーは直接HTML要素に変換され、Astroの[スクリプト](https://docs.astro.build/ja/guides/client-side-scripts/#スクリプトの処理)や[スタイル](https://docs.astro.build/ja/guides/styling/#astroでのスタイリング)の処理を通過しません。スクリプト、スタイル、または画像などのローカルアセットをインポートする必要がある場合は、[Headコンポーネントをオーバーライド](/ja/guides/overriding-components/#組み込みコンポーネントを再利用する)してください。

#### `HeadConfig`

```ts
interface HeadConfig {
	tag: string;
	attrs?: Record<string, string | boolean | undefined>;
	content?: string;
}
```

### `lastUpdated`

**type:** `boolean`  
**default:** `false`

フッターにページの最終更新日を表示するかどうかを制御します。

デフォルトでは、この機能はリポジトリのGit履歴に依存しており、[浅いクローン](https://git-scm.com/docs/git-clone/ja#git-clone---depthltdepthgt)を実行する一部のデプロイプラットフォームでは正確にならない場合があります。[フロントマターの`lastUpdated`フィールド](/ja/reference/frontmatter/#lastupdated)を使用して、各ページでこの設定またはGitを基準とした日付を上書きできます。

### `pagination`

**type:** `boolean`  
**default:** `true`

フッターに前のページと次のページへのリンクを含めるかどうかを定義します。

[`prev`](/ja/reference/frontmatter/#prev)と[`next`](/ja/reference/frontmatter/#next)フロントマターフィールドを使用して、この設定、またはリンクテキストとURLをページごとに上書きできます。

### `favicon`

**type:** `string`  
**default:** `'/favicon.svg'`

サイトのデフォルトファビコンのパスを設定します。ファビコンは`public/`ディレクトリに配置され、また有効なアイコンファイル(`.ico`、`.gif`、`.jpg`、`.png`、または`.svg`)である必要があります。

```js
starlight({
  favicon: '/images/favicon.svg',
}),
```

追加のバリアントやフォールバック用のファビコンを設定する必要がある場合は、[`head`オプション](#head)を使用してタグを追加できます。

```js
starlight({
	favicon: '/images/favicon.svg',
	head: [
		// Safari用にICOファビコンのフォールバックを追加します。
		{
			tag: 'link',
			attrs: {
				rel: 'icon',
				href: '/images/favicon.ico',
				sizes: '32x32',
			},
		},
	],
});
```

### `titleDelimiter`

**type:** `string`  
**default:** `'|'`

ブラウザのタブに表示される、ページの`<title>`タグ内のページタイトルとサイトタイトルの間の区切り文字を設定します。

デフォルトでは、すべてのページの`<title>`は`ページタイトル | サイトタイトル`となります。たとえば、このページのタイトルは「設定方法」であり、このサイトのタイトルは「Starlight」なので、このページの`<title>`は「設定方法 | Starlight」となります。

### `disable404Route`

**type:** `boolean`  
**default:** `false`

Starlightのデフォルトの[404ページ](https://docs.astro.build/ja/basics/astro-pages/#カスタム404エラーページ)を無効にします。プロジェクトでカスタムの`src/pages/404.astro`ルートを使用するには、このオプションを`true`に設定します。

### `routeMiddleware`

**type:** `string | string[]`

Starlightがデータを処理する方法を変更できるルートミドルウェアへのパスを指定します。これらのファイルパスは、[Astroのミドルウェア](https://docs.astro.build/ja/guides/middleware/)と競合してはなりません。

ルートミドルウェアの作成方法の詳細については、[ルートデータガイド](/ja/guides/route-data/#ルートデータのカスタマイズ)を参照してください。

### `components`

**type:** `Record<string, string>`

コンポーネントへのパスを指定して、Starlightのデフォルトの実装をオーバーライドします。

```js
starlight({
	components: {
		SocialLinks: './src/components/MySocialLinks.astro',
	},
});
```

オーバーライド可能なすべてのコンポーネントの詳細については、[オーバーライドリファレンス](/ja/reference/overrides/)を参照してください。

### `plugins`

**type:** [`StarlightPlugin[]`](/ja/reference/plugins/#api早見表)

Starlightをカスタムプラグインにより拡張します。プラグインは、Starlightの機能を変更または追加するために、プロジェクトに変更を適用します。

利用可能なプラグインの一覧については、[プラグインショーケース](/ja/resources/plugins/#プラグイン)を参照してください。

```js
starlight({
	plugins: [starlightPlugin()],
});
```

独自のプラグインを作成する方法の詳細については、[プラグインリファレンス](/ja/reference/plugins/)を参照してください。

### `credits`

**type:** `boolean`  
**default:** `false`

「Starlightで作成」リンクをサイトのフッターに表示します。

```js
starlight({
	credits: true,
});
```

## コンテンツコレクションの設定

Starlightは、Astroの[コンテンツコレクション](https://docs.astro.build/ja/guides/content-collections/)を使用してコンテンツを読み込みます。Starlightのコンテンツローダーとスキーマにより、必要に応じてコレクションを設定できます。

```js
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';

export const collections = {
	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
	// 任意: i18nコレクションは多言語サイトのUI翻訳に使用されます
	i18n: defineCollection({ loader: i18nLoader(), schema: i18nSchema() }),
};
```

### ローダー

Starlightは、コンテンツコレクションの設定をシンプルにするために、`@astrojs/starlight/loaders`モジュールから以下の[Astroローダー](https://docs.astro.build/ja/reference/content-loader-reference/)をエクスポートしています。

#### `docsLoader()`

`docsLoader()`は、`src/content/docs/`ディレクトリからローカルのMarkdown、MDX、Markdocファイルを読み込みます。アンダースコア(`_`)で始まるファイル名は無視されます。

##### インポート

```js
import { docsLoader } from '@astrojs/starlight/loaders';
```

##### オプション

###### `generateId()`

**type:** `({ entry: string; base: URL; data: Record<string, unknown> }) => string`

デフォルトでは、`docsLoader()`を使用して生成されたページは、ファイル名にスラッグ化処理を施し、特殊文字を削除してファイル名を小文字に変換します。このデフォルトの動作をオーバーライドしたい場合は、独自の`generateId()`関数を指定してください。

たとえば、デフォルトでは削除される特殊文字を保持したい場合に便利です。デフォルトでは、`Example.File.md`は`/examplefile`として配信されます。`/Example.File`として配信したい場合は、カスタムの`generateId()`関数を定義することで実現できます。

```js
docsLoader({
	// `.md`または`.mdx`拡張子を削除し、それ以外のファイル名は処理しない。
	generateId: ({ entry }) => entry.split('.').slice(0, -1).join('.'),
}),
```

詳細については、[Astroドキュメントの`generateId()`](https://docs.astro.build/ja/reference/content-loader-reference/#generateid)を参照してください。

#### `i18nLoader()`

`i18nLoader()`は、`src/content/i18n/`ディレクトリからローカルのJSONおよびYAMLファイルを読み込みます。アンダースコア(`_`)で始まるファイル名は無視されます。

##### インポート

```js
import { i18nLoader } from '@astrojs/starlight/loaders';
```

##### オプション

現在、`i18nLoader()`に設定可能なオプションはありません。

### スキーマ

Starlightは、`@astrojs/starlight/schema`モジュールから以下の[コンテンツコレクションスキーマ](https://docs.astro.build/ja/guides/content-collections/#defining-the-collection-schema)を提供しています。これらのスキーマは、Starlightが依存する`docs`および`i18n`コレクションに使用する必要があります。

#### `docsSchema()`

`docsSchema()`は、`docs`コレクション内のすべてのコンテンツのフロントマターを解析します。

##### インポート

```js
import { docsSchema } from '@astrojs/starlight/schema';
```

##### オプション

###### `extend`

**type:** Zodスキーマ、またはZodスキーマを返す関数
**default:** `z.object({})`

Starlightのフロントマタースキーマを追加フィールドで拡張します。`extend`オプションの使用方法の詳細については、[「フロントマタースキーマをカスタマイズする」](/ja/reference/frontmatter/#フロントマタースキーマをカスタマイズする)を参照してください。

#### `i18nSchema()`

`i18nSchema()`は、`i18n`コレクション内のすべてのデータファイルを解析します。

##### インポート

```js
import { i18nSchema } from '@astrojs/starlight/schema';
```

##### オプション

###### `extend`

**type:** Zodオブジェクト
**default:** `z.object({})`

Starlightのi18nスキーマを追加フィールドで拡張します。`extend`オプションの使用方法の詳細については、[「翻訳スキーマを拡張する」](/ja/guides/i18n/#翻訳スキーマを拡張する)を参照してください。


================================================
FILE: docs/src/content/docs/ja/reference/frontmatter.md
================================================
---
title: フロントマター
description: Starlightがデフォルトでサポートするフロントマターのフィールドについて。
---

Starlightでは、フロントマターに値を設定することで、MarkdownとMDXのページを個別にカスタマイズできます。たとえば通常のページでは、`title`と`description`フィールドを設定します。

```md {3-4}
---
# src/content/docs/example.md
title: このプロジェクトについて
description: 私が取り組んでいるプロジェクトについてもっと知る。
---

概要ページへようこそ!
```

## フロントマターのフィールド

### `title`(必須)

**type:** `string`

すべてのページにタイトルを指定する必要があります。これは、ページの上部、ブラウザのタブ、およびページのメタデータとして表示されます。

### `description`

**type:** `string`

ページに関する説明文はページのメタデータとして使用され、また検索エンジンやソーシャルメディアのプレビューでも使用されます。

### `slug`

**type**: `string`

ページのスラグを上書きします。詳しくは、Astroドキュメントの[「カスタムIDの定義」](https://docs.astro.build/ja/guides/content-collections/#defining-custom-ids)を参照してください。

### `editUrl`

**type:** `string | boolean`

[グローバルの `editLink` 設定](/ja/reference/configuration/#editlink)を上書きします。`false`を設定して特定のページの「ページを編集」リンクを無効にするか、あるいはこのページのコンテンツを編集する代替URLを指定します。

### `head`

**type:** [`HeadConfig[]`](/ja/reference/configuration/#headconfig)

フロントマターの`head`フィールドを使用して、ページの`<head>`にタグを追加できます。これにより、カスタムスタイル、メタデータ、またはその他のタグを単一のページに追加できます。[グローバルの`head`オプション](/ja/reference/configuration/#head)と同様です。

```md
---
# src/content/docs/example.md
title: 私たちについて
head:
  # カスタム<title>タグを使う
  - tag: title
    content: カスタムのタイトル
---
```

### `tableOfContents`

**type:** `false | { minHeadingLevel?: number; maxHeadingLevel?: number; }`

[グローバルの`tableOfContents`設定](/ja/reference/configuration/#tableofcontents)を上書きします。表示したい見出しのレベルをカスタマイズするか、あるいは`false`に設定して目次を非表示とします。

```md
---
# src/content/docs/example.md
title: 目次にH2のみを表示するページ
tableOfContents:
  minHeadingLevel: 2
  maxHeadingLevel: 2
---
```

```md
---
# src/content/docs/example.md
title: 目次のないページ
tableOfContents: false
---
```

### `template`

**type:** `'doc' | 'splash'`  
**default:** `'doc'`

ページのレイアウトテンプレートを設定します。ページはデフォルトで`'doc'`レイアウトを使用します。ランディングページ向けにサイドバーのない幅広のレイアウトを使用するには、`'splash'`を設定します。

### `hero`

**type:** [`HeroConfig`](#heroconfig)

ヒーローコンポーネントをページの上部に追加します。`template: splash`との相性が良いでしょう。

リポジトリからの画像の読み込みなど、よく使われるオプションの設定例は以下となります。

```md
---
# src/content/docs/example.md
title: 私のホームページ
template: splash
hero:
  title: '私のプロジェクト: 最高品質を、最速で'
  tagline: 瞬く間に月まで一往復。
  image:
    alt: キラリと光る、鮮やかなロゴ
    file: ../../assets/logo.png
  actions:
    - text: もっと知りたい
      link: /getting-started/
      icon: right-arrow
    - text: GitHubで見る
      link: https://github.com/astronaut/my-project
      icon: external
      variant: minimal
      attrs:
        rel: me
---
```

ライトモードとダークモードで、異なるバージョンのヒーロー画像を表示できます。

```md
---
# src/content/docs/example.md
hero:
  image:
    alt: キラリと光る、鮮やかなロゴ
    dark: ../../assets/logo-dark.png
    light: ../../assets/logo-light.png
---
```

#### `HeroConfig`

```ts
interface HeroConfig {
  title?: string;
  tagline?: string;
  image?:
    | {
        // リポジトリ内の画像への相対パス。
        file: string;
        // この画像を支援技術からアクセス可能にするための代替テキスト。
        alt?: string;
      }
    | {
        // ダークモードで使用する、リポジトリ内の画像への相対パス。
        dark: string;
        // ライトモードで使用する、リポジトリ内の画像への相対パス。
        light: string;
        // この画像を支援技術からアクセス可能にするための代替テキスト。
        alt?: string;
      }
    | {
        // 画像のスロットに使用する生のHTML。
        // カスタムの`<img>`タグやインラインの`<svg>`などが使えます。
        html: string;
      };
  actions?: Array<{
    text: string;
    link: string;
    variant?: 'primary' | 'secondary' | 'minimal';
    icon?: string;
    attrs?: Record<string, string | number | boolean>;
  }>;
}
```

### `banner`

**type:** `{ content: string }`

ページの上部にお知らせ用のバナーを表示します。

`content`の値には、リンクやその他のコンテンツ用のHTMLを含められます。たとえば以下のページでは、`example.com`へのリンクを含むバナーを表示しています。

```md
---
# src/content/docs/example.md
title: バナーを含むページ
banner:
  content: |
    素晴らしいサイトをリリースしました!
    <a href="https://example.com">確認してみてください</a>
---
```

### `lastUpdated`

**type:** `Date | boolean`

[グローバルの`lastUpdated`オプション](/ja/reference/configuration/#lastupdated)を上書きします。日付を指定する場合は有効な[YAMLタイムスタンプ](https://yaml.org/type/timestamp.html)である必要があり、ページのGit履歴に保存されている日付を上書きします。

```md
---
# src/content/docs/example.md
title: 最終更新日をカスタマイズしたページ
lastUpdated: 2022-08-09
---
```

### `prev`

**type:** `boolean | string | { link?: string; label?: string }`

[グローバルの`pagination`オプション](/ja/reference/configuration/#pagination)を上書きします。文字列を指定すると生成されるリンクテキストが置き換えられ、オブジェクトを指定するとリンクとテキストの両方を上書きできます。

```md
---
# src/content/docs/example.md
# 前のページへのリンクを非表示にする
prev: false
---
```

```md
---
# src/content/docs/example.md
# 前のページへのリンクテキストを上書きする
prev: チュートリアルを続ける
---
```

```md
---
# src/content/docs/example.md
# 前のページへのリンクとテキストを上書きする
prev:
  link: /unrelated-page/
  label: その他のページをチェックする
---
```

### `next`

**type:** `boolean | string | { link?: string; label?: string }`

次のページへのリンクに対して、[`prev`](#prev)と同様の設定ができます。

```md
---
# src/content/docs/example.md
# 次のページへのリンクを非表示にする
next: false
---
```

### `pagefind`

**type:** `boolean`  
**default:** `true`

ページを[Pagefind](https://pagefind.app/)の検索インデックスに含めるかどうかを設定します。ページを検索結果から除外するには、`false`に設定します。

```md
---
# src/content/docs/example.md
# このページを検索インデックスから外す
pagefind: false
---
```

### `draft`

**type:** `boolean`  
**default:** `false`

このページをドラフトとしてマークし、[本番ビルド](https://docs.astro.build/ja/reference/cli-reference/#astro-build)から除外するかどうかを設定します。ページをドラフトとしてマークし、開発中にのみ表示するには`true`に設定します。

```md
---
# src/content/docs/example.md
# 本番ビルドからこのページを除外します
draft: true
---
```

ドラフトページはビルド出力に含まれないため、[スラグ](/ja/guides/sidebar/#内部リンク)を使用してサイトのサイドバー設定に直接追加することはできません。[自動生成されるサイドバーグループ](/ja/guides/sidebar/#自動生成されるグループ)に使用されるディレクトリ内のドラフトページは、本番ビルドでは自動的に除外されます。

### `sidebar`

**type:** [`SidebarConfig`](#sidebarconfig)

自動生成されるリンクのグループを使用している際に、[サイドバー](/ja/reference/configuration/#sidebar)にページをどのように表示するかを設定します。

#### `SidebarConfig`

```ts
interface SidebarConfig {
  label?: string;
  order?: number;
  hidden?: boolean;
  badge?: string | BadgeConfig;
  attrs?: Record<string, string | number | boolean | undefined>;
}
```

#### `label`

**type:** `string`  
**default:** ページの[`title`](#title必須)

自動生成されるリンクのグループ内に表示される、ページのサイドバー上でのラベルを設定します。

```md
---
# src/content/docs/example.md
title: このプロジェクトについて
sidebar:
  label: 概要
---
```

#### `order`

**type:** `number`

自動生成されるリンクのグループをソートする際の、このページの順番を設定します。小さな数値ほどリンクグループの上部に表示されます。

```md
---
# src/content/docs/example.md
title: 最初に表示するページ
sidebar:
  order: 1
---
```

#### `hidden`

**type:** `boolean`
**default:** `false`

自動生成されるサイドバーのグループにこのページを含めないようにします。

```md
---
# src/content/docs/example.md
title: 自動生成されるサイドバーで非表示にするページ
sidebar:
  hidden: true
---
```

#### `badge`

**type:** <code>string | <a href="/ja/reference/configuration/#badgeconfig">BadgeConfig</a></code>

自動生成されるリンクのグループに表示されたとき、サイドバーのページにバッジを追加します。文字列を使用すると、バッジはデフォルトのアクセントカラーで表示されます。オプションで、`text`と`variant`、`class`フィールドをもつ[`BadgeConfig`オブジェクト](/ja/reference/configuration/#badgeconfig)を渡してバッジをカスタマイズできます。

```md
---
# src/content/docs/example.md
title: バッジを含むページ
sidebar:
  # サイトのアクセントカラーに合わせたデフォルトのバリアントを使用します
  badge: New
---
```

```md
---
# src/content/docs/example.md
title: バッジを含むページ
sidebar:
  badge:
    text: 実験的
    variant: caution
---
```

#### `attrs`

**type:** `Record<string, string | number | boolean | undefined>`

自動生成されるリンクのグループ内に表示されるサイドバーのページリンクに追加するHTML属性。このページが属する自動生成グループに[`autogenerate.attrs`](/ja/guides/sidebar/#自動生成されるリンクのカスタムhtml属性)が設定されている場合、フロントマターの属性はグループの属性とマージされます。

```md
---
# src/content/docs/example.md
title: 新しいタブで開くページ
sidebar:
  # 新しいタブでページを開きます
  attrs:
    target: _blank
---
```

## フロントマタースキーマをカスタマイズする

Starlightの`docs`コンテンツコレクションのフロントマタースキーマは、`docsSchema()`ヘルパーを使用して`src/content.config.ts`で設定されています。

```ts {4,7}
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
  docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
};
```

コンテンツコレクションのスキーマについて詳しくは、Astroドキュメントの[「コレクションスキーマの定義」](https://docs.astro.build/ja/guides/content-collections/#defining-the-collection-schema)を参照してください。

`docsSchema()`は以下のオプションを受け取ります。

### `extend`

**type:** ZodスキーマまたはZodスキーマを返す関数  
**default:** `z.object({})`

`docsSchema()`のオプションで`extend`を設定すると、Starlightのスキーマを追加のフィールドで拡張できます。値は[Zodスキーマ](https://docs.astro.build/ja/guides/content-collections/#zodによるデータ型の定義)である必要があります。

次の例では、`description`を必須にするために厳し目の型を指定し、さらにオプションの`category`フィールドを新規追加しています。

```ts {10-15}
// src/content.config.ts
import { defineCollection, z } from 'astro:content';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
  docs: defineCollection({
    loader: docsLoader(),
    schema: docsSchema({
      extend: z.object({
        // 組み込みのフィールドをオプションから必須に変更します。
        description: z.string(),
        // 新しいフィールドをスキーマに追加します。
        category: z.enum(['tutorial', 'guide', 'reference']).optional(),
      }),
    }),
  }),
};
```

[Astroの`image()`ヘルパー](https://docs.astro.build/ja/guides/images/#コンテンツコレクションと画像)を利用するには、拡張したスキーマを返す関数を使用します。

```ts {10-15}
// src/content.config.ts
import { defineCollection, z } from 'astro:content';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
  docs: defineCollection({
    loader: docsLoader(),
    schema: docsSchema({
      extend: ({ image }) => {
        return z.object({
          // ローカルの画像へと解決されるフィールドを追加します。
          cover: image(),
        });
      },
    }),
  }),
};
```


================================================
FILE: docs/src/content/docs/ja/reference/icons.mdx
================================================
---
title: アイコン
description: Starlightで利用可能なすべてのアイコンの概要。
---

Starlightには、`<Icon>`コンポーネントを使用してコンテンツに表示できる、組み込みのアイコンセットが用意されています。

## アイコンの使用

アイコンは[`<Icon>`](/ja/components/icons/)コンポーネントを使用して表示できます。また、[カード](/ja/components/cards/)や[ヒーローアクション](/ja/reference/frontmatter/#hero)の設定など、他のコンポーネントでもよく使用されます。

## `StarlightIcon` 型

TypeScriptの`StarlightIcon`型を使用して、[Starlightの組み込みアイコン](#すべてのアイコン)の名前を参照できます。

```ts {2} /icon: (StarlightIcon)/
// src/icon.ts
import type { StarlightIcon } from '@astrojs/starlight/types';

function getIconLabel(icon: StarlightIcon) {
	// …
}
```

## すべてのアイコン

利用可能なすべてのアイコンとその関連名が以下にリストされています。アイコンをクリックすると、その名前がクリップボードにコピーされます。

import IconsList from '~/components/icons-list.astro';

<IconsList labels={{ copied: 'コピー完了!' }} />


================================================
FILE: docs/src/content/docs/ja/reference/overrides.md
================================================
---
title: オーバーライド
description: Starlightのオーバーライドでサポートされているコンポーネントとコンポーネントプロパティの概要。
tableOfContents:
  maxHeadingLevel: 4
---

Starlightの[`components`](/ja/reference/configuration/#components)設定オプションに置き換え対象のコンポーネントへのパスを指定することで、Starlightの組み込みコンポーネントをオーバーライドできます。このページでは、オーバーライド可能なすべてのコンポーネントと、GitHub上にあるコンポーネントのデフォルト実装へのリンクの一覧を記載しています。

[コンポーネントのオーバーライドガイド](/ja/guides/overriding-components/)も参照してください。

## コンポーネント

### ヘッド

以下のコンポーネントは、各ページの`<head>`要素内にレンダリングされます。[`<head>`内に配置可能な要素](https://developer.mozilla.org/ja/docs/Web/HTML/Element/head#関連情報)のみを含めるようにしてください。

#### `Head`

**デフォルトコンポーネント:** [`Head.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Head.astro)

各ページの`<head>`内にレンダリングされるコンポーネント。

このコンポーネントをオーバーライドするのは最後の手段としてください。可能であれば、[`head`設定オプション](/ja/reference/configuration/#head)、[`head`フロントマターフィールド](/ja/reference/frontmatter/#head)、または[ルートデータミドルウェア](/ja/guides/route-data/#ルートデータのカスタマイズ)を使用して、デフォルトコンポーネントがレンダリングするルートデータをカスタマイズすることをおすすめします。

#### `ThemeProvider`

**デフォルトコンポーネント:** [`ThemeProvider.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/ThemeProvider.astro)

ダーク/ライトテーマのサポートを設定するための、`<head>`内にレンダリングされるコンポーネント。デフォルトの実装では、インラインスクリプトと[`<ThemeSelect />`](#themeselect)で使用される`<template>`が含まれています。

---

### アクセシビリティ

#### `SkipLink`

**デフォルトコンポーネント:** [`SkipLink.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/SkipLink.astro)

アクセシビリティのために`<body>`内の最初の要素としてレンダリングされる、メインページコンテンツへのリンクのコンポーネント。デフォルトの実装では、ユーザーがキーボードでタブを押してフォーカスするまで非表示となります。

---

### レイアウト

以下のコンポーネントは、Starlightのコンポーネントのレイアウトと、異なるブレークポイント間のビューの管理を担当します。これらをオーバーライドすると著しく複雑になるため、可能な限り、より低レベルのコンポーネントをオーバーライドすることをおすすめします。

#### `PageFrame`

**デフォルトコンポーネント:** [`PageFrame.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/PageFrame.astro)  
**名前付きスロット:** `header`, `sidebar`

ページコンテンツの大部分をラップするレイアウトコンポーネント。デフォルトの実装では、ヘッダー・サイドバー・メインのレイアウトをセットし、`header`と`sidebar`の名前付きスロットと、メインコンテンツのデフォルトスロットを含みます。また、小さな(モバイル)ビューポートでのサイドバーナビゲーションの切り替えをサポートするために、[`<MobileMenuToggle />`](#mobilemenutoggle)をレンダリングします。

#### `MobileMenuToggle`

**デフォルトコンポーネント:** [`MobileMenuToggle.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MobileMenuToggle.astro)

小さな(モバイル)ビューポートでのサイドバーナビゲーションの切り替えを担当する、[`<PageFrame>`](#pageframe)内にレンダリングされるコンポーネント。

#### `TwoColumnContent`

**デフォルトコンポーネント:** [`TwoColumnContent.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/TwoColumnContent.astro)  
**名前付きスロット:** `right-sidebar`

メインコンテンツのカラムと右サイドバー(目次)をラップするレイアウトコンポーネント。デフォルトの実装では、1カラムの小さなビューポート向けレイアウトと、2カラムの大きなビューポート向けレイアウトの切り替えをおこないます。

---

### ヘッダー

以下のコンポーネントは、Starlightのトップナビゲーションバーをレンダリングします。

#### `Header`

**デフォルトコンポーネント:** [`Header.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Header.astro)

すべてのページの上部に表示されるヘッダーコンポーネント。デフォルトの実装では、[`<SiteTitle />`](#sitetitle)、[`<Search />`](#search)、[`<SocialIcons />`](#socialicons)、[`<ThemeSelect />`](#themeselect)、[`<LanguageSelect />`](#languageselect)を表示します。

#### `SiteTitle`

**デフォルトコンポーネント:** [`SiteTitle.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/SiteTitle.astro)

サイトタイトルをレンダリングするためにサイトヘッダーの先頭にレンダリングされるコンポーネント。デフォルトの実装では、Starlightの設定で定義されたロゴをレンダリングするためのロジックが含まれています。

#### `Search`

**デフォルトコンポーネント:** [`Search.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Search.astro)

Starlightの検索UIをレンダリングするために使用されるコンポーネント。デフォルトの実装では、ヘッダー内のボタンと、クリックされたときに検索モーダルを表示し、[PagefindのUI](https://pagefind.app/)をロードするためのコードが含まれています。

[`pagefind`](/ja/reference/configuration/#pagefind)が無効になっている場合、デフォルトの検索コンポーネントはレンダリングされません。ただし、`Search`をオーバーライドすると、`pagefind`設定オプションが`false`であっても常にカスタムコンポーネントがレンダリングされます。これにより、Pagefindを無効にしたときに、代替となる検索プロバイダーのUIを追加できます。

#### `SocialIcons`

**デフォルトコンポーネント:** [`SocialIcons.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/SocialIcons.astro)

ソーシャルアイコンへのリンクを含む、サイトヘッダーにレンダリングされるコンポーネント。デフォルトの実装では、Starlightの設定の[`social`](/ja/reference/configuration/#social)オプションを使用して、アイコンとリンクをレンダリングします。

#### `ThemeSelect`

**デフォルトコンポーネント:** [`ThemeSelect.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/ThemeSelect.astro)

ユーザーが好みのカラースキームを選択できるようにするための、サイトヘッダーにレンダリングされるコンポーネント。

#### `LanguageSelect`

**デフォルトコンポーネント:** [`LanguageSelect.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/LanguageSelect.astro)

ユーザーが別の言語に切り替えられるようにするための、サイトヘッダーにレンダリングされるコンポーネント。

---

### グローバルサイドバー

Starlightのグローバルサイドバーには、メインのサイトナビゲーションが含まれます。小さなビューポートでは、これはドロップダウンメニューの背後に隠されます。

#### `Sidebar`

**デフォルトコンポーネント:** [`Sidebar.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Sidebar.astro)

グローバルナビゲーションを含んだ、ページコンテンツの前にレンダリングされるコンポーネント。デフォルトの実装では、十分に広いビューポートではサイドバーとして、小さな(モバイル)ビューポートではドロップダウンメニューの内側に表示されます。また、モバイルメニュー内に追加のアイテムを表示するために、[`<MobileMenuFooter />`](#mobilemenufooter)をレンダリングします。

#### `MobileMenuFooter`

**デフォルトコンポーネント:** [`MobileMenuFooter.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MobileMenuFooter.astro)

モバイルドロップダウンメニューの下部にレンダリングされるコンポーネント。デフォルトの実装では、[`<ThemeSelect />`](#themeselect)と[`<LanguageSelect />`](#languageselect)をレンダリングします。

---

### ページサイドバー

Starlightのページサイドバーは、現在のページの見出しを列挙する目次の表示を担当しています。小さなビューポートでは、これは固定されたドロップダウンメニューへと折りたたまれます。

#### `PageSidebar`

**デフォルトコンポーネント:** [`PageSidebar.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/PageSidebar.astro)

目次を表示するために、メインページのコンテンツの前にレンダリングされるコンポーネント。デフォルトの実装では、[`<TableOfContents />`](#tableofcontents)と[`<MobileTableOfContents />`](#mobiletableofcontents)をレンダリングします。

#### `TableOfContents`

**デフォルトコンポーネント:** [`TableOfContents.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/TableOfContents.astro)

現在のページの目次を、大きめのビューポートにおいてレンダリングするコンポーネント。

#### `MobileTableOfContents`

**デフォルトコンポーネント:** [`MobileTableOfContents.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MobileTableOfContents.astro)

現在のページの目次を、小さな(モバイル)ビューポートにおいてレンダリングするコンポーネント。

---

### コンテンツ

以下のコンポーネントは、ページコンテンツのメインカラムにレンダリングされます。

#### `Banner`

**デフォルトコンポーネント:** [`Banner.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Banner.astro)

各ページの上部にレンダリングされるバナーコンポーネント。デフォルトの実装では、ページの[`banner`](/ja/reference/frontmatter/#banner)フロントマターの値を使用して、レンダリングするかどうかを決定します。

#### `ContentPanel`

**デフォルトコンポーネント:** [`ContentPanel.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/ContentPanel.astro)

メインコンテンツカラムのセクションをラップするために使用されるレイアウトコンポーネント。

#### `PageTitle`

**デフォルトコンポーネント:** [`PageTitle.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/PageTitle.astro)

現在のページの`<h1>`要素を含むコンポーネント。

デフォルトの実装と同様に、`<h1>`要素に`id="_top"`を設定する必要があります。

#### `DraftContentNotice`

**デフォルトコンポーネント:** [`DraftContentNotice.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/DraftContentNotice.astro)

現在のページがドラフトとしてマークされている場合、開発中にユーザーに表示される通知。

#### `FallbackContentNotice`

**デフォルトコンポーネント:** [`FallbackContentNotice.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/FallbackContentNotice.astro)

現在の言語の翻訳が利用できないページにおいて、ユーザーに表示される通知。多言語サイトでのみ使用されます。

#### `Hero`

**デフォルトコンポーネント:** [`Hero.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Hero.astro)

フロントマターで[`hero`](/ja/reference/frontmatter/#hero)が設定されている場合に、ページの上部にレンダリングされるコンポーネント。デフォルトの実装では、大きなタイトル、タグライン、コールトゥアクション(call-to-action)リンク、オプションの画像を表示します。

#### `MarkdownContent`

**デフォルトコンポーネント:** [`MarkdownContent.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MarkdownContent.astro)

各ページのメインコンテンツの周囲にレンダリングされるコンポーネント。デフォルトの実装では、Markdownコンテンツに適用する基本的なスタイルをセットします。

Markdownコンテンツのスタイルは`@astrojs/starlight/style/markdown.css`にも公開されており、`.sl-markdown-content`CSSクラスにスコープされています。

---

### フッター

以下のコンポーネントは、ページコンテンツのメインカラムの下部にレンダリングされます。

#### `Footer`

**デフォルトコンポーネント:** [`Footer.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Footer.astro)

各ページの下部に表示されるフッターコンポーネント。デフォルトの実装では、[`<LastUpdated />`](#lastupdated)、[`<Pagination />`](#pagination)、[`<EditLink />`](#editlink)を表示します。

#### `LastUpdated`

**デフォルトコンポーネント:** [`LastUpdated.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/LastUpdated.astro)

最終更新日を表示するために、ページフッターにレンダリングされるコンポーネント。

#### `EditLink`

**デフォルトコンポーネント:** [`EditLink.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/EditLink.astro)

ページを編集できる場所へのリンクを表示するために、ページフッターにレンダリングされるコンポーネント。

#### `Pagination`

**デフォルトコンポーネント:** [`Pagination.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Pagination.astro)

前のページと次のページとの間にナビゲーション用矢印を表示するために、ページフッターにレンダリングされるコンポーネント。


================================================
FILE: docs/src/content/docs/ja/reference/plugins.md
================================================
---
title: プラグイン
description: StarlightのプラグインAPIの概要。
tableOfContents:
  maxHeadingLevel: 4
---

Starlightのプラグインにより、Starlightの設定、UI、および動作をカスタマイズできます。このリファレンスページでは、プラグインがアクセス可能なAPIについて説明します。

Starlightのプラグインを使用する方法について、詳しくは[設定方法のリファレンス](/ja/reference/configuration/#plugins)を参照してください。また、利用可能なプラグインの一覧については、[プラグインショーケース](/ja/resources/plugins/#プラグイン)を確認してください。

## API早見表

Starlightのプラグインは次の構造をもちます。各プロパティとフックパラメータの詳細については、以下を参照してください。

<!-- prettier-ignore-start -->
```ts
interface StarlightPlugin {
  name: string;
  hooks: {
    'i18n:setup'?: (options: {
      injectTranslations: (
        translations: Record<string, Record<string, string>>
      ) => void;
    }) => void | Promise<void>;
    'config:setup': (options: {
      config: StarlightUserConfig;
      updateConfig: (newConfig: StarlightUserConfig) => void;
      addIntegration: (integration: AstroIntegration) => void;
      addRouteMiddleware: (config: { entrypoint: string; order?: 'pre' | 'post' | 'default' }) => void;
      astroConfig: AstroConfig;
      command: 'dev' | 'build' | 'preview';
      isRestart: boolean;
      logger: AstroIntegrationLogger;
      useTranslations: (lang: string) => I18nT;
      absolutePathToLang: (path: string) => string;
    }) => void | Promise<void>;
  };
}
```
<!-- prettier-ignore-end -->

## `name`

**type:** `string`

プラグインには、自身を説明する一意の名前を指定する必要があります。名前は、このプラグインに関連する[ログメッセージ](#logger)を出力するときに使用されます。また、あるプラグインの存在を検出するために使用される場合もあります。

## `hooks`

フックは、Starlightが特定のタイミングでプラグインコードを実行するために呼び出す関数です。

フックの引数の型を取得するには、`HookParameters`ユーティリティ型を使用し、フック名を渡します。以下の例では、`options`パラメータは`config:setup`フックに渡される引数に一致するように型付けされています。

```ts
import type { HookParameters } from '@astrojs/starlight/types';

function configSetup(options: HookParameters['config:setup']) {
  options.useTranslations('en');
}
```

### `i18n:setup`

Starlightが初期化されるときに呼び出される、プラグインの国際化向けのセットアップ関数です。`i18n:setup`フックは、プラグインがさまざまなロケールをサポートできるように翻訳文字列を登録するために使用できます。これらの翻訳は、`config:setup`フックの[`useTranslations()`](#usetranslations)や、UIコンポーネントの[`Astro.locals.t()`](/ja/guides/i18n/#ui翻訳を使用する)を通じて利用できます。

`i18n:setup`フックは、以下のオプションとともに呼び出されます。

#### `injectTranslations`

**type:** `(translations: Record<string, Record<string, string>>) => void`

Starlightの[ローカライズAPI](/ja/guides/i18n/#ui翻訳を使用する)で使用される翻訳文字列を追加または更新するためのコールバック関数です。

以下の例では、プラグインが`en`と`fr`ロケールの`myPlugin.doThing`というカスタムUI文字列の翻訳を登録しています。

```ts {6-13} /(injectTranslations)[^(]/
// plugin.ts
export default {
  name: 'plugin-with-translations',
  hooks: {
    'i18n:setup'({ injectTranslations }) {
      injectTranslations({
        en: {
          'myPlugin.doThing': 'Do the thing',
        },
        fr: {
          'myPlugin.doThing': 'Faire le truc',
        },
      });
    },
  },
};
```

登録した翻訳をプラグインUIで使用するには、[“UI翻訳の使用“ガイド](/ja/guides/i18n/#ui翻訳を使用する)に従ってください。プラグインの[`config:setup`](#configsetup)フックのコンテキストでUI文字列を使用する必要がある場合は、[`useTranslations()`](#usetranslations)コールバックを使用できます。

プラグインが登録する翻訳文字列の型は、ユーザーのプロジェクトで自動的に生成されますが、プラグインのコードベースで作業中はまだ利用できません。プラグインのコンテキストで`locals.t`オブジェクトを型付けするには、TypeScript宣言ファイルで以下のグローバル名前空間を宣言します。

```ts
// env.d.ts
declare namespace App {
  type StarlightLocals = import('@astrojs/starlight').StarlightLocals;
  // プラグインのコンテキストで`locals.t`オブジェクトを定義します。
  interface Locals extends StarlightLocals {}
}

declare namespace StarlightApp {
  // `I18n`インターフェースにプラグインの追加の翻訳を定義します。
  interface I18n {
    'myPlugin.doThing': string;
  }
}
```

翻訳を含むオブジェクトがあるソースファイルから、`StarlightApp.I18n`インターフェースの型を推論することもできます。

たとえば、以下のソースファイルがあるとします。

```ts title="ui-strings.ts"
export const UIStrings = {
  en: { 'myPlugin.doThing': 'Do the thing' },
  fr: { 'myPlugin.doThing': 'Faire le truc' },
};
```

以下の宣言は、ソースファイルの英語キーから型を推論します。

```ts title="env.d.ts"
declare namespace StarlightApp {
  type UIStrings = typeof import('./ui-strings').UIStrings.en;
  interface I18n extends UIStrings {}
}
```

### `config:setup`

プラグインの設定セットアップ関数は、Starlightが初期化される際に呼び出されます([`astro:config:setup`](https://docs.astro.build/ja/reference/integrations-reference/#astroconfigsetup)インテグレーションフック内)。`config:setup`フックは、Starlightの設定を更新したり、Astroのインテグレーションを追加したりするために使用できます。

このフックは、以下のオプションとともに呼び出されます。

#### `config`

**type:** `StarlightUserConfig`

ユーザーが提供した[Starlightの設定](/ja/reference/configuration/)の、読み取り専用の複製です。この設定は、現在のプラグインより前に置かれた他のプラグインによって更新されている可能性があります。

#### `updateConfig`

**type:** `(newConfig: StarlightUserConfig) => void`

ユーザーが提供した[Starlightの設定](/ja/reference/configuration/)を更新するためのコールバック関数です。上書きしたいルートレベルの設定キーを指定します。ネストされた設定値を更新するには、ネストされたオブジェクトの全体を指定する必要があります。

既存の設定オプションをオーバーライドせず拡張するには、既存の値を新しい値へと展開します。以下の例では、`config.social`を新しい`social`配列に展開し、既存の設定に新しい[`social`](/ja/reference/configuration/#social)メディアアカウントを追加しています。

```ts {6-15}
// plugin.ts
export default {
  name: 'add-twitter-plugin',
  hooks: {
    'config:setup'({ config, updateConfig }) {
      updateConfig({
        social: [
          ...config.social,
          {
            icon: 'twitter',
            label: 'Twitter',
            href: 'https://twitter.com/astrodotbuild',
          },
        ],
      });
    },
  },
};
```

#### `addIntegration`

**type:** `(integration: AstroIntegration) => void`

プラグインが必要とする[Astroのインテグレーション](https://docs.astro.build/ja/reference/integrations-reference/)を追加するためのコールバック関数です。

以下の例では、プラグインはまず[AstroのReactインテグレーション](https://docs.astro.build/ja/guides/integrations-guide/react/)が設定されているかどうかを確認し、設定されていない場合は`addIntegration()`を使用して追加します。

```ts {14} "addIntegration,"
// plugin.ts
import react from '@astrojs/react';

export default {
  name: 'plugin-using-react',
  hooks: {
    'config:setup'({ addIntegration, astroConfig }) {
      const isReactLoaded = astroConfig.integrations.find(
        ({ name }) => name === '@astrojs/react'
      );

      // Reactインテグレーションがまだ読み込まれていない場合のみ追加します。
      if (!isReactLoaded) {
        addIntegration(react());
      }
    },
  },
};
```

#### `addRouteMiddleware`

**type:** `(config: { entrypoint: string; order?: 'pre' | 'post' | 'default' }) => void`

サイトに[ルートミドルウェアハンドラー](/ja/guides/route-data/)を追加するためのコールバック関数です。

`entrypoint`プロパティは、`onRequest`ハンドラーをエクスポートするプラグインのミドルウェアファイルのモジュール指定子である必要があります。

以下の例では、`@example/starlight-plugin`として公開されたプラグインが、npmモジュール指定子を使用してルートミドルウェアを追加しています。

```js {6-9}
// plugin.ts
export default {
  name: '@example/starlight-plugin',
  hooks: {
    'config:setup'({ addRouteMiddleware }) {
      addRouteMiddleware({
        entrypoint: '@example/starlight-plugin/route-middleware',
      });
    },
  },
};
```

##### 実行順序の制御

デフォルトでは、プラグインミドルウェアはプラグインが追加された順序で実行されます。

ミドルウェアの実行タイミングをより細かく制御する必要がある場合は、オプションの`order`プロパティを使用します。
ユーザーのミドルウェアより前に実行するには`order: "pre"`を設定します。他のすべてのミドルウェアの後に実行するには`order: "post"`を設定します。

同じ`order`値を持つミドルウェアを2つのプラグインが追加した場合、最初に追加されたプラグインが先に実行されます。

#### `astroConfig`

**type:** `AstroConfig`

ユーザーが提供した[Astroの設定](https://docs.astro.build/ja/reference/configuration-reference/)の、読み取り専用の複製です。

#### `command`

**type:** `'dev' | 'build' | 'preview'`

Starlightを実行するために使用されたコマンドです。

- `dev` - プロジェクトは`astro dev`により実行されています
- `build` - プロジェクトは`astro build`により実行されています
- `preview` - プロジェクトは`astro preview`により実行されています

#### `isRestart`

**type:** `boolean`

開発サーバーが起動したときは`false`、リロードがトリガーされたときは`true`となります。再起動が発生するよくある理由としては、開発サーバーが実行されている間にユーザーが`astro.config.mjs`を編集した場合などがあります。

#### `logger`

**type:** `AstroIntegrationLogger`

ログを書き込むために使用する[Astroインテグレーションロガー](https://docs.astro.build/ja/reference/integrations-reference/#astrointegrationlogger)のインスタンスです。すべてのログメッセージは、プラグイン名が接頭辞として付加されます。

```ts {6}
// plugin.ts
export default {
  name: 'long-process-plugin',
  hooks: {
    'config:setup'({ logger }) {
      logger.info('時間が掛かる処理を開始します…');
      // 何らかの時間が掛かる処理…
    },
  },
};
```

上記の例では、指定した`info`レベルのメッセージを含むログが出力されます。

```shell
[long-process-plugin] 時間が掛かる処理を開始します…
```

#### `useTranslations`

**type:** `(lang: string) => I18nT`

BCP-47言語タグを指定して`useTranslations()`を呼び出すと、その言語のUI文字列にアクセスするためのユーティリティ関数が生成されます。`useTranslations()`は、Astroコンポーネントで利用可能な`Astro.locals.t()`APIと同等のものを返します。利用可能なAPIの詳細については、[“UI翻訳の使用“](/ja/guides/i18n/#ui翻訳を使用する)ガイドを参照してください。

```ts {6}
// plugin.ts
export default {
  name: 'plugin-use-translations',
  hooks: {
    'config:setup'({ useTranslations, logger }) {
      const t = useTranslations('zh-CN');
      logger.info(t('builtWithStarlight.label'));
    },
  },
};
```

上記の例では、中国語簡体字の組み込みUI文字列を含むメッセージがログに出力されます。

```shell
[plugin-use-translations] 基于 Starlight 构建
```

#### `absolutePathToLang`

**type:** `(path: string) => string`

絶対ファイルパスを指定して`absolutePathToLang()`を呼び出すと、そのファイルの言語を取得できます。

これは、MarkdownやMDXファイルを処理する[remarkやrehypeプラグイン](https://docs.astro.build/ja/guides/markdown-content/#markdown-plugins)を追加する際に特に便利です。これらのプラグインが使用する[仮想ファイル形式](https://github.com/vfile/vfile)には、処理中のファイルの[絶対パス](https://github.com/vfile/vfile#filepath)が含まれており、`absolutePathToLang()`と組み合わせてファイルの言語を判定できます。返された言語は、[`useTranslations()`](#usetranslations)ヘルパーと組み合わせて、その言語のUI文字列を取得するために使用できます。

たとえば、以下のStarlight設定があるとします。

```js
starlight({
  title: 'My Docs',
  defaultLocale: 'en',
  locales: {
    // 英語ドキュメント: `src/content/docs/en/`
    en: { label: 'English' },
    // フランス語ドキュメント: `src/content/docs/fr/`
    fr: { label: 'Français', lang: 'fr' },
  },
});
```

プラグインは絶対パスを使用してファイルの言語を判定できます。

```ts {6-8} /fr/
// plugin.ts
export default {
  name: 'plugin-use-translations',
  hooks: {
    'config:setup'({ absolutePathToLang, useTranslations, logger }) {
      const lang = absolutePathToLang(
        '/absolute/path/to/project/src/content/docs/fr/index.mdx'
      );
      const t = useTranslations(lang);
      logger.info(t('aside.tip'));
    },
  },
};
```

上記の例では、フランス語の組み込みUI文字列を含むメッセージがログに出力されます。

```shell
[plugin-use-translations] Astuce
```


================================================
FILE: docs/src/content/docs/ja/reference/route-data.mdx
================================================
---
title: ルートデータ
description: Starlightのルートデータオブジェクトに関する完全なリファレンスドキュメントです。
---

Starlightのルートデータオブジェクトには、現在のページに関する情報が含まれています。Starlightのデータモデルがどのように機能するかについては、[「ルートデータ」ガイド](/ja/guides/route-data/) を参照してください。

Astroコンポーネント内では、`Astro.locals.starlightRoute`からルートデータにアクセスできます。

```astro {4}
---
// src/components/Custom.astro

const { hasSidebar } = Astro.locals.starlightRoute;
---
```

[ルートミドルウェア](/ja/guides/route-data/#ルートデータのカスタマイズ)内では、ミドルウェア関数に渡されるcontextオブジェクトからルートデータにアクセスします。

```ts {5}
// src/routeData.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

export const onRequest = defineRouteMiddleware((context) => {
	const { hasSidebar } = context.locals.starlightRoute;
});
```

## `starlightRoute`

`starlightRoute`オブジェクトは、以下のプロパティをもちます。

### `dir`

**型:** `'ltr' | 'rtl'`

ページの書字方向。

### `lang`

**型:** `string`

このページのロケールのBCP-47言語タグ。たとえば`en`、`zh-CN`、`pt-BR`など。

### `locale`

**型:** `string | undefined`

言語が配信されるベースパス。ルートロケールスラグの場合は`undefined`となります。

### `siteTitle`

**型:** `string`

このページのロケールのサイトタイトル。

### `siteTitleHref`

**型:** `string`

サイトタイトルの`href`属性の値。たとえば`/`など、ホームページへのリンクとなります。多言語サイトの場合、たとえば`/en/`や`/zh-cn/`など、現在のロケールが含まれます。

### `slug`

**型:** `string`

コンテンツファイル名から生成されたページのスラグ。

このプロパティは非推奨であり、Starlightの将来のバージョンで削除される予定です。[Starlightの`docsLoader`](/ja/manual-setup/#コンテンツコレクションの設定)を使用して新しいコンテンツレイヤーAPIに移行し、代わりに[`id`](#id)プロパティを使用してください。

### `id`

**型:** `string`

このページのスラグ。[`legacy.collections`](https://docs.astro.build/ja/reference/legacy-flags/#collections)フラグを使用している場合は、コンテンツファイル名に基づくページの一意のIDとなります。

### `isFallback`

**型:** `boolean | undefined`

このページが現在の言語で未翻訳であり、デフォルトロケールのフォールバックコンテンツを使用している場合は`true`となります。多言語サイトでのみ使用されます。

### `entryMeta`

**型:** `{ dir: 'ltr' | 'rtl'; lang: string }`

ページコンテンツのロケールメタデータ。ページがフォールバックコンテンツを使用している場合、トップレベルのロケール値とは異なる場合があります。

### `entry`

現在のページのAstroコンテンツコレクションのエントリー。`entry.data`には、現在のページのフロントマターの値が含まれます。

```ts
entry: {
	data: {
		title: string;
		description: string | undefined;
		// その他の値
	}
}
```

このオブジェクトの構造については、[Astroのコレクションエントリー型](https://docs.astro.build/ja/reference/modules/astro-content/#collectionentry)リファレンスを参照してください。

### `sidebar`

**型:** `SidebarEntry[]`

ページのサイトナビゲーション用サイドバーのエントリー。

### `hasSidebar`

**型:** `boolean`

ページにサイドバーを表示するかどうか。

### `pagination`

**型:** `{ prev?: Link; next?: Link }`

ページネーションの設定が有効な場合にサイドバーに表示される、前のページと次のページへのリンク。

### `toc`

**型:** `{ minHeadingLevel: number; maxHeadingLevel: number; items: TocItem[] } | undefined`

目次の設定が有効な場合、このページの目次。

### `headings`

**型:** `{ depth: number; slug: string; text: string }[]`

現在のページから抽出されたすべてのMarkdown見出しの配列。Starlightの設定オプションをもとに目次コンポーネントを作成したい場合は、[`toc`](#toc)を使用してください。

### `lastUpdated`

**型:** `Date | undefined`

最終更新日の設定が有効な場合、このページが最後に更新された日時を表わすJavaScriptの`Date`オブジェクト。

### `editUrl`

**型:** `URL | undefined`

ページの編集設定が有効な場合、このページを編集可能なアドレスの`URL`オブジェクト。

### `head`

**型:** [`HeadConfig[]`](/ja/reference/configuration/#headconfig)

現在のページの`<head>`に含めるすべてのタグの配列。`<title>`や`<meta charset="utf-8">`などの重要なタグが含まれます。

## ユーティリティ

### `defineRouteMiddleware()`

ルートミドルウェアモジュールに型を付けるには、`defineRouteMiddleware()`ユーティリティを使用します。

```ts "defineRouteMiddleware"
// src/routeData.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

export const onRequest = defineRouteMiddleware((context) => {
	// ...
});
```

### `StarlightRouteData`型

Starlightのルートデータを扱うコードを書く場合は、`StarlightRouteData`型をインポートして`Astro.locals.starlightRoute`の型定義に合わせることができます。

以下の例では、`usePageTitleInTOC()`関数がルートデータを更新し、目次の最初の項目のラベルとして現在のページのタイトルを使用することで、デフォルトの「概要」ラベルを置き換えます。`StarlightRouteData`型により、ルートデータの変更が正しいかどうかを確認できます。

```ts "StarlightRouteData"
// src/route-utils.ts
import type { StarlightRouteData } from '@astrojs/starlight/route-data';

export function usePageTitleInTOC(starlightRoute: StarlightRouteData) {
	const overviewLink = starlightRoute.toc?.items[0];
	if (overviewLink) {
		overviewLink.text = starlightRoute.entry.data.title;
	}
}
```

この関数は次のようにルートミドルウェアから呼び出すことができます。

```ts {3,6}
// src/route-middleware.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';
import { usePageTitleInTOC } from './route-utils';

export const onRequest = defineRouteMiddleware((context) => {
	usePageTitleInTOC(context.locals.starlightRoute);
});
```


================================================
FILE: docs/src/content/docs/ja/resources/community-content.mdx
================================================
---
title: コミュニティコンテンツ
description: コミュニティ製のガイドや記事、動画をチェックして、Starlightの学習や開発に役立てましょう!
---

:::tip[自分のものを追加しよう!]
Starlightに関するコンテンツを作成しましたか?このページにリンクを追加するPRを作成しましょう!
:::

import { CardGrid, LinkCard } from '@astrojs/starlight/components';

## 記事とレビュー

以下は、Starlightやその開発体験について学ぶための記事のコレクションです。

<CardGrid>
	<LinkCard
		href="https://devm.io/open-source/starlight-astro"
		title="Starlightによる静的サイト生成"
		description="「コンポーネントの設計において、大きすぎるアイデアも小さすぎるアイデアもありません」- StarlightリードのChris Swithinbankとのインタビュー"
	/>
	<LinkCard
		href="https://frontendatscale.com/blog/hybrid-frontend-architecture/"
		title="AstroとStarlightによるハイブリッドフロントエンドアーキテクチャ"
		description="Maxi FerreiraとBen Holmesが、Starlight、TinaCMS、認証付きのインタラクティブAPIプレイグラウンドを使用してドキュメントサイトを作成します。"
	/>
	<LinkCard
		href="https://www.olets.dev/posts/comparing-docs-site-builders-vuepress-vs-starlight/"
		title="ドキュメントサイトビルダーの比較: VuePressとStarlight"
		description="両フレームワークはどのように比較されるのでしょうか?"
	/>
	<LinkCard
		href="https://astro.build/case-studies/wp-engine/"
		title="ケーススタディ: 開発コストの大幅削減"
		description="WP EngineがAstroのStarlightを活用して開発コストを50%以上削減した方法。"
	/>
	<LinkCard
		href="https://maciekpalmowski.dev/blog/building-a-documentation-site-using-astro-starlight/"
		title="Astro Starlightを使ったドキュメントサイトの構築"
		description="Maciek Palmowskiが、PatchstackのドキュメントをどのようにStarlightに移行したかを紹介しています。"
	/>
	<LinkCard
		href="https://blog.cloudflare.com/open-source-all-the-way-down-upgrading-our-developer-documentation/"
		title="すべてをオープンソースで"
		description="Cloudflareが開発者向けドキュメントをStarlightでアップグレードした方法。"
	/>
	<LinkCard
		href="https://starlight-changelog.netlify.app/"
		title="Starlight Changelog"
		description="@astrojs/starlightパッケージのすべてのリリースを1つの見やすいページで確認できます。"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/contributing-to-starlight"
		title="Starlightへのコントリビューション"
		description="Starlightのようなオープンソースプロジェクトへのコントリビューションについての個人的な経験とアドバイス。"
	/>
</CardGrid>

## レシピとガイド

レシピは通常、特定のタスクを読者に具体的に案内する、焦点を絞った短いハウツーガイドです。ステップバイステップの手順に従って、Starlightプロジェクトに新しい機能や動作を追加するための素晴らしい方法といえます!他のガイドでは、画像の使用やMDXの扱い方など、コンテンツの領域に関連する概念も説明しています。

Starlightユーザーによってメンテナンスされている、コミュニティ製のコンテンツをチェックしてみましょう。

<CardGrid>
	<LinkCard
		href="https://www.webpro.nl/scraps/versioned-docs-with-starlight-and-vercel"
		title="StarlightとVercelでバージョン管理されたドキュメントを作成する"
		description="プロジェクトの各メジャーバージョンごとにドキュメントのバージョンを分けて実装する方法についてのガイド。"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-heading-links"
		title="Starlightの見出しにリンクを追加する"
		description="rehypeプラグインを使用して、ドキュメントの特定のセクションへのリンクを共有する方法についてのガイド。"
	/>
	<LinkCard
		href="https://blog.otterlord.dev/posts/starlight-sponsors/"
		title="Starlightサイトにスポンサーを追加する"
		description="ドキュメントのサイドバーにカスタムスポンサーコンポーネントを実装する方法についてのガイド。"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-og-images"
		title="Open Graph画像をStarlightに追加する"
		description="ソーシャル画像とそれに対応するメタタグを生成する方法についてのガイド。"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-third-party-icon-sets"
		title="サードパーティのアイコンセットをStarlightで使用する"
		description="unplugin-iconsを使用して、Starlightで利用可能なアイコンの選択肢を拡張する方法についてのガイド。"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-custom-html-head"
		title="StarlightページのHTMLヘッドを編集する"
		description="ウェブアナリティクス、フォント、スクリプトなどの共通のヘッドコンテンツを追加する方法について学びます。"
	/>
	<LinkCard
		href="https://dev.to/mrrobot/publishing-documentation-with-astro-starlight-691"
		title="AstroのStarlightでドキュメントを公開する"
		description="Starlightドキュメントの始め方。"
	/>
	<LinkCard
		href="https://events-3bg.pages.dev/jotter/starlight/"
		title="ビュートランジションを有効にする"
		description="Starlightドキュメントサイトにビュートランジション、クライアントサイドルーティング、SPAライクなナビゲーションのサポートを追加します。"
	/>
	<LinkCard
		href="https://jamcomments.com/posts/structured-data-with-starlight"
		title="Starlightページに構造化データを追加する"
		description="ドキュメントページに動的なJSON-LD構造化データを作成する方法を紹介しています。"
	/>
	<LinkCard
		href="https://starlight-examples.netlify.app/"
		title="Starlightの実例集"
		description="Starlightドキュメントサイトでの実践的な方法を紹介するStackBlitz上のコレクションです。"
	/>
	<LinkCard
		href="https://hideoo.dev/notebooks/starlight-plugins-by-example"
		title="実例で学ぶStarlightプラグイン"
		description="Starlightプラグインと、その作成における一般的なパターンに関するノートと実例のコレクションです。"
	/>
	<LinkCard
		href="https://blog.trueberryless.org/blog/starlight-progress-indicator/"
		title="閲覧の進捗インジケーターを追加する"
		description="Starlightサイトに水平方向の閲覧進捗バーを追加する方法を紹介しています。"
	/>
	<LinkCard
		href="https://blog.trueberryless.org/blog/starlight-sidebar-whitespace/"
		title="Starlightサイドバーにカスタムスタイルを適用する"
		description="少しのCSSでStarlightサイドバーのフォントや色などを調整する方法を紹介しています。"
	/>
	<LinkCard
		href="https://blog.trueberryless.org/blog/starlight-dropdown-and-list-together/"
		title="モバイルではドロップダウン、デスクトップではリスト表示"
		description="2つのプラグインを組み合わせて、デスクトップとモバイルの両方で最適な表示を実現します。"
	/>
	<LinkCard
		href="https://blog.trueberryless.org/blog/starlight-autogenerate-whole-sidebar/"
		title="ミドルウェアでStarlightサイドバーを処理する"
		description="Nuxt Contentの規約に着想を得た、ルートミドルウェアによるサイドバーの順序やグループラベルの制御方法を紹介しています。"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-custom-social-links"
		title="カスタムアイコン付きのソーシャルリンクをStarlightに追加する"
		description="Starlightサイトのヘッダーでソーシャルリンクにカスタムアイコンを使用する方法を紹介しています。"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-paste-images-with-visual-studio-code"
		title="Visual Studio CodeでStarlightページに画像を貼り付ける"
		description="Visual Studio Codeを使ってドキュメントページに画像を貼り付けることで、Starlightのドキュメント作成ワークフローを改善します。"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-add-diagrams-using-d2"
		title="D2を使ってStarlightドキュメントにダイアグラムを追加する"
		description="D2を使用してStarlightドキュメントにダイアグラムを追加する方法を紹介しています。"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-og-images-cloudinary-astro-sdk"
		title="Cloudinary Astro SDKを使ってStarlightのOpen Graph画像を生成する"
		description="Cloudinary Astro SDKを使用して、StarlightドキュメントサイトのOpen Graph画像を生成する方法を紹介しています。"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-list-recent-github-releases"
		title="Astro Content Layer APIを使ってStarlightにGitHubの最新リリースを一覧表示する"
		description="Astro Content Layer APIを使用して、StarlightプロジェクトにGitHubの最新リリースを一覧表示する方法を紹介しています。"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-sitewide-banner"
		title="Starlightにサイト全体で適用されるバナーを追加する"
		description="Starlightに組み込まれたページごとのバナー機能を活用して、サイト全体で適用されるバナーを作成する方法を紹介しています。"
	/>
</CardGrid>

## 動画コンテンツ

ライブストリームや教育コンテンツなど、Starlightに関する動画やチャンネルをチェックしてみましょう。

import YouTubeGrid from '~/components/youtube-grid.astro';

### 公式動画

<YouTubeGrid
	videos={[
		{
			href: 'https://www.youtube.com/watch?v=5u0Ds7wzUeI',
			title: 'AstroによるStarlight',
			description: '公式のStarlightローンチ動画をご覧ください。',
		},
		{
			href: 'https://www.youtube.com/watch?v=j8K-ESJF814',
			title: 'Starlight 1周年!',
			description:
				'Astroのコミュニティ製ドキュメントテーマについてSarahが語ります。',
		},
	]}
/>

### コミュニティ製の動画とストリーム

<YouTubeGrid
	videos={[
		{
			href: 'https://www.youtube.com/shorts/zjOWezSzd18',
			title: '🌟 1分で起動チャレンジ',
			description:
				'Benが1分以内に新しいStarlightサイトを立ち上げる様子を見てみましょう!',
		},
		{
			href: 'https://www.youtube.com/watch?v=sF6UcV3moZg',
			title: 'StarlightとAstroでドキュメントを作成する',
			description:
				'ChrisとAlexが、Code with CodingCat.devでStarlightについて語ります。',
		},
		{
			href: 'https://www.youtube.com/watch?v=sWkkHbwDeQc',
			title: 'Astro Starlight',
			description: '1分でStarlightを紹介します。',
		},
		{
			href: 'https://www.youtube.com/watch?v=-Ki-1E5gNCk',
			title:
				'AstroによるStarlightドキュメントテンプレート(アプリのドキュメントを作る!)',
			description: '5分で新しいStarlightサイトを立ち上げます。',
		},
		{
			href: 'https://www.youtube.com/watch?v=12o7WxjAxjM',
			title:
				'プロキシを使ってNext.jsプロジェクトにStarlightドキュメントを組み込む',
			description:
				'Next.jsウェブサイト内にStarlightをサブディレクトリプロジェクトとしてセットアップします。',
		},
		{
			href: 'https://www.youtube.com/watch?v=5pq80drDrNs',
			title: 'このすごいツールでShadcnのドキュメントを30分で再現してみた',
			description:
				'この動画では、Starlightのどこがすごいのか、そしてなぜ次のプロジェクトで試してみる価値があるのかを解説します。',
		},
		{
			href: 'https://www.youtube.com/watch?v=Q1E4Gkt63ko',
			title: 'Chris Swithinbankと学ぶAstro Starlightとemoji-blast',
			description:
				'AstroのStarlight生みの親であるChrisが、新しいemoji-blastウェブサイトへのセットアップ方法を一緒に案内してくれます。🌟 🎇',
		},
	]}
/>


================================================
FILE: docs/src/content/docs/ja/resources/plugins.mdx
================================================
---
title: プラグインとインテグレーション
description: プラグインやインテグレーションをチェックして、Starlightを拡張しましょう!
sidebar:
  order: 1
---

:::tip[自分のものを追加しよう!]
Starlight向けのプラグインやツールを作成しましたか?このページにリンクを追加するPRを作成しましょう!
:::

## プラグイン

[プラグイン](/ja/reference/plugins/)により、Starlightの設定やUI、動作をカスタマイズできます。また、プラグインは簡単に共有や再利用ができます。Starlightチームが公式にサポートする公式プラグインと、Starlightユーザーがメンテナンスするコミュニティ製プラグインでサイトを拡張しましょう。

### 公式プラグイン

<CardGrid>
	<LinkCard
		href="/ja/guides/site-search/#algolia-docsearch"
		title="Algolia DocSearch"
		description="デフォルトの検索プロバイダーであるPagefindを、Algolia DocSearchに置き換えます。"
	/>
</CardGrid>

### コミュニティ製プラグイン

<CardGrid>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-links-validator"
		title="starlight-links-validator"
		description="Starlightページ内のリンクが壊れていないかをチェックします。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-typedoc"
		title="starlight-typedoc"
		description="TypeDocにより、TypeScriptコードからStarlightページを生成します。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-blog"
		title="starlight-blog"
		description="ドキュメントサイトにブログを追加します。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-openapi"
		title="starlight-openapi"
		description="OpenAPI/Swaggerの仕様からドキュメントページを作成します。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-obsidian"
		title="starlight-obsidian"
		description="Obsidianの保管庫をStarlightサイトに公開します。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-image-zoom"
		title="starlight-image-zoom"
		description="ドキュメントの画像にズーム機能を追加します。"
	/>
	<LinkCard
		href="https://github.com/lorenzolewis/starlight-utils"
		title="starlight-utils"
		description="よく使うユーティリティのコレクションでStarlightを拡張します。"
	/>
	<LinkCard
		href="https://github.com/trueberryless/starlight-view-modes"
		title="starlight-view-modes"
		description="ドキュメントサイトにさまざまな表示モード機能を追加します。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-versions"
		title="starlight-versions"
		description="Starlightのドキュメントページをバージョン管理します。"
	/>
	<LinkCard
		href="https://inox-tools.fryuni.dev/star-warp"
		title="star-warp"
		description="ドキュメント内の検索結果を高速に移動します。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-heading-badges"
		title="starlight-heading-badges"
		description="MarkdownやMDXの見出しにバッジを追加します。"
	/>
	<LinkCard
		href="https://github.com/Fevol/starlight-site-graph"
		title="starlight-site-graph"
		description="ページのサイドバーにインタラクティブなサイトグラフを追加します。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-sidebar-topics"
		title="starlight-sidebar-topics"
		description="ドキュメントを、それぞれ独自のサイドバーをもつ複数のセクションに分割します。"
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-cooler-credit"
		title="starlight-cooler-credit"
		description="目次の下部にStarlightやAstroへのクレジットを表示します。"
	/>
	<LinkCard
		href="https://github.com/dragomano/starlight-giscus"
		title="starlight-giscus"
		description="ドキュメントサイトにGiscusコメント機能を追加します。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-videos"
		title="starlight-videos"
		description="動画ガイドやコースでドキュメントを充実させます。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-kbd"
		title="starlight-kbd"
		description="キーボードショートカットを簡単にドキュメント化します。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-auto-sidebar"
		title="starlight-auto-sidebar"
		description="自動生成されたサイドバーグループを調整します。"
	/>
	<LinkCard
		href="https://github.com/delucis/starlight-llms-txt"
		title="starlight-llms-txt"
		description="llmstxt.orgに基づいて、ドキュメントサイトにllms.txtを追加します。"
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-toc-overview-customizer"
		title="starlight-toc-overview-customizer"
		description="カスタマイズ可能な概要タイトルでStarlightの目次を調整します。"
	/>
	<LinkCard
		href="https://delucis.github.io/starlight-markdown-blocks/"
		title="starlight-markdown-blocks"
		description="カスタムブロックタイプでStarlightのMarkdownアサイド構文を拡張します。"
	/>
	<LinkCard
		href="https://github.com/WindMillCode/starlight-fullview-mode"
		title="starlight-fullview-mode"
		description="サイドバーを折りたたみ、コンテンツを拡大してフルスクリーン表示を実現します。"
	/>
	<LinkCard
		href="https://github.com/frostybee/starlight-scroll-to-top"
		title="starlight-scroll-to-top"
		description="ドキュメントサイトにページトップへのスクロールボタンを追加します。"
	/>
	<LinkCard
		href="https://github.com/frostybee/starlight-codeblock-fullscreen"
		title="starlight-codeblock-fullscreen"
		description="ドキュメント内のExpressive Codeブロックにフルスクリーン切り替え機能を追加します。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-auto-drafts"
		title="starlight-auto-drafts"
		description="下書きページのデフォルト動作を調整し、本番モードでは下書きページへのサイドバーリンクを自動的に削除します。"
	/>
	<LinkCard
		href="https://github.com/corsfix/starlight-contextual-menu"
		title="starlight-contextual-menu"
		description="Starlightドキュメントにコンテキストメニューを追加します。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-changelogs"
		title="starlight-changelogs"
		description="プロジェクトのドキュメントと一緒に変更履歴を表示します。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-github-alerts"
		title="starlight-github-alerts"
		description="GitHubアラートをStarlightのアサイドとしてレンダリングします。"
	/>
	<LinkCard
		href="https://github.com/dlcastillop/starlight-page-actions"
		title="starlight-page-actions"
		description="ドキュメントにページアクションボタンを追加します。"
	/>
	<LinkCard
		href="https://github.com/typesense/starlight-docsearch-typesense"
		title="starlight-docsearch-typesense"
		description="公式のAlgolia DocSearchプラグインに代わる、Typesenseを使用した検索プラグインです。"
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-sidebar-swipe/"
		title="starlight-sidebar-swipe"
		description="Discord Mobileのように、モバイルデバイスで左サイドバーをスワイプ可能にします。"
	/>
	<LinkCard
		href="https://github.com/Rettend/starlight-plugin-icons"
		title="starlight-plugin-icons"
		description="Astro Starlightのサイドバー、コードブロック、ファイルツリーにアイコンを追加します。"
	/>
	<LinkCard
		href="https://github.com/dlcastillop/starlight-ui-tweaks"
		title="starlight-ui-tweaks"
		description="カスタムナビゲーションリンク、広告、マーケティングフッター、よりシンプルなテーマ切り替えでコアUIコンポーネントを拡張します。"
	/>
	<LinkCard
		href="https://frostybee.github.io/starlight-tags/"
		title="starlight-tags"
		description="コンテンツの整理や検索のために、Starlightドキュメントページにタグを追加します。"
	/>
</CardGrid>

## コミュニティ製ツールとインテグレーション

import { CardGrid, LinkCard } from '@astrojs/starlight/components';

以下のコミュニティ製ツールやインテグレーションにより、Starlightサイトに機能を追加できます。

<CardGrid>
	<LinkCard
		href="https://www.feelback.dev/blog/new-astro-starlight-integration/"
		title="FeelBack"
		description="ユーザーフィードバックシステムをドキュメントページに追加します。"
	/>
	<LinkCard
		href="https://github.com/val-town/notion-to-astro"
		title="notion-to-astro"
		description="NotionのエクスポートをAstro Starlightドキュメントに変換します。"
	/>
	<LinkCard
		href="https://github.com/mattjennings/astro-live-code"
		title="astro-live-code"
		description="MDXコードブロックをインタラクティブなコンポーネントとしてレンダリングします。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-i18n"
		title="starlight-i18n"
		description="Starlightページの翻訳を支援するVisual Studio Code拡張機能です。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-package-managers"
		title="starlight-package-managers"
		description="複数のパッケージマネージャーに対応したnpm関連コマンドをすばやく表示します。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-showcases"
		title="starlight-showcases"
		description="ショーケースページを作成するためのStarlightコンポーネントセットです。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/generator-starlight-plugin"
		title="@hideoo/starlight-plugin"
		description="Starlightプラグインをすばやく雛形から作成するジェネレーターです。"
	/>
	<LinkCard
		href="https://github.com/Linkerin/starlight-to-pdf"
		title="starlight-to-pdf"
		description="StarlightサイトをPDFファイルに変換するCLIツールです。"
	/>
	<LinkCard
		href="https://github.com/joesaby/astro-plantuml"
		title="astro-plantuml"
		description="Markdownコードブロック内のPlantUMLコンテンツをレンダリングします。"
	/>
	<LinkCard
		href="https://github.com/joesaby/astro-mermaid"
		title="astro-mermaid"
		description="Markdownコードブロック内のMermaidコンテンツをクライアントサイドでレンダリングします。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/astro-d2"
		title="astro-d2"
		description="D2のMarkdownコードブロックをダイアグラムに変換します。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-links"
		title="starlight-links"
		description="StarlightのMarkdownおよびMDXコンテンツリンクにIntelliSenseを提供するVisual Studio Code拡張機能です。"
	/>
	<LinkCard
		href="https://docs.contentisland.net/templates/starlight/"
		title="contentisland-cli"
		description="StarlightプロジェクトをContent Island Headless CMSに接続・同期して、ドキュメントを編集・管理します。"
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-sidebar-topics-dropdown"
		title="starlight-sidebar-topics-dropdown"
		description="ドキュメントページを複数のサブページに分割し、サイドバーのドロップダウンメニューで切り替えられるようにします。"
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-save-file-component"
		title="starlight-save-file-component"
		description="Starlightサイト上にダウンロードアセットへのリンクをすばやく表示します。"
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-contributor-list"
		title="starlight-contributor-list"
		description="プロジェクトの全コントリビューター一覧を表示します。"
	/>
</CardGrid>


================================================
FILE: docs/src/content/docs/ja/resources/showcase.mdx
================================================
---
title: Starlightショーケース
description: Starlightで作成されたサイトをチェックしましょう!
sidebar:
  label: サイト紹介
---

:::tip[自分のものを追加しよう!]
Starlightでサイトを作成しましたか?このページにリンクを追加する[PRを作成](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md#showcase)しましょう!
:::

## サイト

import ShowcaseSites from '~/components/showcase-sites.astro';

Starlightはすでに本番環境で使用されています。以下は、ウェブ上のいくつかのサイトです。

<ShowcaseSites />

[Starlightを使用しているパブリックなプロジェクトのGitHubリポジトリ](https://github.com/withastro/starlight/network/dependents)を確認してみてください。


================================================
FILE: docs/src/content/docs/ja/resources/themes.mdx
================================================
---
title: テーマ
description: Starlightのコミュニティテーマでドキュメントをスタイルできます
tableOfContents: false
sidebar:
  order: 2
head:
  - tag: style
    content: |
      body { --sl-content-width: 66.75rem; }
---

import ThemeGrid from '~/components/theme-grid.astro';

テーマはStarlightのプラグインで、[カスタムCSS](/ja/guides/css-and-tailwind/)、[コンポーネントのオーバーライド](/ja/guides/overriding-components/)、その他の新機能などによってサイトの見た目を変更します。

## コミュニティテーマ

コミュニティが作成したテーマをインストールすると、サイトの見た目や使い心地を手早くカスタマイズできます。

以下のリストですべてのテーマをプレビューできるほか、[Starlightテーマのデモサイト](https://starlight-themes.netlify.app/)でインタラクティブに試すこともできます。

<ThemeGrid
	labels={{
		/** テーマ切り替えのアクセシブルラベル。*/
		legend: 'プレビュー',
		/** ダークカラースキームのアクセシブルラベル。*/
		dark: 'ダーク',
		/** ライトカラースキームのアクセシブルラベル。*/
		light: 'ライト',
	}}
	themes={[
		{
			title: 'Starlight Rapide',
			description:
				'Visual Studio CodeのVitesseテーマに着想を得たStarlightテーマです。',
			href: 'https://starlight-theme-rapide.vercel.app/',
			previews: { light: 'rapide-light.png', dark: 'rapide-dark.png' },
		},
		{
			title: 'Starlight Obsidian',
			description:
				'Obsidian Publishサイトのスタイルに着想を得たStarlightテーマです。',
			href: 'https://fevol.github.io/starlight-theme-obsidian/',
			previews: { light: 'obsidian-light.png', dark: 'obsidian-dark.png' },
		},
		{
			title: 'Catppuccin for Starlight',
			description: 'やさしいパステル調のStarlight向けテーマです。',
			href: 'https://starlight.catppuccin.com/',
			previews: { light: 'catppuccin-light.png', dark: 'catppuccin-dark.png' },
		},
		{
			title: 'Ion',
			description: '洗練されたモダンなStarlightテーマです。',
			href: 'https://louisescher.github.io/starlight-ion-theme/',
			previews: { light: 'ion-light.png', dark: 'ion-dark.png' },
		},
		{
			title: 'Starlight Black',
			description: 'shadcnのドキュメントに着想を得たStarlightテーマです。',
			href: 'https://starlight-theme-black.vercel.app/',
			previews: { light: 'black-light.png', dark: 'black-dark.png' },
		},
		{
			title: 'Starlight Flexoki',
			description:
				'Flexokiカラーパレットに基づく、あたたかく親しみやすいテーマです。',
			href: 'https://delucis.github.io/starlight-theme-flexoki/',
			previews: { light: 'flexoki-light.png', dark: 'flexoki-dark.png' },
		},
		{
			title: 'Starlight Nova',
			description: 'モダンで美しいStarlightテーマです。',
			href: 'https://starlight-theme-nova.pages.dev/',
			previews: { light: 'nova-light.png', dark: 'nova-dark.png' },
		},
		{
			title: 'Starlight Next.js',
			description: 'Next.jsのドキュメントに着想を得たStarlightテーマです。',
			href: 'https://starlight-theme-next.trueberryless.org/',
			previews: { light: 'nextjs-light.png', dark: 'nextjs-dark.png' },
		},
		{
			title: 'Starlight Galaxy',
			description:
				'ドキュメントや教育コンテンツの公開に特化したAstro Starlightテーマです。',
			href: 'https://frostybee.github.io/starlight-theme-galaxy/',
			previews: { light: 'galaxy-light.png', dark: 'galaxy-dark.png' },
		},
		{
			title: 'Starlight Page',
			description:
				'スムーズなフロートインアニメーションを備えた直感的でモダンなStarlightテーマです。',
			href: 'https://pelagornis-page.netlify.app/',
			previews: { light: 'page-light.png', dark: 'page-dark.png' },
		},
		{
			title: 'Starlight Gruvbox',
			description: 'レトロでグルーヴィなStarlightテーマです。',
			href: 'https://starlight-theme-gruvbox.otterlord.dev/',
			previews: { light: 'gruvbox-light.png', dark: 'gruvbox-dark.png' },
		},
		{
			title: 'Starlight Six',
			description:
				'Six TechnologyによるクリーンでモダンなStarlightテーマです。',
			href: 'https://six-tech.github.io/Six.StarlightTheme/',
			previews: { light: 'six-light.png', dark: 'six-dark.png' },
		},
	]}
/>

:::tip[あなたのテーマを追加しませんか?]
Starlightテーマを作成しましたか?このページにあなたのテーマを追加するPRを作成してください!
[PRを開く](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md#themes)
:::


================================================
FILE: docs/src/content/docs/ko/404.md
================================================
---
title: 페이지를 찾을 수 없습니다.
template: splash
editUrl: false
lastUpdated: false
hero:
  title: '404'
  tagline: <strong>Houston, 문제가 생겼어요.</strong> 페이지를 찾을 수 없습니다.<br>URL을 다시 확인해보거나 검색을 사용해보세요.
  actions:
    - text: 홈으로 이동
      icon: right-arrow
      link: /ko/
      variant: primary
---


================================================
FILE: docs/src/content/docs/ko/components/asides.mdx
================================================
---
title: 보조 내용
description: Starlight에서 보조 내용을 사용하여 페이지의 주요 콘텐츠와 함께 보조 정보를 표시하는 방법을 알아보세요.
---

import { Aside } from '@astrojs/starlight/components';

페이지의 주요 콘텐츠와 함께 보조 정보를 표시하려면 `<Aside>` 컴포넌트를 사용합니다.

import Preview from '~/components/component-preview.astro';

<Preview>

<Aside slot="preview">
    필수적이지 않은 보충 정보는 `<Aside>`에 포함하세요.
</Aside>

</Preview>

## 가져오기

```tsx
import { Aside } from '@astrojs/starlight/components';
```

## 사용

`<Aside>` 컴포넌트를 사용하여 보조 내용 (“admonitions” 또는 “callouts”이라고도 함)을 표시합니다.

`<Aside>`에는 보조 내용의 색상, 아이콘 및 기본 제목을 제어하는 선택적 [`type`](#type) 속성이 있을 수 있습니다.

<Preview>

````mdx
import { Aside } from '@astrojs/starlight/components';

<Aside>보조 내용의 콘텐츠입니다.</Aside>

<Aside type="caution">몇 가지 주의해야 할 내용입니다.</Aside>

<Aside type="tip">

보조 내용에는 다른 콘텐츠도 지원됩니다.

```js
// 예시 코드 스니펫.
```

</Aside>

<Aside type="danger">비밀번호를 다른 사람에게 알려주지 마세요.</Aside>
````

<Fragment slot="markdoc">

````markdoc
{% aside %}
보조 내용의 콘텐츠입니다.
{% /aside %}

{% aside type="caution" %}
몇 가지 주의해야 할 내용입니다.
{% /aside %}

{% aside type="tip" %}
보조 내용에는 다른 콘텐츠도 지원됩니다.

```js
// 예시 코드 스니펫.
```
{% /aside %}

{% aside type="danger" %}
비밀번호를 다른 사람에게 알려주지 마세요.
{% /aside %}
````

</Fragment>

<Fragment slot="preview">

    <Aside>보조 내용의 콘텐츠입니다.</Aside>

    <Aside type="caution">몇 가지 주의해야 할 내용입니다.</Aside>

    <Aside type="tip">

    보조 내용에는 다른 콘텐츠도 지원됩니다.

    ```js
    // 예시 코드 스니펫.
    ```

    </Aside>

    <Aside type="danger">비밀번호를 다른 사람에게 알려주지 마세요.</Aside>

</Fragment>

</Preview>

Starlight는 또한 `<Aside>` 컴포넌트의 대안으로 Markdown 및 MDX에서 보조 내용을 렌더링하기 위한 사용자 정의 구문을 제공합니다.
사용자 정의 구문에 대한 자세한 내용은 [“Markdown에서 콘텐츠 작성하기”](/ko/guides/authoring-content/#보조-내용) 가이드를 참조하세요.

### 사용자 정의 제목 사용

[`title`](#title) 속성을 사용하여 보조 내용의 기본 제목을 재정의합니다.

<Preview>

```mdx 'title="조심하세요!"'
import { Aside } from '@astrojs/starlight/components';

<Aside type="caution" title="조심하세요!">
	사용자 정의 제목을 *사용하는* 경고 보조 내용입니다.
</Aside>
```

<Fragment slot="markdoc">

```markdoc 'title="조심하세요!"'
{% aside type="caution" title="조심하세요!" %}
사용자 정의 제목을 *사용하는* 경고 보조 내용입니다.
{% /aside %}
```

</Fragment>

<Aside slot="preview" type="caution" title="조심하세요!">
	사용자 정의 제목을 *사용하는* 경고 보조 내용입니다.
</Aside>

</Preview>

### 사용자 정의 아이콘 사용

[Starlight의 기본 제공 아이콘 중 하나](/ko/reference/icons/#모든-아이콘)의 이름으로 설정된 [`icon`](#icon) 속성을 사용하여 기본 아이콘을 재정의합니다.

<Preview>

```mdx 'icon="starlight"'
import { Aside } from '@astrojs/starlight/components';

<Aside type="tip" icon="starlight">
	사용자 정의 아이콘을 *사용하는* 보조 팁입니다.
</Aside>
```

<Fragment slot="markdoc">

```markdoc 'icon="starlight"'
{% aside type="tip" icon="starlight" %}
사용자 정의 아이콘을 *사용하는* 보조 팁입니다.
{% /aside %}
```

</Fragment>

<Aside slot="preview" type="tip" icon="starlight">
	사용자 정의 아이콘을 *사용하는* 보조 팁입니다.
</Aside>

</Preview>

## `<Aside>` 속성

**구현:** [`Aside.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Aside.astro)

`<Aside>` 컴포넌트는 다음과 같은 속성을 허용합니다:

### `type`

**타입:** `'note' | 'tip' | 'caution' | 'danger'`  
**기본값:** `'note'`

표시할 보조 내용의 유형입니다:

- `note` 보조 내용은 파란색이며 정보 아이콘을 표시합니다 (기본값).
- `tip` 보조 내용은 보라색이며 로켓 아이콘을 표시합니다.
- `caution` 보조 내용은 노란색이며 삼각형 경고 아이콘을 표시합니다.
- `danger` 보조 내용은 빨간색이며 팔각형 경고 아이콘을 표시합니다.

### `title`

**타입:** `string`

표시할 보조 내용의 제목입니다.
`title`이 설정되어 있지 않으면 현재 보조 내용의 `type`이 기본 제목으로 사용됩니다.

### `icon`

**타입:** [`StarlightIcon`](/ko/reference/icons/#starlighticon-타입)

보조 내용은 [Starlight의 기본 제공 아이콘 중 하나](/ko/reference/icons/#모든-아이콘)의 이름으로 설정된 `icon` 속성을 포함할 수 있습니다.


================================================
FILE: docs/src/content/docs/ko/components/badges.mdx
================================================
---
title: 배지
description: Starlight에서 배지를 사용하여 추가 정보를 표시하는 방법을 알아보세요.
---

import { Badge } from '@astrojs/starlight/components';

상태나 카테고리와 같은 작은 정보를 표시하려면 `<Badge>` 컴포넌트를 사용합니다.

import Preview from '~/components/component-preview.astro';

<Preview>

<Badge slot="preview" text="새 항목" />

</Preview>

## 가져오기

```tsx
import { Badge } from '@astrojs/starlight/components';
```

## 사용

`<Badge>` 컴포넌트를 사용하여 배지를 표시하고 표시할 콘텐츠를 `<Badge>` 컴포넌트의 [`text`](#text) 속성에 전달합니다.

기본적으로 배지는 사이트의 테마 강조 색상을 사용합니다.
기본적으로 제공되는 배지 색상을 사용하려면 [`variant`](#variant) 속성을 지원되는 값 중 하나로 설정하세요.

<Preview>

```mdx
import { Badge } from '@astrojs/starlight/components';

- <Badge text="노트" variant="note" />
- <Badge text="성공" variant="success" />
- <Badge text="팁" variant="tip" />
- <Badge text="주의" variant="caution" />
- <Badge text="위험" variant="danger" />
```

<Fragment slot="markdoc">

```markdoc
- {% badge text="노트" variant="note" /%}
- {% badge text="성공" variant="success" /%}
- {% badge text="팁" variant="tip" /%}
- {% badge text="주의" variant="caution" /%}
- {% badge text="위험" variant="danger" /%}
```

</Fragment>

<Fragment slot="preview">
	- <Badge text="노트" variant="note" />
	- <Badge text="성공" variant="success" />
	- <Badge text="팁" variant="tip" />
	- <Badge text="주의" variant="caution" />
	- <Badge text="위험" variant="danger" />
</Fragment>

</Preview>

### 다른 크기 사용

[`size`](#size) 속성을 사용하여 배지 텍스트의 크기를 조절할 수 있습니다.

<Preview>

```mdx /size="\w+"/
import { Badge } from '@astrojs/starlight/components';

- <Badge text="새 항목" size="small" />
- <Badge text="개선된 새 항목" size="medium" />
- <Badge text="더 큰 개선된 새 항목" size="large" />
```

<Fragment slot="markdoc">

```markdoc /size="\w+"/
- {% badge text="새 항목" size="small" /%}
- {% badge text="개선된 새 항목" size="medium" /%}
- {% badge text="더 큰 개선된 새 항목" size="large" /%}
```

</Fragment>

<Fragment slot="preview">
	- <Badge text="새 항목" size="small" />
	- <Badge text="개선된 새 항목" size="medium" />
	- <Badge text="더 큰 개선된 새 항목" size="large" />
</Fragment>

</Preview>

### 배지 사용자 정의

`class` 또는 `style`과 같은 다른 `<span>` 속성을 사용자 정의 CSS와 함께 사용하여 배지를 사용자 정의합니다.

<Preview>

```mdx "style={{ fontStyle: 'italic' }}"
import { Badge } from '@astrojs/starlight/components';

<Badge text="사용자 정의" variant="success" style={{ fontStyle: 'italic' }} />
```

<Fragment slot="markdoc">

```markdoc 'style="font-style: italic;"'
{% badge text="사용자 정의" variant="success" style="font-style: italic;" /%}
```

</Fragment>

<Badge
	slot="preview"
	text="사용자 정의"
	variant="success"
	style={{ fontStyle: 'italic' }}
/>

</Preview>

## `<Badge>` 속성

**구현:** [`Badge.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Badge.astro)

`<Badge>` 컴포넌트는 다음 속성과 [기타 `<span>` 속성](https://developer.mozilla.org/ko/docs/Web/HTML/Global_attributes)도 허용합니다:

### `text`

**필수**  
**타입:** `string`

배지에 표시할 텍스트 콘텐츠입니다.

### `variant`

**타입:** `'note' | 'danger' | 'success' | 'caution' | 'tip' | 'default'`  
**기본값:** `'default'`

사용할 배지 색상 변형: `note` (파란색), `tip` (보라색), `danger` (빨간색), `caution` (오렌지색), `success` (초록색), `default` (테마 강조 색상).

### `size`

**타입:** `'small' | 'medium' | 'large'`

표시할 배지의 크기를 정의합니다.


================================================
FILE: docs/src/content/docs/ko/components/card-grids.mdx
================================================
---
title: 카드 그리드
description: Starlight에서 여러 카드를 그리드로 묶는 방법을 알아보세요.
sidebar:
  order: 4
---

import { Card, CardGrid, LinkCard } from '@astrojs/starlight/components';

여러 개의 [`<Card>`](/ko/components/cards/) 또는 [`<LinkCard>`](/ko/components/link-cards/) 컴포넌트를 그리드에 래핑하려면 `<CardGrid>` 컴포넌트를 사용합니다.

import Preview from '~/components/component-preview.astro';

<Preview>

<CardGrid slot="preview">
	<Card title="별" icon="star">
		시리우스, 베가, 베텔게우스
	</Card>
	<Card title="달" icon="moon">
		이오, 유로파, 가니메데
	</Card>
</CardGrid>

</Preview>

## 가져오기

```tsx
import { CardGrid } from '@astrojs/starlight/components';
```

## 사용

### 카드 그룹화

충분한 공간이 있을 때 여러 개의 [`<Card>`](/ko/components/cards/) 컴포넌트를 `<CardGrid>` 컴포넌트로 그룹화하여 나란히 표시합니다.

<Preview>

```mdx {3,10}
import { Card, CardGrid } from '@astrojs/starlight/components';

<CardGrid>
	<Card title="확인하세요" icon="open-book">
		강조하고 싶은 흥미로운 콘텐츠.
	</Card>
	<Card title="기타 기능" icon="information">
		공유하고 싶은 추가 정보.
	</Card>
</CardGrid>
```

<Fragment slot="markdoc">

```markdoc {1,9}
{% cardgrid %}
{% card title="확인하세요" icon="open-book" %}
강조하고 싶은 흥미로운 콘텐츠.
{% /card %}

{% card title="기타 기능" icon="information" %}
공유하고 싶은 추가 정보.
{% /card %}
{% /cardgrid %}
```

</Fragment>

<CardGrid slot="preview">
	<Card title="확인하세요" icon="open-book">
		강조하고 싶은 흥미로운 콘텐츠.
	</Card>
	<Card title="기타 기능" icon="information">
		공유하고 싶은 추가 정보.
	</Card>
</CardGrid>

</Preview>

### 링크 카드 그룹화

충분한 공간이 있을 때 여러 개의 [`<LinkCard>`](/ko/components/link-cards/) 컴포넌트를 `<CardGrid>` 컴포넌트를 사용하여 그룹화하여 나란히 표시합니다.

<Preview>

```mdx {3,6}
import { LinkCard, CardGrid } from '@astrojs/starlight/components';

<CardGrid>
	<LinkCard
		title="Markdown으로 콘텐츠 작성"
		href="/ko/guides/authoring-content/"
	/>
	<LinkCard title="컴포넌트" href="/ko/components/using-components/" />
</CardGrid>
```

<Fragment slot="markdoc">

```markdoc {1,5}
{% cardgrid %}
{% linkcard title="Markdown으로 콘텐츠 작성" href="/ko/guides/authoring-content/" /%}

{% linkcard title="컴포넌트" href="/ko/components/using-components/" /%}
{% /cardgrid %}
```

</Fragment>

<CardGrid slot="preview">
	<LinkCard
		title="Markdown으로 콘텐츠 작성"
		href="/ko/guides/authoring-content/"
	/>
	<LinkCard title="컴포넌트" href="/ko/components/using-components/" />
</CardGrid>

</Preview>

### 카드를 엇갈리게 배치

그리드의 두 번째 열을 수직으로 이동하여 시각적 흥미를 더하려면 `<CardGrid>` 컴포넌트에 [`stagger`](#stagger) 속성을 추가합니다.

이 속성은 홈 페이지에서 프로젝트의 주요 기능을 표시하는 데 유용합니다.

<Preview>

```mdx "stagger"
import { Card, CardGrid } from '@astrojs/starlight/components';

<CardGrid stagger>
	<Card title="확인하세요" icon="open-book">
		강조하고 싶은 흥미로운 콘텐츠.
	</Card>
	<Card title="기타 기능" icon="information">
		공유하고 싶은 추가 정보.
	</Card>
</CardGrid>
```

<Fragment slot="markdoc">

```markdoc "stagger=true"
{% cardgrid stagger=true %}
{% card title="확인하세요" icon="open-book" %}
강조하고 싶은 흥미로운 콘텐츠.
{% /card %}

{% card title="기타 기능" icon="information" %}
공유하고 싶은 추가 정보.
{% /card %}
{% /cardgrid %}
```

</Fragment>

<CardGrid slot="preview" stagger>
	<Card title="확인하세요" icon="open-book">
		강조하고 싶은 흥미로운 콘텐츠.
	</Card>
	<Card title="기타 기능" icon="information">
		공유하고 싶은 추가 정보.
	</Card>
</CardGrid>

</Preview>

## `<CardGrid>` 속성

**구현:** [`CardGrid.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/CardGrid.astro)

`<CardGrid>` 컴포넌트는 다음과 같은 속성을 허용합니다:

### `stagger`

**타입:** `boolean`

그리드에 카드를 엇갈리게 배치할지 여부를 정의합니다.


================================================
FILE: docs/src/content/docs/ko/components/cards.mdx
================================================
---
title: 카드
description: Starlight에서 카드를 사용하여 상자에 콘텐츠를 표시하는 방법을 알아보세요.
sidebar:
  order: 2
---

import { Card } from '@astrojs/starlight/components';

Starlight의 스타일과 일치하는 상자에 콘텐츠를 표시하려면 `<Card>` 컴포넌트를 사용합니다.

import Preview from '~/components/component-preview.astro';

<Preview>

<Card slot="preview" title="달" icon="moon">
	이오, 유로파, 가니메데
</Card>

</Preview>

## 가져오기

```tsx
import { Card } from '@astrojs/starlight/components';
```

## 사용

`<Card>` 컴포넌트를 사용하여 카드를 표시하고 카드의 [`title`](#title)을 입력합니다.

<Preview>

```mdx
import { Card } from '@astrojs/starlight/components';

<Card title="확인하세요">강조하고 싶은 흥미로운 콘텐츠.</Card>
```

<Fragment slot="markdoc">

```markdoc
{% card title="확인하세요" %}
강조하고 싶은 흥미로운 콘텐츠.
{% /card %}
```

</Fragment>

<Card slot="preview" title="확인하세요">
	강조하고 싶은 흥미로운 콘텐츠.
</Card>

</Preview>

### 카드에 아이콘 추가

[Starlight 내장 아이콘 중 하나](/ko/reference/icons/#모든-아이콘)의 이름으로 설정된 [`icon`](#icon) 속성을 사용하여 카드에 아이콘을 포함하세요.

<Preview>

```mdx 'icon="star"'
import { Card } from '@astrojs/starlight/components';

<Card title="별" icon="star">
	시리우스, 베가, 베텔게우스
</Card>
```

<Fragment slot="markdoc">

```markdoc 'icon="star"'
{% card title="별" icon="star" %}
시리우스, 베가, 베텔게우스
{% /card %}
```

</Fragment>

<Card slot="preview" title="별" icon="star">
	시리우스, 베가, 베텔게우스
</Card>

</Preview>

### 카드 그룹화

[`<CardGrid>`](/ko/components/card-grids/) 컴포넌트를 사용해 카드를 그룹화하여 공간이 충분할 때 여러 카드를 나란히 표시합니다.
예시는 [“카드 그룹화”](/ko/components/card-grids/#카드-그룹화) 가이드를 참조하세요.

## `<Card>` 속성

**구현:** [`Card.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Card.astro)

`<Card>` 컴포넌트는 다음과 같은 속성을 허용합니다:

### `title`

**필수**  
**타입:** `string`

표시할 카드의 제목입니다.

### `icon`

**타입:** `string`

카드에는 [Starlight 내장 아이콘 중 하나](/ko/reference/icons/#모든-아이콘)의 이름으로 설정된 `icon` 속성을 포함할 수 있습니다.


================================================
FILE: docs/src/content/docs/ko/components/code.mdx
================================================
---
title: 코드
description: Markdown 코드 블록 없이 Starlight에서 구문 강조 표시된 코드를 표시하는 방법을 알아보세요.
---

import { Code } from '@astrojs/starlight/components';

`<Code>` 컴포넌트는 구문이 강조 표시된 코드를 렌더링합니다.
예를 들어 파일, 데이터베이스, API와 같은 외부 소스에서 가져온 데이터를 렌더링할 때와 같이 [Markdown 코드 블록](/ko/guides/authoring-content/#코드-블록)을 사용할 수 없을 때 유용합니다.

import Preview from '~/components/component-preview.astro';

<Preview>

<Code
	slot="preview"
	code={`## 환영합니다

**우주에서** 하는 인사!`}
lang="md"
title="example.md"
ins={3}
/>

</Preview>

## 가져오기

```tsx
import { Code } from '@astrojs/starlight/components';
```

## 사용

외부 소스에서 가져온 코드를 표시할 때와 같은 상황에서 구문이 강조된 코드를 렌더링하려면 `<Code>` 컴포넌트를 사용합니다.

[Expressive Code “Code 컴포넌트” 문서](https://expressive-code.com/key-features/code-component/)에서 `<Code>` 컴포넌트 사용 방법과 사용 가능한 속성 목록에 대한 자세한 내용을 확인할 수 있습니다.

<Preview>

```mdx
import { Code } from '@astrojs/starlight/components';

export const exampleCode = `console.log('이는 파일이나 CMS에서 올 수 있습니다!');`;
export const fileName = 'example.js';
export const highlights = ['파일', 'CMS'];

<Code code={exampleCode} lang="js" title={fileName} mark={highlights} />
```

<Fragment slot="markdoc">

```markdoc
{% code
   code="console.log('이는 파일이나 CMS에서 올 수 있습니다!');"
   lang="js"
   title="example.js"
   meta="'파일' 'CMS'" /%}
```

</Fragment>

export const exampleCode = `console.log('이는 파일이나 CMS에서 올 수 있습니다!');`;
export const fileName = 'example.js';
export const highlights = ['파일', 'CMS'];

<Code
	slot="preview"
	code={exampleCode}
	lang="js"
	title={fileName}
	mark={highlights}
/>

</Preview>

### 가져온 코드 표시

MDX 파일 및 Astro 컴포넌트에서 [Vite의 `?raw` 가져오기 접미사](https://ko.vite.dev/guide/assets#importing-asset-as-string)를 사용하여 코드 파일을 문자열로 가져옵니다.
그런 다음 이 가져온 문자열을 `<Code>` 컴포넌트에 전달하여 페이지에 포함할 수 있습니다.

<Preview>

```mdx "?raw"
# src/content/docs/example.mdx

import { Code } from '@astrojs/starlight/components';
import importedCode from '/tsconfig.json?raw';

<Code code={importedCode} lang="json" title="tsconfig.json" />
```

import importedCode from '../../../../../../examples/basics/tsconfig.json?raw';

<Code slot="preview" code={importedCode} lang="json" title="tsconfig.json" />

</Preview>

## `<Code>` 속성

**구현:** [`Code.astro`](https://github.com/expressive-code/expressive-code/blob/main/packages/astro-expressive-code/components/Code.astro)

`<Code>` 컴포넌트는 [Expressive Code “Code 컴포넌트” 문서](https://expressive-code.com/key-features/code-component/#available-props)에 문서화된 모든 속성을 허용합니다.


================================================
FILE: docs/src/content/docs/ko/components/file-tree.mdx
================================================
---
title: 파일 트리
description: Starlight에서 파일 아이콘과 접을 수 있는 하위 디렉터리를 사용하여 디렉터리 구조를 표시하는 방법을 알아보세요.
---

import { FileTree } from '@astrojs/starlight/components';

파일 아이콘과 접을 수 있는 하위 디렉터리가 있는 디렉터리의 구조를 표시하려면 `<FileTree>` 컴포넌트를 사용하세요.

import Preview from '~/components/component-preview.astro';

<Preview>

<FileTree slot="preview">

- astro.config.mjs **중요** 파일
- package.json
- README.md
- src
  - components
    - **Header.astro**
  - …
- pages/

</FileTree>

</Preview>

## 가져오기

```tsx
import { FileTree } from '@astrojs/starlight/components';
```

## 사용

`<FileTree>` 컴포넌트를 사용하여 파일 아이콘과 접을 수 있는 하위 디렉터리가 있는 파일 트리를 표시합니다.

`<FileTree>`에서 [순서가 지정되지 않은 Markdown 목록](https://www.markdownguide.org/basic-syntax/#unordered-lists)을 사용하여 파일 및 디렉터리의 구조를 지정하세요.
중첩된 목록을 사용하여 하위 디렉터리를 생성하거나 목록 항목 끝에 `/`를 추가하여 특정 내용이 없는 디렉터리로 렌더링합니다.

<Preview>

```mdx
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- astro.config.mjs
- package.json
- src
  - components
    - Header.astro
    - Title.astro
  - pages/

</FileTree>
```

<Fragment slot="markdoc">

```markdoc
{% filetree %}
- astro.config.mjs
- package.json
- src
  - components
    - Header.astro
    - Title.astro
  - pages/
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- astro.config.mjs
- package.json
- src
  - components
    - Header.astro
    - Title.astro
  - pages/

</FileTree>

</Preview>

### 항목 강조 표시

파일이나 디렉터리의 이름을 굵은 글씨로 만들어 눈에 띄게 만드세요 (예: `**README.md**`).

<Preview>

```mdx {7}
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src
  - components
    - **Header.astro**
    - Title.astro

</FileTree>
```

<Fragment slot="markdoc">

```markdoc {4}
{% filetree %}
- src
  - components
    - **Header.astro**
    - Title.astro
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- src
  - components
    - **Header.astro**
    - Title.astro

</FileTree>

</Preview>

### 주석 추가

이름 뒤에 텍스트를 더 추가하여 파일이나 디렉터리에 주석을 추가합니다.
주석에서 굵게 및 기울임꼴과 같은 인라인 Markdown 서식이 지원됩니다.

<Preview>

```mdx {7}
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src
  - components
    - Header.astro **중요** 파일
    - Title.astro

</FileTree>
```

<Fragment slot="markdoc">

```markdoc {4}
{% filetree %}
- src
  - components
    - Header.astro **중요** 파일
    - Title.astro
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- src
  - components
    - Header.astro **중요** 파일
    - Title.astro

</FileTree>

</Preview>

### 자리 표시자 추가

`...` 또는 `…`을 이름으로 사용하여 자리 표시자 파일과 디렉터리를 추가합니다.
이는 폴더에 더 많은 항목이 포함될 수 있음을 모든 항목을 일일이 명시하지 않고도 독자에게 알려주는 데 유용할 수 있습니다.

<Preview>

```mdx {8}
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src
  - components
    - Header.astro
    - …

</FileTree>
```

<Fragment slot="markdoc">

```markdoc {5}
{% filetree %}
- src
  - components
    - Header.astro
    - …
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- src
  - components
    - Header.astro
    - …

</FileTree>

</Preview>

### 특수 문자 이스케이프

파일 이름에 밑줄 또는 공백과 같은 특수 문자가 포함된 경우, 파일 이름을 코드 백틱으로 감싸서 이스케이프하세요.

<Preview>

```mdx
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- `__init__.py`
- `Hello world.txt`
- **`READ ME FIRST.md`**

</FileTree>
```

<Fragment slot="markdoc">

```markdoc
{% filetree %}
- `__init__.py`
- `Hello world.txt`
- **`READ ME FIRST.md`**
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- `__init__.py`
- `Hello world.txt`
- **`READ ME FIRST.md`**

</FileTree>

</Preview>

## `<FileTree>` 속성

**구현:** [`FileTree.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/FileTree.astro)

`<FileTree>` 컴포넌트는 어떤 속성도 허용하지 않습니다.


================================================
FILE: docs/src/content/docs/ko/components/icons.mdx
================================================
---
title: 아이콘
description: Starlight에서 아이콘을 표시하는 방법을 알아보세요.
---

import { Icon } from '@astrojs/starlight/components';

Starlight의 [기본 제공 아이콘 세트](/ko/reference/icons/#모든-아이콘)의 아이콘을 표시하려면 `<Icon>` 컴포넌트를 사용하세요.

import Preview from '~/components/component-preview.astro';

<Preview>

<Icon
	slot="preview"
	name="open-book"
	color="var(--sl-color-text-accent)"
	size="4rem"
/>

</Preview>

## 가져오기

```tsx
import { Icon } from '@astrojs/starlight/components';
```

## 사용

`<Icon>` 컴포넌트를 사용하여 아이콘을 표시합니다.
아이콘에는 [Starlight의 기본 제공 아이콘 중 하나](/ko/reference/icons/#모든-아이콘)로 설정된 [`name`](#name)이 필요하며, 화면 리더에 컨텍스트를 제공하기 위해 선택적으로 [`label`](#label)을 포함할 수 있습니다.

<Preview>

```mdx
import { Icon } from '@astrojs/starlight/components';

<Icon name="star" />
<Icon name="starlight" label="Starlight 로고" />
```

<Fragment slot="markdoc">

```markdoc
{% icon name="star" /%}
{% icon name="starlight" label="Starlight 로고" /%}
```

</Fragment>

<Fragment slot="preview">
	<Icon name="star" />
	<Icon name="starlight" label="Starlight 로고" />
</Fragment>

</Preview>

### 아이콘 사용자 정의

CSS 단위와 색상 값을 사용하여 아이콘의 모양을 조정하는 데 [`size`](#size) 및 [`color`](#color) 속성을 사용할 수 있습니다.
[`class`](#class) 속성을 사용하여 아이콘에 사용자 정의 CSS 클래스를 추가할 수 있습니다.

<Preview>

```mdx
import { Icon } from '@astrojs/starlight/components';

<Icon name="star" color="goldenrod" size="2rem" />
<Icon name="rocket" color="var(--sl-color-text-accent)" />
```

<Fragment slot="markdoc">

```markdoc
{% icon name="star" color="goldenrod" size="2rem" /%}
{% icon name="rocket" color="var(--sl-color-text-accent)" /%}
```

</Fragment>

<Fragment slot="preview">
	<Icon name="star" color="goldenrod" size="2rem" />
	<Icon name="rocket" color="var(--sl-color-text-accent)" />
</Fragment>

</Preview>

## `<Icon>` 속성

**구현:** [`Icon.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Icon.astro)

`<Icon>` 컴포넌트는 다음 속성을 허용합니다:

### `name`

**필수**  
**타입:** [`StarlightIcon`](/ko/reference/icons/#starlighticon-타입)

표시할 아이콘의 이름을 [Starlight의 기본 제공 아이콘 중 하나](/ko/reference/icons/#모든-아이콘)로 설정합니다.

### `label`

**타입:** `string`

화면 리더와 같은 보조 기술에 컨텍스트를 제공하기 위한 선택적 레이블입니다.

`label`을 설정하지 않으면 보조 기술에서 아이콘이 완전히 숨겨집니다.
이 경우 아이콘 없이도 문맥을 이해할 수 있는지 확인하세요.
예를 들어 아이콘만 포함된 링크는 `label` 속성을 **포함해야** 액세스할 수 있지만, 링크에 텍스트가 포함되어 있고 아이콘이 순전히 장식용인 경우에는 `label`을 생략해도 괜찮습니다.

### `size`

**타입:** `string`

CSS 단위를 사용한 아이콘 크기입니다.

### `color`

**타입:** `string`

CSS 색상 값을 사용하는 아이콘의 색상입니다.

### `class`

**타입:** `string`

아이콘에 추가할 사용자 정의 CSS 클래스입니다.


================================================
FILE: docs/src/content/docs/ko/components/link-buttons.mdx
================================================
---
title: 링크 버튼
description: 시각적으로 뚜렷한 콜투액션 링크를 위해 Starlight에서 링크 버튼을 만드는 방법을 알아보세요.
---

import { LinkButton } from '@astrojs/starlight/components';

시각적으로 뚜렷한 콜투액션 링크를 표시하려면 `<LinkButton>` 컴포넌트를 사용합니다.

import Preview from '~/components/component-preview.astro';

<Preview>

<LinkButton slot="preview" href="/ko/getting-started/">
	문서 읽기
</LinkButton>

</Preview>

## 가져오기

```tsx
import { LinkButton } from '@astrojs/starlight/components';
```

## 사용

시각적으로 구분되는 콜투액션 링크를 표시하려면 `<LinkButton>` 컴포넌트를 사용합니다.
링크 버튼은 가장 관련성이 높거나 실행 가능한 콘텐츠로 사용자를 안내하는 데 유용하며 랜딩 페이지에서 자주 사용됩니다.

`<LinkButton>`에는 [`href`](#href) 속성이 필요합니다.
선택적으로 `primary` (기본값), `secondary`, `minimal`로 설정할 수 있는 [`variant`](#variant) 속성을 사용하여 링크 버튼의 모양을 사용자 정의합니다.

<Preview>

```mdx
import { LinkButton } from '@astrojs/starlight/components';

<LinkButton href="/ko/getting-started/">시작하기</LinkButton>
<LinkButton href="/ko/reference/configuration/" variant="secondary">
	구성 참조
</LinkButton>
```

<Fragment slot="markdoc">

```markdoc
{% linkbutton href="/ko/getting-started/" %}시작하기{% /linkbutton %}

{% linkbutton href="/ko/reference/configuration/" variant="secondary" %}
구성 참조
{% /linkbutton %}
```

</Fragment>

<Fragment slot="preview">
	<LinkButton href="/ko/getting-started/">시작하기</LinkButton>
	<LinkButton href="/ko/reference/configuration/" variant="secondary">
		구성 참조
	</LinkButton>
</Fragment>

</Preview>

### 링크 버튼에 아이콘 추가

[Starlight의 내장 아이콘 중 하나](/ko/reference/icons/#모든-아이콘)의 이름으로 설정된 [`icon`](#icon) 속성을 사용하여 링크 버튼에 아이콘을 포함시킵니다.

텍스트 앞에 아이콘을 배치하기 위해 [`iconPlacement`](#iconplacement) 속성을 `start`로 설정할 수 있습니다 (기본값은 `end`).

<Preview>

```mdx {6-7}
import { LinkButton } from '@astrojs/starlight/components';

<LinkButton
	href="https://docs.astro.build/ko"
	variant="secondary"
	icon="external"
	iconPlacement="start"
>
	관련: Astro
</LinkButton>
```

<Fragment slot="markdoc">

```markdoc {4-5}
{% linkbutton
   href="https://docs.astro.build/ko"
	 variant="secondary"
	 icon="external"
	 iconPlacement="start" %}
관련: Astro
{% /linkbutton %}
```

</Fragment>

<LinkButton
	slot="preview"
	href="https://docs.astro.build/ko"
	variant="secondary"
	icon="external"
	iconPlacement="start"
>
	관련: Astro
</LinkButton>

</Preview>

## `<LinkButton>` 속성

**구현:** [`LinkButton.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/LinkButton.astro)

`<LinkButton>` 컴포넌트는 다음 속성과 [기타 `<a>` 속성](https://developer.mozilla.org/ko/docs/Web/HTML/Element/a)도 허용합니다:

### `href`

**필수**  
**타입:** `string`

링크 버튼이 가리키는 URL입니다.

### `variant`

**타입:** `'primary' | 'secondary' | 'minimal'`  
**기본값:** `'primary'`

링크 버튼의 모양입니다.
테마 강조 색상을 사용하여 눈에 잘 띄는 콜투액션 링크를 만들려면 `primary`, 덜 눈에 띄는 링크를 만들려면 `secondary`, 최소한의 스타일을 적용한 링크를 만들려면 `minimal`로 설정합니다.

### `icon`

**타입:** `string`

링크 버튼에는 [Starlight의 기본 제공 아이콘 중 하나](/ko/reference/icons/#모든-아이콘)의 이름으로 설정된 `icon` 속성을 포함할 수 있습니다.

### `iconPlacement`

**타입:** `'start' | 'end'`  
**기본값:** `'end'`

링크 버튼 텍스트에 상대적인 아이콘의 위치를 결정합니다.


================================================
FILE: docs/src/content/docs/ko/components/link-cards.mdx
================================================
---
title: 링크 카드
description: Starlight에서 링크를 카드로 눈에 잘 띄게 표시하는 방법을 알아보세요.
sidebar:
  order: 3
---

import { LinkCard } from '@astrojs/starlight/components';

다른 페이지로 연결되는 링크를 눈에 잘 띄게 표시하려면 `<LinkCard>` 컴포넌트를 사용하세요.

import Preview from '~/components/component-preview.astro';

<Preview>

<LinkCard
	slot="preview"
	title="Starlight 사용자 정의"
	description="사용자 정의 스타일, 글꼴 등을 사용하여 스타라이트 사이트를 나만의 사이트로 만드는 방법을 알아보세요."
	href="/ko/guides/customization/"
/>

</Preview>

## 가져오기

```tsx
import { LinkCard } from '@astrojs/starlight/components';
```

## 사용

`<LinkCard>` 컴포넌트를 사용하여 링크를 눈에 잘 띄게 표시합니다.
각 `<LinkCard>`에는 [`title`](#title) 및 [`href`](#href) 속성이 필요합니다.

<Preview>

```mdx
import { LinkCard } from '@astrojs/starlight/components';

<LinkCard
	title="Markdown으로 콘텐츠 작성"
	href="/ko/guides/authoring-content/"
/>
```

<Fragment slot="markdoc">

```markdoc
{% linkcard title="Markdown으로 콘텐츠 작성" href="/ko/guides/authoring-content/" /%}
```

</Fragment>

<LinkCard
	slot="preview"
	title="Markdown으로 콘텐츠 작성"
	href="/ko/guides/authoring-content/"
/>

</Preview>

### 링크 설명 추가

[`description`](#description) 속성을 사용하여 링크 카드에 간단한 설명을 추가합니다.

<Preview>

```mdx {6}
import { LinkCard } from '@astrojs/starlight/components';

<LinkCard
	title="국제화"
	href="/ko/guides/i18n/"
	description="여러 언어를 지원하도록 Starlight를 구성합니다."
/>
```

<Fragment slot="markdoc">

```markdoc {4}
{% linkcard
   title="국제화"
	 href="/ko/guides/i18n/"
	 description="여러 언어를 지원하도록 Starlight를 구성합니다." /%}
```

</Fragment>

<LinkCard
	slot="preview"
	title="국제화"
	href="/ko/guides/i18n/"
	description="여러 언어를 지원하도록 Starlight를 구성합니다."
/>

</Preview>

### 링크 카드 그룹화

[`<CardGrid>`](/ko/components/card-grids/) 컴포넌트를 사용해 여러 개의 링크 카드를 그룹화하여 충분한 공간이 있을 때 나란히 표시합니다.
예시는 [“링크 카드 그룹화”](/ko/components/card-grids/#링크-카드-그룹화) 가이드를 참조하세요.

## `<LinkCard>` 속성

**구현:** [`LinkCard.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/LinkCard.astro)

`<LinkCard>` 컴포넌트는 다음 속성과 기타 [`<a>` 요소의 속성](https://developer.mozilla.org/ko/docs/Web/HTML/Element/a)도 허용합니다:

### `title`

**필수**  
**타입:** `string`

표시할 링크 카드의 제목입니다.

### `href`

**필수**  
**타입:** `string`

카드와 상호 작용할 때 연결할 URL입니다.

### `description`

**타입:** `string`

제목 아래에 표시할 설명 (선택 사항)입니다.


================================================
FILE: docs/src/content/docs/ko/components/steps.mdx
================================================
---
title: 단계
description: Starlight에서 단계별 가이드를 만들기 위해 작업의 번호가 매겨진 목록에 스타일을 지정하는 방법을 알아보세요.
---

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

번호가 매겨진 작업 목록에 스타일을 지정하여 단계별 가이드를 만들려면 `<Steps>` 컴포넌트를 사용하세요.

import Preview from '~/components/component-preview.astro';

<Preview>

<Steps slot="preview">

1. 새 Starlight 프로젝트를 만듭니다:

   <Tabs syncKey="pkg">

   <TabItem label="npm">

   ```sh
   npm create astro@latest -- --template starlight
   ```

   </TabItem>

   <TabItem label="pnpm">

   ```sh
   pnpm create astro --template starlight
   ```

   </TabItem>

   <TabItem label="Yarn">

   ```sh
   yarn create astro --template starlight
   ```

   </TabItem>

   </Tabs>

2. 첫 번째 문서 페이지를 작성합니다.

</Steps>

</Preview>

## 가져오기

```tsx
import { Steps } from '@astrojs/starlight/components';
```

## 사용

`<Steps>` 컴포넌트를 사용하여 번호가 매겨진 작업 목록의 스타일을 지정합니다.
이는 각 단계를 명확하게 강조해야 하는 보다 복잡한 단계별 가이드에 유용합니다.

표준 Markdown 정렬 목록을 `<Steps>`로 묶습니다.
모든 일반적인 Markdown 구문은 `<Steps>` 내에서 적용 가능합니다.

<Preview>

````mdx
import { Steps } from '@astrojs/starlight/components';

<Steps>

1. 컴포넌트를 MDX 파일로 가져옵니다.

   ```js
   import { Steps } from '@astrojs/starlight/components';
   ```

2. 순서가 매겨진 목록 항목을 `<Steps>`로 묶습니다.

</Steps>
````

<Fragment slot="markdoc">

````markdoc
{% steps %}

1. 컴포넌트를 MDX 파일로 가져옵니다.

   ```js
   import { Steps } from '@astrojs/starlight/components';
   ```

2. 순서가 매겨진 목록 항목을 `<Steps>`로 묶습니다.

{% /steps %}
````

</Fragment>

<Steps slot="preview">

1. 컴포넌트를 MDX 파일로 가져옵니다.

   ```js
   import { Steps } from '@astrojs/starlight/components';
   ```

2. 순서가 매겨진 목록 항목을 `<Steps>`로 묶습니다.

</Steps>

</Preview>

## `<Steps>` 속성

**구현:** [`Steps.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Steps.astro)

`<Steps>` 컴포넌트는 어떤 속성도 허용하지 않습니다.


================================================
FILE: docs/src/content/docs/ko/components/tabs.mdx
================================================
---
title: 탭
description: Starlight에서 탭 인터페이스를 만들어 동등한 정보를 그룹화하는 방법을 알아보세요.
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

탭 인터페이스를 만들려면 `<Tabs>` 및 `<TabItem>` 컴포넌트를 사용합니다.
탭은 사용자가 여러 옵션 중 하나만 확인해야 하는 경우 동등한 정보를 그룹화하는 데 유용합니다.

import Preview from '~/components/component-preview.astro';

<Preview>

<Tabs slot="preview">
	<TabItem label="별">시리우스, 베가, 베텔게우스</TabItem>
	<TabItem label="달">이오, 유로파, 가니메데</TabItem>
</Tabs>

</Preview>

## 가져오기

```tsx
import { Tabs, TabItem } from '@astrojs/starlight/components';
```

## 사용

탭 인터페이스는 `<Tabs>` 및 `<TabItem>` 컴포넌트를 사용하여 표시합니다.
각 `<TabItem>`에는 사용자에게 표시할 [`label`](#label)이 있어야 합니다.

<Preview>

```mdx
import { Tabs, TabItem } from '@astrojs/starlight/components';

<Tabs>
	<TabItem label="별">시리우스, 베가, 베텔게우스</TabItem>
	<TabItem label="달">이오, 유로파, 가니메데</TabItem>
</Tabs>
```

<Fragment slot="markdoc">

```markdoc
{% tabs %}
{% tabitem label="별" %}
시리우스, 베가, 베텔게우스
{% /tabitem %}

{% tabitem label="달" %}
이오, 유로파, 가니메데
{% /tabitem %}
{% /tabs %}
```

</Fragment>

<Tabs slot="preview">
	<TabItem label="별">시리우스, 베가, 베텔게우스</TabItem>
	<TabItem label="달">이오, 유로파, 가니메데</TabItem>
</Tabs>

</Preview>

### 탭 동기화

[`syncKey`](#synckey) 속성을 추가하여 여러 탭 그룹을 동기화된 상태로 유지합니다.

`syncKey` 값이 같은 페이지의 모든 `<Tabs>`는 동일한 활성 레이블을 표시합니다.
이렇게 하면 독자가 운영 체제나 패키지 관리자 등을 한 번 선택하면 페이지 탐색 간 선택한 내용이 유지되는 것을 확인할 수 있습니다.

관련 탭을 동기화하려면 각 `<Tabs>` 컴포넌트에 동일한 `syncKey` 속성을 추가하고 모두 동일한 `<TabItem>` 레이블을 사용하는지 확인하세요.

<Preview>

```mdx 'syncKey="별자리"'
import { Tabs, TabItem } from '@astrojs/starlight/components';

_별:_

<Tabs syncKey="별자리">
	<TabItem label="오리온자리">벨라트릭스, 리겔, 베텔게우스</TabItem>
	<TabItem label="쌍둥이자리">폴룩스, 캐스터 A, 캐스터 B</TabItem>
</Tabs>{' '}

_외계 행성:_

<Tabs syncKey="별자리">
	<TabItem label="오리온자리">HD 34445 b, 글리제 179 b, Wasp-82 b</TabItem>
	<TabItem label="쌍둥이자리">폴룩스 b, HAT-P-24b, HD 50554 b</TabItem>
</Tabs>
```

<Fragment slot="markdoc">

```markdoc 'syncKey="별자리"'
_별:_

{% tabs syncKey="별자리" %}
{% tabitem label="오리온자리" %}
벨라트릭스, 리겔, 베텔게우스
{% /tabitem %}

{% tabitem label="쌍둥이자리" %}
폴룩스, 캐스터 A, 캐스터 B
{% /tabitem %}
{% /tabs %}

_외계 행성:_

{% tabs syncKey="별자리" %}
{% tabitem label="오리온자리" %}
HD 34445 b, 글리제 179 b, Wasp-82 b
{% /tabitem %}

{% tabitem label="쌍둥이자리" %}
폴룩스 b, HAT-P-24b, HD 50554 b
{% /tabitem %}
{% /tabs %}
```

</Fragment>

<Fragment slot="preview">

_별:_

<Tabs syncKey="별자리">
	<TabItem label="오리온자리">벨라트릭스, 리겔, 베텔게우스</TabItem>
	<TabItem label="쌍둥이자리">폴룩스, 캐스터 A, 캐스터 B</TabItem>
</Tabs>{' '}

_외계 행성:_

<Tabs syncKey="별자리">
	<TabItem label="오리온자리">HD 34445 b, 글리제 179 b, Wasp-82 b</TabItem>
	<TabItem label="쌍둥이자리">폴룩스 b, HAT-P-24b, HD 50554 b</TabItem>
</Tabs>

</Fragment>

</Preview>

### 탭에 아이콘 추가

[Starlight의 내장 아이콘 중 하나](/ko/reference/icons/#모든-아이콘)의 이름으로 설정된 [`icon`](#icon) 속성을 사용하여 탭 항목에 아이콘을 포함하면 레이블 옆에 아이콘이 표시됩니다.

<Preview>

```mdx /icon="\w+"/
import { Tabs, TabItem } from '@astrojs/starlight/components';

<Tabs>
	<TabItem label="별" icon="star">
		시리우스, 베가, 베텔게우스
	</TabItem>
	<TabItem label="달" icon="moon">
		이오, 유로파, 가니메데
	</TabItem>
</Tabs>
```

<Fragment slot="markdoc">

```markdoc /icon="\w+"/
{% tabs %}
{% tabitem label="별" icon="star" %}
시리우스, 베가, 베텔게우스
{% /tabitem %}

{% tabitem label="달" icon="moon" %}
이오, 유로파, 가니메데
{% /tabitem %}
{% /tabs %}
```

</Fragment>

<Tabs slot="preview">
	<TabItem label="별" icon="star">
		시리우스, 베가, 베텔게우스
	</TabItem>
	<TabItem label="달" icon="moon">
		이오, 유로파, 가니메데
	</TabItem>
</Tabs>

</Preview>

## `<Tabs>` 속성

**구현:** [`Tabs.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Tabs.astro)

`<Tabs>` 컴포넌트는 여러 개의 `<TabItem>` 컴포넌트를 그룹화하고 다음과 같은 속성을 허용합니다:

### `syncKey`

**타입:** `string`

여러 페이지에서 여러 탭 그룹을 동기화하는 데 사용되는 키입니다.

## `<TabItem>` 속성

**구현:** [`TabItem.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/TabItem.astro)

탭 세트는 탭 항목으로 구성되며, 각 항목에는 다음과 같은 속성이 있습니다:

### `label`

**필수**  
**타입:** `string`

탭 항목에는 탭에 표시될 텍스트로 설정된 `label` 속성이 포함되어야 합니다.

### `icon`

**타입:** `string`

각 탭 항목에는 [Starlight의 내장 아이콘 중 하나](/ko/reference/icons/#모든-아이콘)의 이름으로 설정된 `icon` 속성을 포함하여 레이블 옆에 아이콘을 표시할 수 있습니다.


================================================
FILE: docs/src/content/docs/ko/components/using-components.mdx
================================================
---
title: 컴포넌트 사용
description: Starlight와 함께 MDX 및 Markdoc에서 컴포넌트 사용.
sidebar:
  order: 1
---

컴포넌트를 사용하면 쉽고 일관되게 UI 조각이나 스타일을 재사용할 수 있습니다.
링크 카드나 YouTube 삽입 등을 예로 들 수 있습니다.
Starlight는 [MDX](https://mdxjs.com/) 및 [Markdoc](https://markdoc.dev/) 파일에서 컴포넌트 사용을 지원하며 사용할 수 있는 몇 가지 공통 컴포넌트를 제공합니다.

[Astro 문서에서 컴포넌트 구축에 대해 자세히 알아보세요](https://docs.astro.build/ko/basics/astro-components/).

## MDX에서 컴포넌트 사용

MDX 파일에서 컴포넌트를 가져온 다음 JSX 태그로 렌더링하여 사용할 수 있습니다.
이는 HTML 태그처럼 보이지만 `import` 문에 있는 이름과 일치하는 대문자로 시작합니다.

```mdx
---
# src/content/docs/example.mdx
title: 내 문서에 오신 것을 환영합니다
---

import { Icon } from '@astrojs/starlight/components';
import CustomCard from '../../components/CustomCard.astro';

<Icon name="open-book" />

<CustomCard>컴포넌트에는 **중첩된 콘텐츠**가 포함될 수도 있습니다.</CustomCard>
```

Starlight는 Astro로 구동되므로 [지원되는 UI 프레임워크(React, Preact, Svelte, Vue, Solid, Alpine)](https://docs.astro.build/ko/guides/framework-components/)로 빌드된 컴포넌트를 MDX 파일에 추가할 수 있습니다.
Astro 문서에서 [MDX에서 컴포넌트 사용](https://docs.astro.build/ko/guides/integrations-guide/mdx/#mdx에서-컴포넌트-사용)에 대해 자세히 알아보세요.

## Markdoc에서 컴포넌트 사용

[Markdoc 설정 가이드](/ko/guides/authoring-content/#markdoc)에 따라 Markdoc에서 콘텐츠 작성에 대한 지원을 추가하세요.

Starlight Markdoc 프리셋을 사용하면 Starlight의 내장 컴포넌트를 Markdoc의 `{% %}` 태그 구문과 함께 사용할 수 있습니다.
MDX와 달리 Markdoc에서는 컴포넌트를 가져올 필요가 없습니다.
다음 예시는 Starlight의 [카드 컴포넌트](/ko/components/cards/)를 Markdoc 파일에서 렌더링합니다:

```markdoc
---
# src/content/docs/example.mdoc
title: 내 문서에 오신 것을 환영합니다
---

{% card title="별" icon="star" %}
시리우스, 베가, 베텔게우스
{% /card %}
```

Markdoc 파일에서 컴포넌트를 사용하는 방법에 대한 자세한 내용은 [Astro Markdoc 통합 문서](https://docs.astro.build/ko/guides/integrations-guide/markdoc/#컴포넌트-렌더링)를 참조하세요.

## 내장 컴포넌트

Starlight는 일반적인 문서 사용 사례를 위한 내장 컴포넌트를 제공합니다.
이러한 컴포넌트는 MDX 파일의 `@astrojs/starlight/components` 패키지와 Markdoc 파일의 [Starlight Markdoc 프리셋](/ko/guides/authoring-content/#markdoc)에서 사용할 수 있습니다.

사용 가능한 컴포넌트 목록과 사용 방법은 사이드바를 참조하세요.

## Starlight 스타일과의 호환성

Starlight는 요소 사이에 여백을 추가하는 등 Markdown 콘텐츠에 기본 스타일을 적용합니다.
이러한 스타일이 컴포넌트의 모양과 충돌하는 경우 컴포넌트에 `not-content` 클래스를 추가하여 비활성화하세요.

```astro 'class="not-content"'
---
// src/components/Example.astro
---

<div class="not-content">
	<p>Starlight의 기본 콘텐츠 스타일링의 영향을 받지 않습니다.</p>
</div>
```

## 컴포넌트 속성

컴포넌트 자체에서 내보내지 않더라도 컴포넌트에서 허용하는 `Props`를 참조하려면 `astro/types`의 [`ComponentProps`](https://docs.astro.build/ko/guides/typescript/#componentprops-타입) 타입을 사용합니다.
이는 기존 컴포넌트를 래핑하거나 확장할 때 유용할 수 있습니다.

다음 예시는 `ComponentProps`를 사용하여 Starlight의 내장 `Badge` 컴포넌트가 허용하는 속성의 타입을 가져옵니다:

```astro
---
// src/components/Example.astro
import type { ComponentProps } from 'astro/types';
import { Badge } from '@astrojs/starlight/components';

type BadgeProps = ComponentProps<typeof Badge>;
---
```


================================================
FILE: docs/src/content/docs/ko/environmental-impact.md
================================================
---
title: 친환경 문서
description: Starlight가 어떻게 친환경 문서 사이트를 구축하고 탄소 배출량을 줄이는 데 도움이 되는지 알아보세요.
---

웹 산업이 기후에 미치는 영향에 대한 추정치는 전 세계 탄소 배출량의 [2%][sf] ~ [4%][bbc] 범위이며, 이는 항공 산업의 배출량과 비슷합니다.
웹 사이트의 생태학적 영향을 계산하기 위한 여러 복잡한 요소가 존재하지만, 이 가이드는 문서 사이트의 환경적 영향을 줄이기 위한 몇 가지 팁을 포함합니다.

좋은 소식은 Starlight를 선택하는 것이 좋은 시작이라는 것입니다.
Website Carbon Calculator에 따르면 이 사이트는 [테스트된 웹페이지의 98%보다 깨끗하며][sl-carbon] 페이지 방문당 0.01g의 CO₂를 배출합니다.

## 페이지 크기

웹페이지가 전송하는 데이터가 많을수록 더 많은 에너지 자원이 필요합니다.
2023년 4월, [HTTP Archive의 데이터][http]에 따르면 웹페이지 중앙값은 2,000KB 이상을 다운로드해야 했습니다.

Starlight는 최대한 가벼운 페이지를 구축합니다.
예를 들어, 사용자는 첫 방문 시 50KB 미만의 압축 데이터를 다운로드하게 됩니다. 이는 HTTP Archive 중앙값의 2.5%에 불과합니다.
좋은 캐싱 전략을 사용하면 후속 탐색에서 10KB 정도만 다운로드할 수 있습니다.

### 이미지

Starlight는 좋은 기준을 제공하지만 문서 페이지에 이미지를 추가하면 페이지의 크기가 빠르게 증가할 수 있습니다.
Starlight는 Astro의 [최적화된 자산 지원][assets]을 사용하여 Markdown 및 MDX 파일에서 추가한 로컬 이미지를 최적화합니다.

### UI 컴포넌트

React 또는 Vue와 같은 UI 프레임워크로 구축된 컴포넌트는 페이지에 많은 양의 JavaScript를 추가합니다.
Starlight는 Astro 기반으로 구축되었고, Astro 자체 컴포넌트는 [Astro 아일랜드][islands] 덕분에 **기본적으로 클라이언트 측 JavaScript가 전혀 로드되지 않습니다**.

### 캐싱

캐싱은 브라우저가 이미 다운로드한 데이터를 저장하고 재사용하는 기간을 제어하는 ​​데 사용됩니다.
좋은 캐싱 전략은 콘텐츠가 변경될 때 새 콘텐츠를 최대한 빨리 얻을 수 있도록 하며, 변경되지 않은 동일한 콘텐츠를 무의미하게 반복해서 다운로드하는 것을 방지합니다.

캐싱을 구성하는 가장 일반적인 방법은 [`Cache-Control` HTTP 헤더][cache]를 사용하는 것입니다.
Starlight를 사용할 때 `/_astro/` 디렉터리의 모든 항목에 대해 긴 캐시 시간을 설정할 수 있습니다.
이 디렉터리에는 불필요한 다운로드를 줄여 영원히 안전하게 캐시할 수 있는 CSS, JavaScript 및 기타 번들 자산이 포함되어 있습니다.

```
Cache-Control: public, max-age=604800, immutable
```

캐싱을 구성하는 방법은 웹 호스트에 따라 다릅니다. 예를 들어 Vercel은 구성 없이 이 캐싱 전략을 적용하는 반면, 프로젝트에 `public/_headers` 파일을 추가하여 [Netlify용 사용자 정의 헤더][ntl-headers]를 설정할 수 있습니다.

```
/_astro/*
  Cache-Control: public
  Cache-Control: max-age=604800
  Cache-Control: immutable
```

[cache]: https://csswizardry.com/2019/03/cache-control-for-civilians/
[ntl-headers]: https://docs.netlify.com/routing/headers/

## 전력 소비

웹 페이지가 구축되는 방식은 사용자 장치를 실행하는 데 필요한 전력에 영향을 미칠 수 있습니다. Starlight는 최소한의 JavaScript를 사용하여 사용자의 휴대폰, 태블릿 또는 컴퓨터가 페이지를 로드하고 렌더링하는 데 필요한 전력을 감소시킵니다.

분석 추적 스크립트나 동영상 삽입과 같은 JavaScript 중심 콘텐츠를 추가할 때 페이지의 전력 사용량이 증가할 수 있으므로 주의하세요.
분석이 필요한 경우 [Cabin][cabin], [Fathom][fathom] 또는 [Plausible][plausible]과 같은 가벼운 옵션을 선택하는 것이 좋습니다.
YouTube 및 Vimeo와 같은 동영상 삽입은 [상호 작용 시 동영상 로드][lazy-video]를 통해 개선될 수 있습니다.
[`astro-embed`][embed]와 같은 패키지는 일반적인 서비스에 도움이 될 수 있습니다.

:::tip[알고 계셨나요?]

JavaScript를 분석하고 컴파일하는 것은 브라우저가 수행해야 하는 비용이 가장 많이 드는 작업 중 하나입니다.
동일한 크기의 JPEG 이미지를 렌더링하는 것을 다른 언어들과 비교해보면 [JavaScript는 처리하는 데 30배 이상 더 오래 걸릴 수 있습니다][cost-of-js].

:::

[cabin]: https://withcabin.com/
[fathom]: https://usefathom.com/
[plausible]: https://plausible.io/
[lazy-video]: https://web.dev/iframe-lazy-loading/
[embed]: https://www.npmjs.com/package/astro-embed
[cost-of-js]: https://medium.com/dev-channel/the-cost-of-javascript-84009f51e99e

## 호스팅

웹 페이지가 호스팅되는 위치는 문서 사이트가 얼마나 친환경적인지에 큰 영향을 미칠 수 있습니다.
데이터 센터와 서버 팜은 높은 전력 소비와 물의 집중적 사용 등으로 인해 생태학적으로 큰 영향을 미칠 수 있습니다.

재생 가능 에너지를 사용하는 호스트를 선택하면 사이트의 탄소 배출량이 줄어듭니다. [Green Web Directory][gwb]는 호스팅 회사를 찾는 데 도움이 되는 도구 중 하나입니다.

[gwb]: https://www.thegreenwebfoundation.org/directory/

## 비교

다른 문서 프레임워크와 어떻게 비교되는지 궁금하십니까?
[Website Carbon Calculator][wcc]를 사용한 이러한 테스트는 서로 다른 도구로 작성된 유사한 페이지를 비교합니다.

| 프레임워크                  | 페이지 방문당 CO₂ | 등급 |
| --------------------------- | ----------------- | :--: |
| [Starlight][sl-carbon]      | 0.01g             |  A+  |
| [Sphinx][sx-carbon]         | 0.01g             |  A+  |
| [Read the Docs][rtd-carbon] | 0.03g             |  A+  |
| [VitePress][vp-carbon]      | 0.04g             |  A   |
| [docsify][dy-carbon]        | 0.05g             |  A   |
| [mdBook][md-carbon]         | 0.05g             |  A   |
| [Nextra][nx-carbon]         | 0.05g             |  A   |
| [MkDocs][mk-carbon]         | 0.07g             |  A   |
| [Fumadocs][fs-carbon]       | 0.07g             |  A   |
| [Docusaurus][ds-carbon]     | 0.10g             |  B   |
| [Docus][dc-carbon]          | 0.11g             |  B   |
| [GitBook][gb-carbon]        | 0.42g             |  F   |
| [Mintlify][mt-carbon]       | 0.48g             |  F   |

<small>2025년 8월 7일에 수집된 데이터. 최신 수치를 보려면 링크를 클릭하세요.</small>

[sl-carbon]: https://www.websitecarbon.com/website/starlight-astro-build-getting-started/
[vp-carbon]: https://www.websitecarbon.com/website/vitepress-dev-guide-what-is-vitepress/
[dc-carbon]: https://www.websitecarbon.com/website/docus-dev-en-getting-started-project-structure/
[sx-carbon]: https://www.websitecarbon.com/website/sphinx-doc-org-en-master-usage-quickstart-html/
[mk-carbon]: https://www.websitecarbon.com/website/mkdocs-org-getting-started/
[md-carbon]: https://www.websitecarbon.com/website/rust-lang-github-io-mdbook/
[nx-carbon]: https://www.websitecarbon.com/website/nextra-site-docs-docs-theme-start/
[fs-carbon]: https://www.websitecarbon.com/website/fumadocs-dev-docs-ui/
[dy-carbon]: https://www.websitecarbon.com/website/docsify-js-org/
[ds-carbon]: https://www.websitecarbon.com/website/docusaurus-io-docs/
[rtd-carbon]: https://www.websitecarbon.com/website/docs-readthedocs-io-en-stable-index-html/
[gb-carbon]: https://www.websitecarbon.com/website/gitbook-com-docs/
[mt-carbon]: https://www.websitecarbon.com/website/mintlify-com-docs-quickstart/

## 더 많은 자료

### 도구

- [Website Carbon Calculator][wcc]
- [GreenFrame](https://greenframe.io/)
- [Ecograder](https://ecograder.com/)
- [WebPageTest Carbon Control](https://www.webpagetest.org/carbon-control/)
- [Ecoping](https://ecoping.earth/)

### 기사 및 강연

- [“더 친환경적인 웹 구축”](https://youtu.be/EfPoOt7T5lg), Michelle Barker의 강연
- [“조직 내의 지속 가능한 웹 개발 전략”](https://www.smashingmagazine.com/2022/10/sustainable-web-development-strategies-organization/), Michelle Barker의 기사
- [“모두를 위한 지속 가능한 웹”](https://2021.stateofthebrowser.com/speakers/tom-greenwood/), Tom Greenwood의 강연
- [“웹 콘텐츠가 전력 사용량에 미치는 영향”](https://webkit.org/blog/8970/how-web-content-can-affect-power-usage/), Benjamin Poulain 및 Simon Fraser의 기사

[sf]: https://www.sciencefocus.com/science/what-is-the-carbon-footprint-of-the-internet/
[bbc]: https://www.bbc.com/future/article/20200305-why-your-internet-habits-are-not-as-clean-as-you-think
[http]: https://httparchive.org/reports/state-of-the-web
[assets]: https://docs.astro.build/ko/guides/images/
[islands]: https://docs.astro.build/ko/concepts/islands/
[wcc]: https://www.websitecarbon.com/


================================================
FILE: docs/src/content/docs/ko/getting-started.mdx
================================================
---
title: 시작하기
description: Astro가 제공하는 Starlight를 사용해 문서 사이트를 만드는 방법을 알아보세요.
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

## 새 프로젝트 생성

Starlight는 [Astro](https://astro.build) 프레임워크 위에 구축되었으며, 완전한 기능을 갖춘 문서 테마입니다.
이 가이드는 새 프로젝트를 시작하는 데 도움이 될 것입니다.
기존 Astro 프로젝트에 Starlight를 추가하려면 [수동 설정 지침](/ko/manual-setup/)을 참조하세요.

## 빠른 시작

### 새 프로젝트 생성

터미널에서 다음 명령을 실행하여 새 Astro + Starlight 프로젝트를 생성합니다.

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight
```

</TabItem>
</Tabs>

이 명령은 필요한 파일과 구성을 모두 갖춘 새 [프로젝트 디렉터리](/ko/guides/project-structure/)를 생성합니다.

:::tip[시도 해보기]
브라우저에서 Starlight 사용:
[StackBlitz에서 템플릿 열기](https://stackblitz.com/github/withastro/starlight/tree/main/examples/basics)
:::

### 개발 서버 시작

로컬에서 작업할 때 [Astro의 개발 서버](https://docs.astro.build/ko/reference/cli-reference/#astro-dev)를 사용하면 작업을 미리 볼 수 있으며 변경 시 자동으로 브라우저를 새로 고칠 수 있습니다.

프로젝트 디렉터리에서 다음 명령을 실행하여 개발 서버를 시작합니다.

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm run dev
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dev
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dev
```

</TabItem>
</Tabs>

그러면 로컬 미리보기의 URL이 포함된 메시지가 터미널에 기록됩니다.
사이트 탐색을 시작하려면 이 URL을 여세요.

### 콘텐츠 추가

Starlight는 새로운 콘텐츠를 추가하거나 기존 파일을 가져올 준비가 되어 있습니다!

`src/content/docs/` 디렉터리에 Markdown 파일을 생성하여 사이트에 새 페이지를 추가하세요.

[“페이지”](/ko/guides/pages/) 가이드에서 MDX 및 Markdoc 파일에 대한 파일 기반 라우팅 및 지원에 대해 자세히 알아보세요.

### 다음 단계

- **구성:** [“Starlight 사용자 정의”](/ko/guides/customization/)에서 일반적인 옵션에 대해 알아보세요.
- **탐색:** ["사이드바 탐색"](/ko/guides/sidebar/) 가이드를 사용하여 사이드바를 설정하세요.
- **컴포넌트:** ["컴포넌트"](/ko/components/using-components/) 가이드에서 내장된 카드 컴포넌트, 탭 컴포넌트 등을 찾아보세요.
- **확장:** ["플러그인"](/ko/resources/plugins/) 및 ["테마"](/ko/resources/themes/) 카탈로그에서 커뮤니티 애드온을 살펴보세요.
- **배포:** Astro 문서의 [“사이트 배포”](https://docs.astro.build/ko/guides/deploy/) 가이드를 사용하여 작업을 게시하세요.

## Starlight 업데이트

:::tip
Starlight는 베타 소프트웨어이기 때문에 업데이트와 개선이 자주 이루어질 것입니다.
정기적으로 Starlight를 업데이트하세요!
:::

Starlight는 Astro 통합입니다. 터미널에서 다음 명령을 실행하여 이 패키지와 다른 Astro 패키지를 업데이트할 수 있습니다.

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npx @astrojs/upgrade
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dlx @astrojs/upgrade
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dlx @astrojs/upgrade
```

</TabItem>
</Tabs>

각 릴리스의 전체 변경 사항 목록은 [Starlight 변경 로그](https://github.com/withastro/starlight/blob/main/packages/starlight/CHANGELOG.md)를 참조하세요.

## Starlight 문제 해결

[프로젝트 구성](/ko/reference/configuration/) 및 [개별 페이지 프런트매터 구성](/ko/reference/frontmatter/) 참조 페이지를 사용하여 Starlight 사이트가 올바르게 구성되고 작동하는지 확인하세요.
콘텐츠를 추가하고 Starlight 사이트를 사용자 정의하는 데 도움이 필요하면 사이드바의 가이드를 참조하세요.

이 문서에서 답변을 찾을 수 없다면 완전한 Astro 문서를 확인하기 위해 [Astro 공식 문서](https://docs.astro.build)를 방문하세요.
이 Starlight 테마에서 Astro가 어떻게 작동하는지 이해하는 것은 질문에 대한 해답이 될 것입니다.

[Github issues](https://github.com/withastro/starlight/issues)에서 Starlight의 알려진 문제를 확인할 수 있으며, 활발하고 친근한 커뮤니티인 [Astro Discord](https://astro.build/chat)에서 도음을 받을수도 있습니다! 현재 진행되고 있는 개발 및 기타 주제에 대해 논의하기 위해 `#support` 채널에서 "starlight" 태그를 사용하여 질문을 게시하거나 `#starlight` 채널을 방문하세요.


================================================
FILE: docs/src/content/docs/ko/guides/authoring-content.mdx
================================================
---
title: Markdown으로 콘텐츠 작성
description: Starlight가 지원하는 Markdown 구문의 개요입니다.
---

Starlight는 `.md` 파일에서 제목 및 설명과 같은 메타데이터를 정의하기 위해 [Markdown](https://daringfireball.net/projects/markdown/)의 모든 구문과 프론트매터 [YAML](https://dev.to/paulasantamaria/introduction-to-yaml-125f)을 지원합니다.

해당 파일 형식을 사용하는 경우 Markdown 지원 및 사용법이 다를 수 있으므로 [MDX 문서](https://mdxjs.com/docs/what-is-mdx/#markdown) 또는 [Markdoc 문서](https://markdoc.dev/docs/syntax)를 확인하세요.

## 프런트매터

프런트매터의 값을 설정하여 Starlight의 개별 페이지를 사용자 정의할 수 있습니다.
프런트매터는 다음과 같이 파일 상단에 `---` 구분 기호를 사용하여 설정합니다.

```md title="src/content/docs/example.md"
---
title: 페이지 제목
---

페이지의 콘텐츠는 두 번째 `---` 뒤에 옵니다.
```

모든 페이지에는 최소 하나의 `title`이 포함되어야 합니다.
사용 가능한 모든 필드를 확인하고 사용자 정의 필드를 추가하는 방법을 알아보기 위해 [프런트매터 참조](/ko/reference/frontmatter/)를 확인하세요.

## 인라인 스타일

텍스트는 **굵게**, _기울임꼴_ 또는 ~~취소선~~으로 표시할 수 있습니다.

```md
텍스트는 **굵게**, _기울임꼴_ 또는 ~~취소선~~으로 표시할 수 있습니다.
```

[다른 페이지로 링크](/ko/getting-started/)할 수 있습니다.

```md
[다른 페이지로 링크](/ko/getting-started/)할 수 있습니다.
```

백틱을 사용하여 `인라인 코드`를 강조 표시할 수 있습니다.

```md
백틱을 사용하여 `인라인 코드`를 강조 표시할 수 있습니다.
```

## 이미지

Starlight의 이미지는 [Astro에 내장된 최적화된 자산 지원](https://docs.astro.build/ko/guides/images/)을 사용합니다.

Markdown 및 MDX는 스크린 리더 및 보조 기술에서 사용되는 대체 텍스트가 포함된 이미지를 표시하기 위한 Markdown 구문을 지원합니다.

!["astro"라는 단어가 포함된 행성과 별 그림](https://raw.githubusercontent.com/withastro/docs/main/public/default-og-image.png)

```md
!["astro"라는 단어가 포함된 행성과 별 그림](https://raw.githubusercontent.com/withastro/docs/main/public/default-og-image.png)
```

프로젝트 내 로컬 이미지 파일에 대한 상대 경로도 지원합니다.

```md
// src/content/docs/page-1.md

![우주에 있는 로켓](../../assets/images/rocket.svg)
```

## 제목

제목을 사용하여 콘텐츠를 구조화할 수 있습니다. Markdown의 제목은 줄 시작 부분에 `#` 개수로 나타냅니다.

### Starlight에서 페이지 콘텐츠를 구성하는 방법

Starlight는 페이지 제목을 최상위 제목으로 사용하도록 구성되어 있으며 각 페이지 목차 상단에 "개요" 제목을 포함합니다. 각 페이지를 일반 단락 텍스트 콘텐츠로 시작하고 `<h2>`부터 아래로 페이지 제목을 사용하는 것이 좋습니다.

```md
---
title: Markdown 가이드
description: Starlight에서 Markdown을 사용하는 방법
---

이 페이지는 Starlight에서 Markdown을 사용하는 방법을 설명합니다.

## 인라인 스타일

## 제목
```

### 제목 링크

Markdown에서 제목을 사용하면 자동으로 링크가 제공되므로 페이지의 특정 섹션에 직접 연결할 수 있습니다.

```md
---
title: 내 콘텐츠 페이지
description: Starlight에 내장된 링크를 사용하는 방법
---

## 서론

[나의 결론](#결론)은 같은 페이지 하단에 링크될 수 있습니다.

## 결론

`https://my-site.com/page1/#서론` 서론으로 바로 이동합니다.
```

레벨 2 (`<h2>`) 및 레벨 3 (`<h3>`) 제목이 페이지 목차에 자동으로 나타납니다.

[Astro 공식 문서](https://docs.astro.build/ko/guides/markdown-content/#제목-id)에서 Astro가 제목의 `id`를 처리하는 방법에 대해 자세히 알아보세요.

## 보조 내용

보조 내용은 "admonitions" 또는 "callouts" 라고도 하며, 페이지의 기본 콘텐츠 주변에 보조 정보를 표시하는 데 유용합니다.

Starlight는 보조 내용 렌더링을 위한 사용자 정의 Markdown 구문을 제공합니다. 보조 내용 블록은 내용을 감싸기 위해 세 개의 콜론 `:::`을 사용하며 `note`, `tip`, `caution` 또는 `danger` 타입일 수 있습니다.

다른 Markdown 콘텐츠를 보조 내용 안에 중첩시킬 수도 있지만 짧고 간결한 콘텐츠 덩어리에 가장 적합합니다.

### Note 보조 내용

:::note

Starlight는 [Astro](https://astro.build/)로 구축된 문서 웹사이트 툴킷입니다. 다음 명령으로 시작할 수 있습니다.

```sh
npm create astro@latest -- --template starlight
```

:::

````md
:::note
Starlight는 [Astro](https://astro.build/)로 구축된 문서 웹사이트 툴킷입니다. 다음 명령으로 시작할 수 있습니다.

```sh
npm create astro@latest -- --template starlight
```

:::
````

### 사용자 정의 보조 내용 제목

보조 내용 타입 다음에 대괄호를 사용해 보조 내용의 제목을 지정할 수 있습니다. `:::tip[알고 계셨나요?]`

:::tip[알고 계셨나요?]

Astro는 ["아일랜드 아키텍처"](https://docs.astro.build/ko/concepts/islands/)를 사용하여 더 빠른 웹사이트를 구축할 수 있도록 도와줍니다.
:::

```md
:::tip[알고 계셨나요?]
Astro는 ["아일랜드 아키텍처"](https://docs.astro.build/ko/concepts/islands/)를 사용하여 더 빠른 웹사이트를 구축할 수 있도록 도와줍니다.
:::
```

### 사용자 정의 보조 내용 아이콘

보조 내용 유형 또는 [사용자 정의 제목](#사용자-정의-보조-내용-제목) 뒤에 오는 중괄호에 보조 내용에 대한 사용자 정의 아이콘을 지정할 수 있습니다. (예: `:::tip{icon="heart"}` 또는 `:::tip[알고 계셨나요?]{icon="heart"}`).
아이콘 이름은 [Starlight의 기본 제공 아이콘 중 하나](/ko/reference/icons/#모든-아이콘)의 이름으로 설정해야 합니다.

:::tip{icon="heart"}
Astro는 ["아일랜드 아키텍처"](https://docs.astro.build/ko/concepts/islands/)를 사용하여 더 빠른 웹사이트를 구축할 수 있도록 도와줍니다.
:::

```md
:::tip{icon="heart"}
Astro는 ["아일랜드 아키텍처"](https://docs.astro.build/ko/concepts/islands/)를 사용하여 더 빠른 웹사이트를 구축할 수 있도록 도와줍니다.
:::
```

### 더 많은 보조 내용 타입

Caution과 Danger 보조 내용은 실수하기 쉬운 세부 사항에 대해 사용자를 집중시키는 데 도움이 됩니다. 이러한 기능을 많이 사용하고 있다면, 문서화중인 내용을 다시 디자인하는 것이 좋습니다.

:::caution
당신이 멋진 문서 사이트를 원하지 않는다면 [Starlight](/ko/)는 필요하지 않을 수도 있습니다.
:::

:::danger
Starlight의 유용한 기능 덕분에 사용자의 생산성이 향상되고 제품을 더 쉽게 사용할 수 있습니다.

- 쉬운 탐색
- 사용자 구성 가능한 색상 테마
- [i18n 지원](/ko/guides/i18n/)

:::

```md
:::caution
당신이 멋진 문서 사이트를 원하지 않는다면 [Starlight](/ko/)는 필요하지 않을 수도 있습니다.
:::

:::danger
Starlight의 유용한 기능 덕분에 사용자의 생산성이 향상되고 제품을 더 쉽게 사용할 수 있습니다.

- 쉬운 탐색
- 사용자 구성 가능한 색상 테마
- [i18n 지원](/ko/guides/i18n/)

:::
```

## 인용

> 이것은 인용 구문입니다. 다른 사람의 말이나 문서를 인용할 때 자주 사용됩니다.
>
> 인용은 각 줄의 시작 부분에 `>`를 사용하여 나타낼 수 있습니다.

```md
> 이것은 인용 구문입니다. 다른 사람의 말이나 문서를 인용할 때 자주 사용됩니다.
>
> 인용은 각 줄의 시작 부분에 `>`를 사용하여 나타낼 수 있습니다.
```

## 코드 블록

코드 블록은 시작과 끝 부분에 세 개의 백틱 <code>```</code>이 있는 블록으로 나타냅니다. 시작하는 백틱 뒤에 프로그래밍 언어를 명시할 수 있습니다.

```js
// 구문 강조 기능이 있는 Javascript 코드입니다.
var fun = function lang(l) {
	dateformat.i18n = require('./lang/' + l);
	return true;
};
```

````md
```js
// 구문 강조 기능이 있는 Javascript 코드입니다.
var fun = function lang(l) {
	dateformat.i18n = require('./lang/' + l);
	return true;
};
```
````

### Expressive Code 기능

Starlight는 [Expressive Code](https://expressive-code.com/)를 사용하여 코드 블록의 형식 지정 가능성을 확장합니다.
기본적으로 Expressive Code의 텍스트 마커와 창 프레임 플러그인은 활성화되어 있습니다.
코드 블록 렌더링은 Starlight의 [`expressiveCode` 구성 옵션](/ko/reference/configuration/#expressivecode)을 사용하여 구성할 수 있습니다.

#### 텍스트 마커

코드 블록의 시작 줄에 [Expressive Code 텍스트 마커](https://expressive-code.com/key-features/text-markers/)를 사용하여 코드 블록의 특정 줄이나 부분을 강조 표시할 수 있습니다. 전체 줄을 강조 표시하려면 중괄호(`{ }`)를 사용하고, 텍스트 문자열을 강조 표시하려면 따옴표를 사용하세요.

세 가지 강조 스타일이 있습니다. 코드에 주의를 환기시키는 중립, 삽입된 코드를 나타내는 녹색, 삭제된 코드를 나타내는 빨간색입니다.
텍스트와 전체 줄 모두 기본 마커를 사용하거나 `ins=` 및 `del=`과 함께 표시하여 원하는 강조 표시를 생성할 수 있습니다.

Expressive Code는 코드 샘플의 시각적 모습을 사용자 정의하기 위한 여러 옵션을 제공합니다. 이들 중 다수는 예시적인 코드 샘플을 위해 결합될 수 있습니다. 사용 가능한 광범위한 옵션을 보려면 [Expressive Code 문서](https://expressive-code.com/key-features/text-markers/#configuration)를 살펴보세요. 가장 일반적인 예시 중 일부는 다음과 같습니다.

- [`{ }` 마커를 사용하여 전체 줄과 줄 범위를 표시합니다.](https://expressive-code.com/key-features/text-markers/#marking-full-lines--line-ranges)

  ```js {2-3}
  function demo() {
  	// 이 줄(#2)과 다음 줄이 강조 표시됩니다.
  	return '이 줄은 이 스니펫의 라인 #3입니다.';
  }
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```js {2-3}
  function demo() {
  	// 이 줄(#2)과 다음 줄이 강조 표시됩니다.
  	return '이 줄은 이 스니펫의 라인 #3입니다.';
  }
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```js {% meta="{2-3}" %}
  function demo() {
  	// 이 줄(#2)과 다음 줄이 강조 표시됩니다.
  	return '이 줄은 이 스니펫의 라인 #3입니다.';
  }
  ```
  ````

  </TabItem>

  </Tabs>

- [`" "` 마커 또는 정규 표현식을 사용하여 텍스트 선택 항목을 표시합니다.](https://expressive-code.com/key-features/text-markers/#marking-individual-text-inside-lines)

  ```js "개별 용어" /정규.*지원됩니다./
  // 개별 용어도 강조 표시할 수 있습니다.
  function demo() {
  	return '정규 표현식도 지원됩니다.';
  }
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```js "개별 용어" /정규.*지원됩니다./
  // 개별 용어도 강조 표시할 수 있습니다.
  function demo() {
  	return '정규 표현식도 지원됩니다.';
  }
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```js {% meta="'개별 용어' /정규.*지원됩니다./" %}
  // 개별 용어도 강조 표시할 수 있습니다.
  function demo() {
  	return '정규 표현식도 지원됩니다.';
  }
  ```
  ````

  </TabItem>

  </Tabs>

- [`ins` 또는 `del`을 사용하여 텍스트나 줄을 삽입 또는 삭제된 것으로 표시합니다.](https://expressive-code.com/key-features/text-markers/#selecting-inline-marker-types-mark-ins-del)

  ```js "return true;" ins="삽입" del="삭제된"
  function demo() {
  	console.log('삽입 및 삭제된 마커 타입입니다.');
  	// return 문은 기본 마커 타입을 사용합니다.
  	return true;
  }
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```js "return true;" ins="삽입" del="삭제된"
  function demo() {
  	console.log('삽입 및 삭제된 마커 타입입니다.');
  	// return 문은 기본 마커 타입을 사용합니다.
  	return true;
  }
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```js {% meta="'return true;' ins='삽입' del='삭제된'" %}
  function demo() {
  	console.log('삽입 및 삭제된 마커 타입입니다.');
  	// return 문은 기본 마커 타입을 사용합니다.
    return true;
  }
  ```
  ````

  </TabItem>

  </Tabs>

- [구문 강조와 `diff` 유사 구문을 결합합니다.](https://expressive-code.com/key-features/text-markers/#combining-syntax-highlighting-with-diff-like-syntax)

  ```diff lang="js"
    function thisIsJavaScript() {
      // 이 전체 블록은 JavaScript로 강조표시됩니다.
      // 그리고 여전히 diff 마커를 추가할 수 있습니다!
  -   console.log('제거할 이전 코드')
  +   console.log('새롭고 빛나는 코드!')
    }
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```diff lang="js"
    function thisIsJavaScript() {
      // 이 전체 블록은 JavaScript로 강조표시됩니다.
      // 그리고 여전히 diff 마커를 추가할 수 있습니다!
  -   console.log('제거할 이전 코드')
  +   console.log('새롭고 빛나는 코드!')
    }
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```diff {% meta="lang='js'" %}
    function thisIsJavaScript() {
      // 이 전체 블록은 JavaScript로 강조표시됩니다.
      // 그리고 여전히 diff 마커를 추가할 수 있습니다!
  -   console.log('제거할 이전 코드')
  +   console.log('새롭고 빛나는 코드!')
    }
  ```
  ````

  </TabItem>

  </Tabs>

#### Frames 및 titles

코드 블록은 창과 같은 프레임 내부에서 렌더링될 수 있습니다.
터미널 창처럼 보이는 프레임은 쉘 스크립팅 언어(예: `bash` 또는 `sh`)에 사용됩니다.
title이 포함된 다른 언어는 코드 편집기 스타일의 프레임에 표시됩니다.

코드 블록의 선택적 제목은 코드 블록을 여는 백틱 및 언어 식별자 뒤에 `title="..."` 속성을 추가하거나 코드 첫 번째 줄에 파일 이름 주석을 추가하여 설정할 수 있습니다.

- [설명과 함께 파일 이름 탭 추가](https://expressive-code.com/key-features/frames/#code-editor-frames)

  ```js
  // my-test-file.js
  console.log('안녕하세요!');
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```js
  // my-test-file.js
  console.log('안녕하세요!');
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````md
  ```js
  // my-test-file.js
  console.log('안녕하세요!');
  ```
  ````

  </TabItem>

  </Tabs>

- [터미널 창에 제목 추가](https://expressive-code.com/key-features/frames/#terminal-frames)

  ```bash title="의존성 설치 중…"
  npm install
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```bash title="의존성 설치 중…"
  npm install
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```bash {% title="의존성 설치 중…" %}
  npm install
  ```
  ````

  </TabItem>

  </Tabs>

- [`frame="none"`으로 창 프레임 비활성화](https://expressive-code.com/key-features/frames/#overriding-frame-types)

  ```bash frame="none"
  echo "bash 언어를 사용해도 터미널로 렌더링되지 않습니다."
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```bash frame="none"
  echo "bash 언어를 사용해도 터미널로 렌더링되지 않습니다."
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```bash {% frame="none" %}
  echo "bash 언어를 사용해도 터미널로 렌더링되지 않습니다."
  ```
  ````

  </TabItem>

  </Tabs>

## Details

Details (“disclosures” 또는 “accordions”이라고도 함)는 즉시 관련이 없는 콘텐츠를 숨기는 데 유용합니다.
사용자는 짧은 요약을 클릭하여 전체 콘텐츠를 확장하고 볼 수 있습니다.

Markdown 콘텐츠에서 표준 HTML인 [`<details>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details) 및 [`<summary>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/summary) 요소를 사용하여 공개 위젯을 만듭니다.

`<details>` 요소에 다른 Markdown 구문을 중첩할 수 있습니다.

<details>
<summary>안드로메다 별자리는 언제 어디서 가장 잘 보입니까?</summary>

[안드로메다 별자리](<https://en.wikipedia.org/wiki/Andromeda_(constellation)>)는 11월 밤하늘의 위도 `+90°`에서 `-40°` 사이에서 가장 잘 보입니다.

</details>

```md
<details>
<summary>안드로메다 별자리는 언제 어디서 가장 잘 보입니까?</summary>

[안드로메다 별자리](<https://en.wikipedia.org/wiki/Andromeda_(constellation)>)는 11월 밤하늘의 위도 `+90°`에서 `-40°` 사이에서 가장 잘 보입니다.

</details>
```

## Footnotes

[각주(Footnotes)](https://www.markdownguide.org/extended-syntax/#footnotes)는 콘텐츠 흐름을 방해하지 않고 간략한 참조나 설명을 추가하는 데 유용합니다. 각주는 페이지 하단에 모아둔 참조 텍스트로 이동하는 번호가 매겨진 위첨자 링크로 나타납니다.

대괄호와 캐럿, 숫자 참조를 사용하여 각주를 정의합니다.

```md
여기에 각주[^1]가 있고 그 뒤에 추가 텍스트가 있습니다.

[^1]: 나의 참조
```

## 기타 일반적인 Markdown 기능

Starlight는 목록 및 테이블과 같은 다른 모든 Markdown 작성 구문을 지원합니다. 모든 Markdown 구문 요소에 대한 간략한 개요는 [Markdown Guide의 Markdown 치트 시트](https://www.markdownguide.org/cheat-sheet/)를 참조하세요.

## 고급 Markdown 및 MDX 구성

Starlight는 remark 및 rehype를 기반으로 구축된 Astro의 Markdown 및 MDX 렌더러를 사용합니다. Astro 구성 파일에 `remarkPlugins` 또는 `rehypePlugins`를 추가하여 사용자 정의 구문 및 동작에 대한 지원을 추가할 수 있습니다. 자세한 내용은 Astro 문서의 [Markdown 플러그인](https://docs.astro.build/ko/guides/markdown-content/#markdown-플러그인)을 참조하세요.

## Markdoc

Starlight는 실험적인 [Astro Markdoc 통합](https://docs.astro.build/ko/guides/integrations-guide/markdoc/)과 Starlight Markdoc 프리셋을 사용하여 Markdoc으로 콘텐츠를 작성할 수 있도록 지원합니다.

### Markdoc으로 새 프로젝트 만들기

`create astro`를 사용하여 사전 구성된 Markdoc이 포함된 새 Starlight 프로젝트를 시작합니다:

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight/markdoc
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight/markdoc
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight/markdoc
```

</TabItem>
</Tabs>

### 기존 프로젝트에 Markdoc 추가하기

이미 Starlight 사이트가 있고 Markdoc을 추가하려는 경우 다음 단계를 따르세요.

<Steps>

1.  Astro의 Markdoc 통합을 추가하세요:

    <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npx astro add markdoc
    ```

    </TabItem>

    <TabItem label="pnpm">

    ```sh
    pnpm astro add markdoc
    ```

    </TabItem>

    <TabItem label="Yarn">

    ```sh
    yarn astro add markdoc
    ```

    </TabItem>

    </Tabs>

2.  Starlight Markdoc 프리셋을 설치합니다:

    <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npm install @astrojs/starlight-markdoc
    ```

    </TabItem>

    <TabItem label="pnpm">

    ```sh
    pnpm add @astrojs/starlight-markdoc
    ```

    </TabItem>

    <TabItem label="Yarn">

    ```sh
    yarn add @astrojs/starlight-markdoc
    ```

    </TabItem>

    </Tabs>

3.  `markdoc.config.mjs`에 Markdoc 구성 파일을 만들고 Starlight Markdoc 프리셋을 사용하세요:

    ```js
    import { defineMarkdocConfig } from '@astrojs/markdoc/config';
    import starlightMarkdoc from '@astrojs/starlight-markdoc';

    export default defineMarkdocConfig({
    	extends: [starlightMarkdoc()],
    });
    ```

</Steps>

Markdoc 구문 및 기능에 대한 자세한 내용은 [Markdoc 문서](https://markdoc.dev/docs/syntax) 또는 [Astro Markdoc 통합 가이드](https://docs.astro.build/ko/guides/integrations-guide/markdoc/)를 참조하세요.

### Markdoc 프리셋 구성

다음은 `starlightMarkdoc()` 프리셋이 허용하는 구성 옵션입니다.

#### `headingLinks`

**타입:** `boolean`  
**기본값:** `true`

제목이 클릭 가능한 앵커 링크와 함께 렌더링될지 여부를 제어합니다. Markdown 및 MDX 파일에 적용되는 [`markdown.headingLinks`](/ko/reference/configuration/#markdown) 옵션과 동일합니다.

```js "headingLinks: false"
export default defineMarkdocConfig({
	// 기본 제목 앵커 링크 지원을 비활성화합니다.
	extends: [starlightMarkdoc({ headingLinks: false })],
});
```


================================================
FILE: docs/src/content/docs/ko/guides/css-and-tailwind.mdx
================================================
---
title: CSS & 스타일링
description: 맞춤형 CSS로 Starlight 사이트의 스타일을 지정하거나 Tailwind CSS와 통합하는 방법을 알아보세요.
---

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

사용자 정의 CSS 파일을 사용하여 Starlight 사이트의 스타일을 지정하거나 Starlight Tailwind 플러그인을 사용할 수 있습니다.

사이트의 기본 스타일을 빠르게 변경하려면 [커뮤니티 테마](/ko/resources/themes/)를 확인하세요.

## 사용자 정의 CSS 스타일

Starlight의 기본 스타일을 수정하거나 확장하기 위한 CSS 파일을 제공하여 사이트에 적용된 스타일을 원하는대로 변경할 수 있습니다.

<Steps>

1. `src/` 디렉터리에 CSS 파일을 추가합니다. 예를 들어, 아래 코드를 통해 페이지 제목을 더 넓게 만들고, 더 큰 텍스트를 사용할 수 있습니다.

   ```css
   /* src/styles/custom.css */
   :root {
   	--sl-content-width: 50rem;
   	--sl-text-5xl: 3.5rem;
   }
   ```

2. `astro.config.mjs` 파일에 있는 Starlight의 `customCss` 배열에 CSS 파일 경로를 추가하세요.

   ```diff lang="js"
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: '사용자 정의 CSS를 사용한 문서',
   			customCss: [
   +				// 사용자 정의 CSS 파일의 상대 경로
   +				'./src/styles/custom.css',
   			],
   		}),
   	],
   });
   ```

</Steps>

사이트를 스타일링하기 위해 Starlight에서 사용되는 모든 CSS 속성을 [`props.css` 파일](https://github.com/withastro/starlight/blob/main/packages/starlight/style/props.css)에서 확인할 수 있습니다.

### 캐스케이드 레이어

Starlight는 스타일 순서를 관리하기 위해 내부적으로 [캐스케이드 레이어](https://developer.mozilla.org/ko/docs/Learn_web_development/Core/Styling_basics/Cascade_layers)를 사용합니다. 이를 통해 예측 가능한 CSS 순서를 보장하고 더 간단한 재정의를 할 수 있습니다.
레이어가 지정되지 않은 사용자 정의 CSS는 기본 Starlight 스타일을 재정의합니다.

캐스케이드 레이어를 사용하고 있다면, 사용자 정의 CSS에서 [`@layer`](https://developer.mozilla.org/ko/docs/Web/CSS/@layer)를 사용하여 `starlight` 레이어의 스타일을 기준으로 서로 다른 레이어의 우선순위를 정의할 수 있습니다.

```css "starlight"
/* src/styles/custom.css */
@layer my-reset, starlight, my-overrides;
```

위 예시는 `my-reset`이라는 사용자 정의 레이어를 정의하며, 이는 모든 Starlight 레이어보다 먼저 적용됩니다. 또 다른 레이어인 `my-overrides`는 모든 Starlight 레이어 이후에 적용됩니다. `my-overrides` 레이어의 모든 스타일은 Starlight의 스타일보다 우선 적용되지만, Starlight는 여전히 `my-reset` 레이어에 설정된 스타일을 변경할 수 있습니다.

## Tailwind CSS

Astro 프로젝트의 Tailwind CSS v4 지원은 [Tailwind Vite 플러그인](https://tailwindcss.com/docs/installation/using-vite)을 통해 제공됩니다.
Starlight는 Starlight 스타일과 호환되도록 Tailwind를 구성하는 데 도움이 되는 보완 CSS를 제공합니다.

Starlight Tailwind CSS는 다음 구성을 적용합니다.

- Starlight의 다크 모드와 작동하도록 Tailwind의 `dark:` 변형을 구성합니다.
- Starlight UI에서 Tailwind [테마 색상 및 글꼴](#tailwind로-starlight-스타일링하기)을 사용합니다.
- Tailwind Preflight 리셋 스타일의 필수적인 부분을 복원합니다.

### Tailwind가 포함된 새 프로젝트 만들기

`create astro`를 사용하여 Tailwind CSS가 사전 구성된 새 Starlight 프로젝트를 시작하세요.

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight/tailwind
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight/tailwind
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight/tailwind
```

</TabItem>
</Tabs>

### 기존 프로젝트에 Tailwind 추가하기

이미 Starlight 사이트가 존재할때, Tailwind CSS를 추가하려면 다음 단계를 따르세요.

<Steps>

1. 다음 명령을 실행하고 터미널의 지침에 따라 프로젝트에 Tailwind를 설정합니다.

   <Tabs syncKey="pkg">

   <TabItem label="npm">

   ```sh
   npx astro add tailwind
   ```

   </TabItem>

   <TabItem label="pnpm">

   ```sh
   pnpm astro add tailwind
   ```

   </TabItem>

   <TabItem label="Yarn">

   ```sh
   yarn astro add tailwind
   ```

   </TabItem>

   </Tabs>

2. Starlight의 Tailwind 호환성 패키지를 설치합니다.

   <Tabs syncKey="pkg">

   <TabItem label="npm">

   ```sh
   npm install @astrojs/starlight-tailwind
   ```

   </TabItem>

   <TabItem label="pnpm">

   ```sh
   pnpm add @astrojs/starlight-tailwind
   ```

   </TabItem>

   <TabItem label="Yarn">

   ```sh
   yarn add @astrojs/starlight-tailwind
   ```

   </TabItem>

   </Tabs>

3. Astro가 스캐폴딩한 `src/styles/global.css` 파일의 콘텐츠를 Starlight와의 호환성을 위해 다음 코드로 교체합니다.

   ```css
   /* src/styles/global.css */
   @layer base, starlight, theme, components, utilities;

   @import '@astrojs/starlight-tailwind';
   @import 'tailwindcss/theme.css' layer(theme);
   @import 'tailwindcss/utilities.css' layer(utilities);
   ```

   이 Tailwind 테마 구성은 Starlight의 [캐스케이드 레이어](#캐스케이드-레이어) 순서를 정의하고, Starlight의 Tailwind 보완 CSS와 Tailwind 테마, 유틸리티 스타일을 가져옵니다. 프로젝트에 추가 Tailwind 구성이 필요한 경우 ["여러 Tailwind 구성 사용하기"](#여러-tailwind-구성-사용하기) 섹션을 확인하세요.

4. `customCss` 배열의 첫 번째 항목으로 Tailwind CSS 파일을 추가하도록 Starlight 구성을 업데이트합니다.

   ```js ins={11-12}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';
   import tailwindcss from '@tailwindcss/vite';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Tailwind를 사용한 문서',
   			customCss: [
   				// Tailwind 기본 스타일의 경로입니다.
   				'./src/styles/global.css',
   			],
   		}),
   	],
   	vite: { plugins: [tailwindcss()] },
   });
   ```

</Steps>

### Tailwind로 Starlight 스타일링하기

[Tailwind를 사용하여 새 Starlight 프로젝트를 만들거나](#tailwind가-포함된-새-프로젝트-만들기) [기존 Starlight 프로젝트에 Tailwind를 추가할 때](#기존-프로젝트에-tailwind-추가하기), Starlight는 `src/styles/global.css` 파일에 있는 [Tailwind 테마 구성](https://tailwindcss.com/docs/theme)의 값을 사용하여 UI의 스타일을 지정합니다.

설정되면 다음 CSS 사용자 정의 속성이 Starlight의 기본 스타일을 재정의합니다.

- `--color-accent-*` — 링크 및 현재 항목 강조 표시에 사용됩니다.
- `--color-gray-*` — 배경색 및 테두리에 사용됩니다.
- `--font-sans` — UI 및 콘텐츠 텍스트에 사용됩니다.
- `--font-mono` — 코드 예시에 사용됩니다.

```css {9,11,13,25}
/* src/styles/global.css */
@layer base, starlight, theme, components, utilities;

@import '@astrojs/starlight-tailwind';
@import 'tailwindcss/theme.css' layer(theme);
@import 'tailwindcss/utilities.css' layer(utilities);

@theme {
	/* 선호하는 텍스트 글꼴입니다. Starlight는 기본적으로 시스템 글꼴 스택을 사용합니다. */
	--font-sans: 'Atkinson Hyperlegible';
	/* 선호하는 코드 글꼴입니다. Starlight는 기본적으로 시스템 고정폭 글꼴을 사용합니다. */
	--font-mono: 'IBM Plex Mono';
	/* 선호하는 강조 색상입니다. 남색(indigo)이 Starlight의 기본값과 가장 유사합니다. */
	--color-accent-50: var(--color-indigo-50);
	--color-accent-100: var(--color-indigo-100);
	--color-accent-200: var(--color-indigo-200);
	--color-accent-300: var(--color-indigo-300);
	--color-accent-400: var(--color-indigo-400);
	--color-accent-500: var(--color-indigo-500);
	--color-accent-600: var(--color-indigo-600);
	--color-accent-700: var(--color-indigo-700);
	--color-accent-800: var(--color-indigo-800);
	--color-accent-900: var(--color-indigo-900);
	--color-accent-950: var(--color-indigo-950);
	/* 선호하는 회색조입니다. 아연색(zinc)이 Starlight의 기본값과 가장 유사합니다. */
	--color-gray-50: var(--color-zinc-50);
	--color-gray-100: var(--color-zinc-100);
	--color-gray-200: var(--color-zinc-200);
	--color-gray-300: var(--color-zinc-300);
	--color-gray-400: var(--color-zinc-400);
	--color-gray-500: var(--color-zinc-500);
	--color-gray-600: var(--color-zinc-600);
	--color-gray-700: var(--color-zinc-700);
	--color-gray-800: var(--color-zinc-800);
	--color-gray-900: var(--color-zinc-900);
	--color-gray-950: var(--color-zinc-950);
}
```

### 여러 Tailwind 구성 사용하기

[하위 경로에서 Starlight를 사용](/ko/manual-setup/#하위-경로에서-starlight-사용)하거나 사이트에 [사용자 정의 페이지](/ko/guides/pages/#사용자-정의-페이지)를 추가할 때와 같이 사이트의 여러 부분에 서로 다른 스타일을 적용하기 위해 여러 Tailwind 구성을 사용할 수 있습니다.
예를 들어 사용자 정의 페이지에 Tailwind의 Preflight 재설정 스타일을 사용하면서 Starlight 페이지에는 Starlight의 호환성 레이어를 적용하고 싶을 수 있습니다.

다음 Tailwind CSS 구성은 플러그인이나 추가 구성 없이 Tailwind를 설정하며, Starlight가 아닌 페이지의 시작점으로 사용할 수 있습니다.

```css title="src/styles/custom-pages-tailwind.css"
/* Starlight의 보완 CSS 없이 Tailwind를 로드합니다. */
@import 'tailwindcss';
```

<Steps>

1. Starlight 페이지의 경우 ["기존 프로젝트에 Tailwind 추가하기"](#기존-프로젝트에-tailwind-추가하기)에 따라 원하는 Tailwind CSS 구성을 적용합니다.

2. 다른 페이지의 경우 해당 페이지에서 원하는 Tailwind CSS 구성을 가져와서 적용하세요. 이 작업은 레이아웃 컴포넌트에서 수행되는 경우가 많으므로 해당 레이아웃을 공유하는 모든 페이지에서 Tailwind 스타일을 사용할 수 있습니다.
   ```astro
   ---
   // src/layouts/CustomPageLayout.astro
   import '../styles/custom-pages-tailwind.css';
   ---
   ```

</Steps>

Tailwind 테마 구성에 대해 자세히 알아보려면 [Tailwind CSS 문서](https://tailwindcss.com/docs/theme)를 확인하세요.

## 테마

기본 사용자 정의 속성을 변경하여 Starlight의 색상 테마를 제어할 수 있습니다.
이러한 변수는 텍스트 및 배경색에 사용되는 다양한 회색 음영과 링크에 사용되는 강조 색상 및 탐색에서 현재 항목을 강조 표시하는 UI 전체에서 사용됩니다.

### 색상 테마 편집기

아래 슬라이더를 사용하여 Starlight의 강조 및 회색 색상 팔레트를 수정하세요. 어둡고 밝은 미리보기 영역에는 결과 색상이 표시되며 전체 페이지도 업데이트되어 변경 사항을 미리 확인할 수 있습니다.

대비 수준 옵션을 사용하여 웹 콘텐츠 접근성 가이드라인 [색상 대비 표준](https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable/Color_contrast) 중 어느 것을 충족할지 지정합니다.

변경 사항이 만족스러우면 아래 CSS 또는 Tailwind 코드를 복사하여 프로젝트에 사용하세요.

import ThemeDesigner from '~/components/theme-designer.astro';

<ThemeDesigner
	labels={{
		presets: {
			label: '프리셋',
			ocean: '오션',
			forest: '숲',
			oxide: '옥사이드',
			nebula: '성운',
			default: '기본값',
			random: '무작위',
		},
		contrast: {
			label: '대비 수준',
		},
		editor: {
			accentColor: '강조',
			grayColor: '회색조',
			hue: '색상',
			chroma: '채도',
			pickColor: '색상 선택',
		},
		preview: {
			darkMode: '어두운 테마',
			lightMode: '밝은 테마',
			bodyText: '본문 텍스트는 배경과 대비가 높은 회색 음영으로 표시됩니다.',
			linkText: '링크에 색상이 지정됩니다.',
			dimText: '콘텐츠 목차와 같은 일부 텍스트는 대비가 낮습니다.',
			inlineCode: '인라인 코드에는 뚜렷한 배경이 있습니다.',
		},
	}}
>
	<Fragment slot="css-docs">
		[사용자 정의 CSS파일](#사용자-정의-css-스타일)에 아래 코드를 추가하여 현재 테마를 프로젝트에 적용하세요.
	</Fragment>
	<Fragment slot="tailwind-docs">
		사이트에 이 테마를 적용하려면 [Tailwind CSS 파일](#tailwind로-starlight-스타일링하기)의 `@theme` 블록에 다음 CSS 변수를 추가하세요.
	</Fragment>

</ThemeDesigner>


================================================
FILE: docs/src/content/docs/ko/guides/customization.mdx
================================================
---
title: Starlight 사용자 정의
description: 로고, 사용자 정의 글꼴, 랜딩 페이지 디자인 등을 사용하여 나만의 Starlight 사이트를 만드는 방법을 알아보세요.
---

import { Tabs, TabItem, FileTree, Steps } from '@astrojs/starlight/components';

Starlight는 합리적인 기본 스타일과 기능을 제공하므로 구성 없이 빠르게 시작할 수 있습니다. Starlight 사이트의 모양과 느낌을 바꾸고 싶다면 이 가이드를 참조하세요.

## 로고 추가

사이트 헤더에 로고를 추가하는 것은 Starlight 사이트에 브랜드를 추가하는 빠른 방법입니다.

<Steps>

1. `src/assets/` 디렉터리에 로고 이미지 파일을 추가합니다.

   <FileTree>

   - src/
     - assets/
       - **my-logo.svg**
     - content/
   - astro.config.mjs

   </FileTree>

2. `astro.config.mjs` 파일에 있는 [logo.src](/ko/reference/configuration/#logo) 옵션의 값으로 로고 파일의 경로를 추가하세요.

   ```diff lang="js"
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: '로고를 사용하는 문서',
   			logo: {
   +				src: './src/assets/my-logo.svg',
   			},
   		}),
   	],
   });
   ```

</Steps>

기본적으로 로고는 사이트의 `title`과 함께 표시됩니다. 이미 로고 이미지에 사이트 제목이 포함되어 있는 경우, `replacementTitle` 옵션을 설정하여 제목 텍스트를 시각적으로 숨길 수 있습니다. `title` 텍스트는 스크린 리더를 위해 남아 있기 때문에 헤더의 접근성은 유지됩니다.

```js {5}
starlight({
  title: '로고를 사용하는 문서',
  logo: {
    src: './src/assets/my-logo.svg',
    replacesTitle: true,
  },
}),
```

### 라이트 모드와 다크 모드에서의 로고 변형

라이트 모드와 다크 모드에서 다른 버전의 로고를 표시할 수 있습니다.

<Steps>

1. `src/assets/` 디렉터리에 각 변형에 대한 이미지 파일을 추가합니다.

   <FileTree>

   - src/
     - assets/
       - **light-logo.svg**
       - **dark-logo.svg**
     - content/
   - astro.config.mjs

   </FileTree>

2. `astro.config.mjs` 파일에서 `src` 대신 `light` 및 `dark` 옵션을 전달하여 로고 변형에 대한 경로를 추가합니다.

   ```diff lang="js"
   starlight({
     title: '로고를 사용하는 문서',
     logo: {
   +    light: './src/assets/light-logo.svg',
   +    dark: './src/assets/dark-logo.svg',
     },
   }),
   ```

</Steps>

## 사이트맵 활성화

Starlight에는 사이트맵 생성 기능이 내장되어 있습니다. `astro.config.mjs` 파일에 있는 `site` 속성의 값을 URL로 설정하여 사이트맵 생성을 활성화할 수 있습니다.

```js {4}
// astro.config.mjs

export default defineConfig({
	site: 'https://stargazers.club',
	integrations: [starlight({ title: '사이트맵을 사용하는 웹 사이트' })],
});
```

Astro 문서에서 [`robots.txt`에 사이트맵 링크를 추가](https://docs.astro.build/ko/guides/integrations-guide/sitemap/#robotstxt-내-사이트맵-링크)하는 방법을 알아보세요.

## 페이지 레이아웃

기본적으로 Starlight 페이지는 전역 탐색 사이드바와 현재 페이지 제목의 목차가 포함된 레이아웃을 사용합니다.

프론트매터에 [`template: splash`](/ko/reference/frontmatter/#template)를 설정하여 사이드바 없이 더 넓은 페이지 레이아웃을 적용할 수 있습니다. 주로 랜딩 페이지에서 사용되며, [이 사이트의 홈페이지](/ko/)에서 실제로 작동하는 것을 확인할 수 있습니다.

```md {5}
---
# src/content/docs/index.md

title: 랜딩 페이지
template: splash
---
```

## 목차

Starlight는 독자가 원하는 제목으로 쉽게 이동할 수 있도록 각 페이지에 목차를 표시합니다. Starlight 통합을 통해 모든 페이지의 목차를 변경하거나 비활성화할 수 있습니다. 또한, 프론트매터를 수정하여 각 페이지의 목차를 변경할 수도 있습니다.

기본적으로 `<h2>` 및 `<h3>` 제목이 목차에 포함됩니다. [`tableOfContents`](/ko/reference/configuration/#tableofcontents) 의 `minHeadingLevel` 및 `maxHeadingLevel` 옵션을 사용하여 모든 페이지의 목차를 변경할 수 있습니다. 개별 페이지의 기본 목차를 변경하기 위해서는 [프론트매터에 `tableOfContents`](/ko/reference/frontmatter/#tableofcontents) 속성을 추가하세요.

<Tabs syncKey="config-type">
  <TabItem label="개별 페이지 설정">

```md {4-6}
---
# src/content/docs/example.md
title: 목차에 H2만 있는 페이지
tableOfContents:
  minHeadingLevel: 2
  maxHeadingLevel: 2
---
```

  </TabItem>
  <TabItem label="전역 설정">

```js {7}
// astro.config.mjs

defineConfig({
	integrations: [
		starlight({
			title: '맞춤 목차 구성이 포함된 문서',
			tableOfContents: { minHeadingLevel: 2, maxHeadingLevel: 2 },
		}),
	],
});
```

  </TabItem>
</Tabs>

`tableOfContents` 옵션의 값을 `false`로 설정하여 모든 페이지의 목차를 비활성화 할 수 있습니다.

<Tabs syncKey="config-type">
  <TabItem label="개별 페이지 설정">

```md {4}
---
# src/content/docs/example.md
title: 목차가 없는 페이지
tableOfContents: false
---
```

  </TabItem>
  <TabItem label="전역 설정">

```js {7}
// astro.config.mjs

defineConfig({
	integrations: [
		starlight({
			title: '모든 목차가 비활성화된 문서',
			tableOfContents: false,
		}),
	],
});
```

  </TabItem>
</Tabs>

## 소셜 링크

Starlight에는 [`social`](/ko/reference/configuration/#social) 옵션을 사용하여 사이트 헤더에 소셜 미디어 계정을 링크하는 기능이 내장되어 있습니다.

`social` 배열의 각 항목은 세 가지 속성을 가진 객체여야 합니다:

- `icon`: Starlight의 [내장 아이콘](/ko/reference/icons/) 중 하나, 예: `"github"`
- `label`: 링크에 대한 접근성이 있는 레이블, 예: `"GitHub"`
- `href`: 해당 링크의 URL, 예: `"https://github.com/withastro/starlight"`

다음 예시는 Astro Discord 채팅과 Starlight GitHub 리포지토리 링크를 추가합니다:

```js {9-16}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: '소셜 링크를 사용하는 문서',
			social: [
				{ icon: 'discord', label: 'Discord', href: 'https://astro.build/chat' },
				{
					icon: 'github',
					label: 'GitHub',
					href: 'https://github.com/withastro/starlight',
				},
			],
		}),
	],
});
```

## 링크 편집

Starlight는 각 페이지의 아래에 "페이지 편집" 링크를 표시할 수 있습니다. 이렇게 하면 독자가 문서 개선을 위해 편집할 파일을 쉽게 찾을 수 있습니다. 특히 오픈 소스 프로젝트에서는 커뮤니티의 기여를 장려하는 데 도움이 될 수 있습니다.

편집 링크를 활성화하기 위해 [`editLink.baseUrl`](/ko/reference/configuration/#editlink)의 값을 저장소를 편집하는 데 사용되는 URL로 설정하세요. `editLink.baseUrl`의 값은 전체 편집 링크를 형성하기 위해 현재 페이지의 경로 앞에 추가됩니다.

일반적인 패턴은 다음과 같습니다.

- GitHub: `https://github.com/USER_NAME/REPO_NAME/edit/BRANCH_NAME/`
- GitLab: `https://gitlab.com/USER_NAME/REPO_NAME/-/edit/BRANCH_NAME/`

Starlight 프로젝트가 저장소의 루트에 없는 경우 기본 URL 끝에 프로젝트 경로를 포함합니다.

아래 예시는 GitHub `withastro/starlight` 저장소의 `main` 브랜치에 있는 `docs/` 디렉터리에 있는 Starlight 문서에 대해 구성된 편집 링크를 보여줍니다.

```js {9-11}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: '편집 링크가 있는 문서',
			editLink: {
				baseUrl: 'https://github.com/withastro/starlight/edit/main/docs/',
			},
		}),
	],
});
```

## 사용자 정의 404 페이지

Starlight 사이트는 기본적으로 간단한 404 페이지를 표시합니다. `src/content/docs/` 디렉터리에 `404.md`(또는 `404.mdx`) 파일을 추가하여 이를 변경할 수 있습니다:

<FileTree>

- src/
  - content/
    - docs/
      - **404.md**
      - index.md
- astro.config.mjs

</FileTree>

404 페이지에서 Starlight의 모든 페이지 레이아웃과 사용자 정의 기술을 사용할 수 있습니다. 예를 들어 기본 404 페이지는 프론트매터에서 [`splash` 템플릿](#페이지-레이아웃)과 [`hero`](/ko/reference/frontmatter/#hero) 컴포넌트를 사용합니다.

```md {4,6-8}
---
# src/content/docs/404.md
title: '404'
template: splash
editUrl: false
hero:
  title: '404'
  tagline: 페이지를 찾을 수 없습니다. URL을 확인하거나 검색창을 사용해 보세요.
---
```

### 기본 404 페이지 비활성화

프로젝트에 완전히 사용자 정의된 404 레이아웃이 필요한 경우 `src/pages/404.astro` 경로를 생성하고 [`disable404Route`](/ko/reference/configuration/#disable404route) 구성 옵션을 설정하여 Starlight의 기본 경로를 비활성화할 수 있습니다.

```js {9}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: '사용자 정의 404가 포함된 문서',
			disable404Route: true,
		}),
	],
});
```

## 사용자 정의 글꼴

기본적으로 Starlight는 모든 텍스트에 대해 사용자의 로컬 장치에서 사용할 수 있는 sans-serif 글꼴을 사용합니다. 이를 통해 대용량 글꼴 파일을 다운로드하기 위한 추가 대역폭 없이 각 사용자에게 친숙한 글꼴로 문서를 빠르게 로드할 수 있습니다.

Starlight 사이트에 사용자 정의 글꼴을 추가해야 하는 경우, 사용자 정의 CSS 파일이나 다른 [Astro 스타일링 기술](https://docs.astro.build/ko/guides/styling/)을 사용하세요.

### 글꼴 설정

이미 글꼴 파일이 존재한다면 [로컬 설정 가이드](#로컬-글꼴-파일-설정)를 따르세요. Google Fonts를 사용하려면 [Fontsource 설정 가이드](#fontsource-글꼴-설정)를 따르세요.

#### 로컬 글꼴 파일 설정

<Steps>

1. `src/fonts/` 디렉터리에 글꼴 파일을 추가하고 빈 `font-face.css` 파일을 만드세요.

   <FileTree>

   - src/
     - content/
     - fonts/
       - **CustomFont.woff2**
       - **font-face.css**
   - astro.config.mjs

   </FileTree>

2. `src/fonts/font-face.css` 파일에 각 글꼴에 대한 [`@font-face` 선언](https://developer.mozilla.org/ko/docs/Web/CSS/@font-face)을 추가하세요. `url()` 함수에서 글꼴 파일의 상대 경로를 사용하세요.

   ```css
   /* src/fonts/font-face.css */

   @font-face {
   	font-family: 'Custom Font';
   	/* `url()`에서 로컬 글꼴 파일의 상대 경로를 사용하세요. */
   	src: url('./CustomFont.woff2') format('woff2');
   	font-weight: normal;
   	font-style: normal;
   	font-display: swap;
   }
   ```

3. `astro.config.mjs` 파일에 있는 Starlight의 `customCss` 배열에 `font-face.css` 파일의 경로를 추가하세요.

   ```diff lang="js"
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: '사용자 정의 글꼴을 사용하는 문서',
   			customCss: [
   +				// @font-face CSS 파일의 상대 경로입니다.
   +				'./src/fonts/font-face.css',
   			],
   		}),
   	],
   });
   ```

</Steps>

#### Fontsource 글꼴 설정

[Fontsource](https://fontsource.org/) 프로젝트는 Google Fonts 및 기타 오픈 소스 글꼴 사용을 단순화합니다. 글꼴을 설치할 수 있는 npm 모듈과 프로젝트에 추가할 CSS 파일을 제공합니다.

<Steps>

1.  [Fontsource 카탈로그](https://fontsource.org/)에서 사용하려는 글꼴을 찾으세요. 예시에서는 [IBM Plex Serif](https://fontsource.org/fonts/ibm-plex-serif)를 사용합니다.

2.  선택한 글꼴에 대한 패키지를 설치합니다. Fontsource 글꼴 페이지에서 “Install”을 클릭하면 패키지 이름을 찾을 수 있습니다.

         <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npm install @fontsource/ibm-plex-serif
    ```

           </TabItem>

        <TabItem label="pnpm">

    ```sh
    pnpm add @fontsource/ibm-plex-serif
    ```

           </TabItem>

        <TabItem label="Yarn">

    ```sh
    yarn add @fontsource/ibm-plex-serif
    ```

           </TabItem>

      </Tabs>

3.  `astro.config.mjs`에 있는 Starlight의 `customCss` 배열에 Fontsource CSS 파일을 추가합니다.

    ```diff lang="js"
    // astro.config.mjs
    import { defineConfig } from 'astro/config';
    import starlight from '@astrojs/starlight';

    export default defineConfig({
    	integrations: [
    		starlight({
    			title: '사용자 정의 글꼴을 사용하는 문서',
    			customCss: [
    + 				// 보통 및 약간 굵은 글꼴 두께에 대한 Fontsource 파일입니다.
    + 				'@fontsource/ibm-plex-serif/400.css',
    + 				'@fontsource/ibm-plex-serif/600.css',
    			],
    		}),
    	],
    });
    ```

    Fontsource는 각 글꼴에 대해 여러 CSS 파일을 제공합니다. 다른 굵기 및 스타일을 포함하는 방법이 궁금하다면 [Fontsource 문서](https://fontsource.org/docs/getting-started/install#4-weights-and-styles)를 참조하세요.

</Steps>

### 글꼴 사용

설정한 글꼴을 웹 사이트에 적용하려면 [사용자 정의 CSS 파일](/ko/guides/css-and-tailwind/#사용자-정의-css-스타일)에서 선택한 글꼴 이름을 사용하세요. 예를 들어 Starlight의 기본 글꼴을 변경하려면 사용자 정의 속성인 `--sl-font`를 설정하세요.

```css
/* src/styles/custom.css */

:root {
	--sl-font: 'IBM Plex Serif', serif;
}
```

글꼴을 더 선택적으로 적용하기 위해 더 많은 CSS를 작성할 수도 있습니다.
예를 들어 다음과 같은 방법으로 메인 콘텐츠에만 글꼴을 설정하고 사이드바에는 글꼴을 설정하지 않을 수 있습니다.

```css
/* src/styles/custom.css */

main {
	font-family: 'IBM Plex Serif', serif;
}
```

[사용자 정의 CSS 사용법](/ko/guides/css-and-tailwind/#사용자-정의-css-스타일)에 따라 웹 사이트에 스타일을 추가하세요.


================================================
FILE: docs/src/content/docs/ko/guides/i18n.mdx
================================================
---
title: 국제화 (i18n)
description: 여러 언어를 지원하도록 Starlight 사이트를 구성하는 방법을 알아보세요.
---

import { FileTree, Steps } from '@astrojs/starlight/components';

Starlight는 라우팅, 대체 콘텐츠 및 전체 RTL(오른쪽에서 왼쪽으로) 언어 지원을 포함한 다국어 사이트에 대한 기본 지원을 제공합니다.

## i18n 구성

<Steps>

1. Starlight 통합에 [`locales`](/ko/reference/configuration/#locales) 및 [`defaultLocale`](/ko/reference/configuration/#defaultlocale)을 전달하여 사이트가 지원해야 할 언어에 대해 알려주세요.

   ```js {9-26}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: '나의 문서',
   			// 사이트의 기본 언어를 영어로 설정합니다.
   			defaultLocale: 'en',
   			locales: {
   				// 영어 문서는 `src/content/docs/en/`에 있습니다.
   				en: {
   					label: 'English',
   				},
   				// 중국어 간체 문서는 `src/content/docs/zh-cn/`에 있습니다.
   				'zh-cn': {
   					label: '简体中文',
   					lang: 'zh-CN',
   				},
   				// 아랍어 문서는 `src/content/docs/ar/`에 있습니다.
   				ar: {
   					label: 'العربية',
   					dir: 'rtl',
   				},
   			},
   		}),
   	],
   });
   ```

   `defaultLocale`은 대체 콘텐츠 및 UI 라벨에 사용되므로 콘텐츠 작성을 시작할 가능성이 가장 높거나 이미 콘텐츠가 있는 언어로 선택하세요.

2. `src/content/docs/`에 각 언어에 대한 디렉터리를 만듭니다. 예를 들어 위에서 사용한 구성의 경우 다음과 같이 디렉터리를 생성할 수 있습니다.

   <FileTree>

   - src/
     - content/
       - docs/
         - ar/
         - en/
         - zh-cn/

   </FileTree>

3. 이제 언어 디렉터리에 콘텐츠 파일을 추가할 수 있습니다. 여러 언어로 작성된 페이지를 연결하기 위해 같은 이름의 파일을 사용하면 Starlight의 모든 i18n 기능(대체 콘텐츠, 번역 알림 등)을 활용할 수 있습니다.

   예를 들어, 아랍어와 영어 홈페이지를 각각 나타내려면 `ar/index.md` 및 `en/index.md`를 만듭니다.

</Steps>

고급 국제화 시나리오를 위해 Starlight는 [Astro의 `i18n` 구성](https://docs.astro.build/ko/guides/internationalization/#i18n-라우팅-구성) 옵션을 사용하는 국제화 구성도 지원합니다.

### 루트 로케일 사용

경로에 i18n 접두사가 없는 언어를 제공하려면 "루트" 로케일을 사용할 수 있습니다. 예를 들어 영어가 루트 로케일인 경우 영어 페이지 경로는 `/en/about` 대신 `/about`이 됩니다.

루트 로케일을 설정하려면 `locales` 구성에서 `root` 키를 사용하세요. 루트 로케일이 콘텐츠의 기본 로케일이기도 한 경우 `defaultLocale`을 제거하거나 값을 `root`로 설정하세요.

```js {9,11-14}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: '나의 문서',
			defaultLocale: 'root', // 선택적
			locales: {
				root: {
					label: 'English',
					lang: 'en', // 루트 로케일은 lang이 반드시 필요합니다.
				},
				'zh-cn': {
					label: '简体中文',
					lang: 'zh-CN',
				},
			},
		}),
	],
});
```

루트 로케일을 사용하는 경우 해당 언어로 작성된 페이지를 전용 언어 폴더 대신 `src/content/docs/`에 직접 보관하세요. 예를 들어 위 구성을 사용할 때 영어와 중국어에 대한 홈 페이지 파일은 다음과 같습니다.

<FileTree>

- src/
  - content/
    - docs/
      - **index.md**
      - zh-cn/
        - **index.md**

</FileTree>

#### 단일 언어를 사용하는 사이트

기본적으로 Starlight는 단일 언어(영어) 사이트입니다.
다른 언어로 단일 언어 사이트를 만들려면 `locales` 구성에서 `root`를 해당 언어로 설정하세요.

```diff lang="js" {10-13}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: '나의 문서',
			locales: {
				root: {
					label: '한국어',
					lang: 'ko',
				},
			},
		}),
	],
});
```

이를 통해 언어 선택기와 같은 다국어 사이트에 대한 다른 국제화 기능을 활성화하지 않고도 Starlight의 기본 언어를 변경할 수 있습니다.

## 대체 콘텐츠

Starlight는 귀하가 모든 언어로 같은 페이지를 생성할 것을 기대합니다. 예를 들어 `en/about.md` 파일이 있는 경우 지원하는 각 언어에 대해 `about.md`를 만듭니다. 이를 통해 Starlight는 아직 번역되지 않은 페이지에 대체 콘텐츠를 제공합니다.

특정 언어에 대한 번역이 아직 제공되지 않는 경우 Starlight는 독자에게 해당 페이지의 콘텐츠를 기본 언어(`defaultLocale`을 통해 설정된 언어)로 표시합니다. 예를 들어, About 페이지의 프랑스어 버전을 아직 만들지 않았고 기본 언어가 영어인 경우 `/fr/about`에 방문한 독자는 이 페이지가 아직 번역되지 않았다는 알림과 함께 `/en/about`에 있는 영어 콘텐츠를 보게 됩니다. 이를 통해 기본 언어로 콘텐츠를 추가한 다음 점진적으로 번역할 수 있습니다.

## 사이트 제목 번역

기본적으로 Starlight는 모든 언어에 대해 동일한 사이트 제목을 사용합니다.
각 로케일의 제목을 사용자 정의해야 하는 경우 Starlight 옵션의 [`title`](/ko/reference/configuration/#title-필수)에 객체를 전달할 수 있습니다.

```diff lang="js"
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
-			title: '나의 문서',
+			title: {
+				ko: '나의 문서',
+				'zh-CN': '我的文档',
+			},
			defaultLocale: 'ko',
			locales: {
				ko: { label: '한국어' },
				'zh-cn': { label: '简体中文', lang: 'zh-CN' },
			},
		}),
	],
});
```

## Starlight UI 번역

import LanguagesList from '~/components/languages-list.astro';
import UIStringsList from '~/components/ui-strings-list.astro';

Starlight를 사용하면 번역된 콘텐츠 파일을 호스팅하는 것 외에도 독자가 선택한 언어로 사이트 전체를 경험할 수 있도록 기본 UI 문자열(예를 들어, 목차의 제목인 "목차")을 번역할 수 있습니다.

<LanguagesList startsSentence />로 번역된 UI 문자열이 기본적으로 제공됩니다.
그리고 우리는 [더 많은 기본 언어를 추가하는 데
기여](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md)하는걸
환영합니다.

`i18n` 데이터 컬렉션을 통해 지원하는 추가 언어에 대한 번역을 제공하거나 기본 라벨을 변경할 수 있습니다.

<Steps>

1. 아직 구성되지 않은 경우 `src/content.config.ts`에서 `i18n` 데이터 컬렉션을 구성합니다.

   ```diff lang="js" ins=/, (i18nLoader|i18nSchema)/
   // src/content.config.ts
   import { defineCollection } from 'astro:content';
   import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
   import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';

   export const collections = {
   docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
   +	i18n: defineCollection({ loader: i18nLoader(), schema: i18nSchema() }),
   };
   ```

2. `src/content/i18n/`에 UI 번역 문자열을 제공하려는 각 추가 언어에 대한 JSON 파일을 만듭니다. 예를 들어 다음은 아랍어 및 중국어 간체에 대한 번역 파일을 추가합니다.

   <FileTree>

   - src/
     - content/
       - i18n/
         - ar.json
         - zh-CN.json

   </FileTree>

3. JSON 파일에서 키에 대한 번역을 추가합니다. 키는 영어로 남겨두고 값을 번역해야합니다. (예: `"search.label": "Buscar"`)

   Starlight와 함께 제공되는 기존 문자열의 영어 기본값은 다음과 같습니다.

   <UIStringsList />

   Starlight의 코드 블록은 [Expressive Code](https://expressive-code.com/) 라이브러리에 의해 구동됩니다.
   `expressiveCode` 키를 사용하여 동일한 JSON 파일에서 UI 문자열에 대한 번역을 설정할 수 있습니다.

   ```json
   {
   	"expressiveCode.copyButtonCopied": "Copied!",
   	"expressiveCode.copyButtonTooltip": "Copy to clipboard",
   	"expressiveCode.terminalWindowFallbackTitle": "Terminal window"
   }
   ```

   Starlight의 검색 모달은 [Pagefind](https://pagefind.app/) 라이브러리에 의해 구동됩니다. 동일한 JSON 파일에서 `pagefind` 키를 사용하여 Pagefind의 UI에 대한 번역을 설정할 수 있습니다.

   ```json
   {
   	"pagefind.clear_search": "Clear",
   	"pagefind.load_more": "Load more results",
   	"pagefind.search_label": "Search this site",
   	"pagefind.filters_label": "Filters",
   	"pagefind.zero_results": "No results for [SEARCH_TERM]",
   	"pagefind.many_results": "[COUNT] results for [SEARCH_TERM]",
   	"pagefind.one_result": "[COUNT] result for [SEARCH_TERM]",
   	"pagefind.alt_search": "No results for [SEARCH_TERM]. Showing results for [DIFFERENT_TERM] instead",
   	"pagefind.search_suggestion": "No results for [SEARCH_TERM]. Try one of the following searches:",
   	"pagefind.searching": "Searching for [SEARCH_TERM]..."
   }
   ```

</Steps>

### 번역 스키마 확장

`i18nSchema()` 옵션에서 `extend`를 설정하여 사이트 번역 사전에 맞춤 키를 추가하세요.
다음 예시에서는 기본 키에 새로운 선택적 `custom.label` 키가 추가됩니다.

```diff lang="js"
// src/content.config.ts
import { defineCollection, z } from 'astro:content';
import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';

export const collections = {
  docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
	i18n: defineCollection({
	  loader: i18nLoader(),
		schema: i18nSchema({
+			extend: z.object({
+				'custom.label': z.string().optional(),
+			}),
		}),
	}),
};
```

Astro 공식문서의 ["컬렉션 스키마 정의"](https://docs.astro.build/ko/guides/content-collections/#컬렉션-스키마-정의)에서 콘텐츠 컬렉션 스키마에 대해 자세히 알아보세요.

## UI 번역 사용

Starlight의 [기본 제공 UI 문자열](/ko/guides/i18n/#starlight-ui-번역)과 [사용자 정의](/ko/guides/i18n/#번역-스키마-확장) 및 [플러그인 제공](/ko/reference/plugins/#injecttranslations) UI 문자열에 액세스할 수 있는 통합 API는 [i18next](https://www.i18next.com/)로 구동됩니다.
여기에는 [보간](https://www.i18next.com/translation-function/interpolation) 및 [복수화](https://www.i18next.com/translation-function/plurals)와 같은 기능에 대한 지원이 포함됩니다.

Astro 컴포넌트에서 이 API는 [전역 `Astro` 객체](https://docs.astro.build/ko/reference/api-reference/#locals)의 일부인 `Astro.locals.t`로 사용할 수 있습니다:

```astro title="example.astro"
<p dir={Astro.locals.t.dir()}>
	{Astro.locals.t('404.text')}
</p>
```

[엔드포인트](https://docs.astro.build/ko/guides/endpoints/)에서도 API를 사용할 수 있으며, 여기서 `locals` 객체는 [엔드포인트 컨텍스트](https://docs.astro.build/ko/reference/api-reference/#locals)의 일부로 사용할 수 있습니다:

```ts title="src/pages/404.ts"
export const GET = (context) => {
	return new Response(context.locals.t('404.text'));
};
```

Starlight 플러그인 컨텍스트에서 [`useTranslations()`](/ko/reference/plugins/#usetranslations) 도우미를 사용하여 특정 언어에 대한 이 API에 접근할 수 있습니다.
자세한 내용은 [플러그인 참조](/ko/reference/plugins/)를 확인하세요.

### UI 문자열 렌더링

`locals.t()` 함수를 사용하여 UI 문자열을 렌더링합니다.
이것은 UI 문자열 키를 첫 번째 인수로 받아 현재 언어에 해당하는 번역을 반환하는 i18next의 `t()` 함수의 인스턴스입니다.

예를 들어 다음과 같은 콘텐츠가 포함된 사용자 정의 번역 파일이 있다고 가정해 보겠습니다:

```json title="src/content/i18n/en.json"
{
	"link.astro": "Astro documentation",
	"link.astro.custom": "Astro documentation for {{feature}}"
}
```

첫 번째 UI 문자열은 `t()` 함수에 `'link.astro'`를 전달하여 렌더링할 수 있습니다:

```astro {3}
<!-- src/components/Example.astro -->
<a href="https://docs.astro.build/">
	{Astro.locals.t('link.astro')}
</a>
<!-- 렌더링: <a href="...">Astro documentation</a> -->
```

두 번째 UI 문자열은 `{{feature}}` 자리 표시자에 i18next의 [보간 구문](https://www.i18next.com/translation-function/interpolation)을 사용합니다.
`feature`의 값은 `t()`의 두 번째 인수로 전달된 옵션 객체에서 설정되어야 합니다:

```astro {3}
<!-- src/components/Example.astro -->
<a href="https://docs.astro.build/en/guides/astro-db/">
	{Astro.locals.t('link.astro.custom', { feature: 'Astro DB' })}
</a>
<!-- 렌더링: <a href="...">Astro documentation for Astro DB</a> -->
```

보간, 서식 지정 등과 함께 `t()` 함수를 사용하는 방법에 대한 자세한 내용은 [i18next 문서](https://www.i18next.com/overview/api#t)를 참조하세요.

### 고급 API

#### `t.all()`

`locals.t.all()` 함수는 현재 로케일에서 사용 가능한 모든 UI 문자열이 포함된 객체를 반환합니다.

```astro
---
// src/components/Example.astro
const allStrings = Astro.locals.t.all();
//    ^
//    {
//      "skipLink.label": "Skip to content",
//      "search.label": "Search",
//      …
//    }
---
```

#### `t.exists()`

번역 키가 존재하는지 확인하려면 번역 키를 첫 번째 인수로 전달하여 `locals.t.exists()` 함수를 사용합니다.
특정 로케일에 대한 번역이 존재하는지 확인해야 하는 경우 선택적으로 두 번째 인수를 전달합니다.

```astro
---
// src/components/Example.astro
const keyExists = Astro.locals.t.exists('a.key');
//    ^ true
const keyExistsInFrench = Astro.locals.t.exists('other.key', { lngs: ['fr'] });
//    ^ false
---
```

자세한 내용은 [i18next 문서의 `exists()` 참조](https://www.i18next.com/overview/api#exists)를 확인하세요.

#### `t.dir()`

`locals.t.dir()` 함수는 현재 또는 특정 로케일의 텍스트 방향을 반환합니다.

```astro
---
// src/components/Example.astro
const currentDirection = Astro.locals.t.dir();
//    ^
//    'ltr'
const arabicDirection = Astro.locals.t.dir('ar');
//    ^
//    'rtl'
---
```

자세한 내용은 [i18next 문서의 `dir()` 참조](https://www.i18next.com/overview/api#dir)를 확인하세요.

## 현재 로케일에 액세스

[`Astro.currentLocale`](https://docs.astro.build/ko/reference/api-reference/#currentlocale)을 사용하여 `.astro` 컴포넌트의 현재 로케일을 읽을 수 있습니다.

다음 예시는 현재 로케일을 읽고 이를 [`getRelativeLocaleUrl()`](https://docs.astro.build/ko/reference/modules/astro-i18n/#getrelativelocaleurl) 헬퍼와 함께 사용하여 현재 언어로 된 소개 페이지 링크를 생성합니다:

```astro
---
// src/components/AboutLink.astro
import { getRelativeLocaleUrl } from 'astro:i18n';
---

<a href={getRelativeLocaleUrl(Astro.currentLocale ?? 'en', 'about')}>소개</a>
```


================================================
FILE: docs/src/content/docs/ko/guides/overriding-components.mdx
================================================
---
title: 컴포넌트 재정의
description: Starlight 내장 컴포넌트를 재정의하여 문서 사이트 UI에 사용자 정의 요소를 추가하는 방법에 대해 알아보세요.
---

import { Steps } from '@astrojs/starlight/components';

Starlight의 기본 UI 및 구성 옵션은 유연하고 다양한 콘텐츠에 작동하도록 설계되었습니다. Starlight의 기본 형태는 대부분 [CSS](/ko/guides/css-and-tailwind/) 및 [구성 옵션](/ko/guides/customization/)을 사용하여 변경할 수 있습니다.

기본적으로 Starlight는 가능한 것보다 더 많은 것이 필요한 경우, 기본 컴포넌트를 확장하거나 재정의(완전히 대체)하기 위한 자체 사용자 정의 컴포넌트 구축을 지원합니다.

## 재정의가 필요한 경우

Starlight의 기본 컴포넌트를 재정의하는 것은 다음과 같은 경우에 유용할 수 있습니다.

- [사용자 정의 CSS](/ko/guides/css-and-tailwind/)로는 불가능한 방식으로 Starlight UI를 변경하고 싶은 경우.
- Starlight UI의 일부 동작을 변경하고 싶은 경우.
- Starlight의 기존 UI 외 새로운 UI를 추가하고 싶은 경우.

## 재정의 방법

<Steps>

1. 재정의하려는 Starlight 컴포넌트를 선택합니다.
   [재정의 참조](/ko/reference/overrides/)에서 전체 컴포넌트 목록을 확인할 수 있습니다.

   :::tip
   어떤 컴포넌트를 재정의해야 할지 잘 모르겠나요? [상호작용 할 수 있는 Starlight Overrides Map](https://starlight-overrides-map.netlify.app/)에서 Starlight의 UI 컴포넌트 이름을 확인할 수 있습니다.
   :::

   이 예시는 페이지 탐색 바에 있는 Starlight의 [`SocialIcons`](/ko/reference/overrides/#socialicons) 컴포넌트를 재정의합니다.

2. Starlight 컴포넌트를 대체할 Astro 컴포넌트를 생성합니다.
   이 예시는 연락처 링크를 렌더링합니다.

   ```astro
   ---
   // src/components/EmailLink.astro

   const email = 'houston@example.com';
   ---

   <a href=`mailto:${email}`>메일 보내기</a>
   ```

3. `astro.config.mjs` 파일의 [`components`](/ko/reference/configuration/#components) 구성 옵션에서 사용자 정의 컴포넌트를 사용하기 위한 설정을 추가합니다.

   ```js {9-12}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: '재정의된 문서',
   			components: {
   				// 기존 `SocialIcons` 컴포넌트를 재정의합니다.
   				SocialIcons: './src/components/EmailLink.astro',
   			},
   		}),
   	],
   });
   ```

</Steps>

## 내장 컴포넌트 재사용

Starlight의 기본 UI 컴포넌트를 사용하여 나만의 컴포넌트를 구축할 수 있습니다. 즉, 사용자 정의 컴포넌트에 Starlight UI 컴포넌트를 가져와 렌더링할 수 있습니다. 이를 통해 기존 Starlight UI를 유지하면서 새로운 UI를 추가할 수 있습니다.

아래 예시는 기존 `SocialIcons` 컴포넌트와 함께 이메일 링크를 렌더링하는 사용자 정의 컴포넌트를 나타냅니다.

```astro {3,7}
---
// src/components/EmailLink.astro
import Default from '@astrojs/starlight/components/SocialIcons.astro';
---

<a href="mailto:houston@example.com">메일 보내기</a>
<Default><slot /></Default>
```

사용자 정의 컴포넌트 내부에 내장 컴포넌트를 렌더링할 때 기본 컴포넌트 내부에 [`<slot />`](https://docs.astro.build/ko/basics/astro-components/#슬롯)을 추가하세요. 이렇게 하면 컴포넌트에 자식 요소가 전달될 경우 Astro가 해당 요소를 렌더링할 위치를 알 수 있습니다.

[명명된 슬롯](https://docs.astro.build/ko/basics/astro-components/#명명된-슬롯)이 포함된 [`PageFrame`](/ko/reference/overrides/#pageframe) 또는 [`TwoColumnContent`](/ko/reference/overrides/#twocolumncontent) 컴포넌트를 재사용하는 경우 이러한 슬롯도 [전송](https://docs.astro.build/ko/basics/astro-components/#슬롯-전송)해야 합니다.

아래 예시는 `TwoColumnContent` 컴포넌트를 재사용하는 사용자 정의 컴포넌트를 보여줍니다. 이 컴포넌트는 `right-sidebar`라는 이름의 추가 슬롯을 포함하여 전송합니다.

```astro {8}
---
// src/components/CustomContent.astro
import Default from '@astrojs/starlight/components/TwoColumnContent.astro';
---

<Default>
	<slot />
	<slot name="right-sidebar" slot="right-sidebar" />
</Default>
```

## 페이지 데이터 사용

Starlight 컴포넌트를 재정의할 때, 현재 페이지의 모든 데이터를 포함하는 전역 [`starlightRoute` 객체](/ko/guides/route-data/)에 접근할 수 있습니다.

전달받은 값을 사용하여 컴포넌트 템플릿이 렌더링되는 방식을 제어할 수 있습니다.

다음 예제에서 대체된 [`PageTitle`](/ko/reference/overrides/#pagetitle) 컴포넌트는 콘텐츠 프런트매터에 설정된 현재 페이지의 제목을 표시합니다:

```astro {4} "{title}"
---
// src/components/Title.astro

const { title } = Astro.locals.starlightRoute.entry.data;
---

<h1 id="_top">{title}</h1>

<style>
	h1 {
		font-family: 'Comic Sans';
	}
</style>
```

[경로 데이터 참조](/ko/reference/route-data/)에서 사용 가능한 모든 속성에 대해 자세히 알아보세요.

### 특정 페이지 재정의

컴포넌트 재정의는 모든 페이지에 적용됩니다. 하지만, 사용자 정의 UI, Starlight의 기본 UI, 또는 완전히 다른 무언가가 나타나는 시기를 결정하기 위해 `starlightRoute`의 값을 사용하여 조건부 렌더링이 가능합니다.

다음 예시에서 Starlight의 [`Footer`](/ko/reference/overrides/#footer)를 재정의하는 컴포넌트는 "Starlight 🌟 를 사용하여 구축"을 홈페이지에만 표시하고, 다른 모든 페이지에는 기본 바닥글만 표시합니다.

```astro
---
// src/components/ConditionalFooter.astro
import Default from '@astrojs/starlight/components/Footer.astro';

const isHomepage = Astro.locals.starlightRoute.id === '';
---

{
	isHomepage ? (
		<footer>Starlight 🌟 를 사용하여 구축</footer>
	) : (
		<Default>
			<slot />
		</Default>
	)
}
```

[Astro의 템플릿 구문 가이드](https://docs.astro.build/ko/basics/astro-syntax/#동적-html)에서 조건부 렌더링에 대해 자세히 알아보세요.


================================================
FILE: docs/src/content/docs/ko/guides/pages.mdx
================================================
---
title: 페이지
description: Starlight를 사용하여 문서 사이트의 페이지를 만들고 관리하는 방법을 알아보세요.
sidebar:
  order: 1
tableOfContents:
  maxHeadingLevel: 4
---

Starlight는 Markdown Frontmatter를 통해 제공되는 유연한 옵션을 사용하여 콘텐츠를 기반으로 사이트의 HTML 페이지를 생성합니다.
또한 Starlight 프로젝트는 [Astro의 강력한 페이지 생성 도구](https://docs.astro.build/ko/basics/astro-pages/)에 대한 전체 액세스 권한을 갖습니다.
이 가이드에서는 Starlight에서 페이지 생성이 작동하는 방식을 보여줍니다.

## 콘텐츠 페이지

### 파일 형식

Starlight는 구성이 필요 없는 Markdown 및 MDX 콘텐츠 작성을 지원합니다.
Markdoc에 대한 지원은 ["Markdoc" 가이드](/ko/guides/authoring-content/#markdoc)를 참조하여 추가할 수 있습니다.

### 페이지 추가

`src/content/docs/`에 `.md` 또는 `.mdx` 파일을 생성하여 사이트에 새 페이지를 추가하세요.
하위 폴더를 사용하여 파일을 정리하고 여러 경로 세그먼트를 생성하세요.

예를 들어, 다음 파일 구조는 `example.com/hello-world` 및 `example.com/reference/faq`에 페이지를 생성합니다.

import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src/
  - content/
    - docs/
      - hello-world.md
      - reference/
        - faq.md

</FileTree>

### 타입 안정성을 갖춘 프론트매터

모든 Starlight 페이지는 페이지 표시 방법을 제어하기 위해 사용자 정의 가능한 [공통 프론트매터 속성 세트](/ko/reference/frontmatter/)를 공유합니다.

```md
---
title: 안녕하세요!
description: 이것은 내 Starlight 기반 사이트의 페이지입니다.
---
```

중요한 사항을 잊어버리면 Starlight가 알려드립니다.

## 사용자 정의 페이지

고급 사용 사례의 경우 `src/pages/` 디렉터리를 생성하여 사용자 정의 페이지를 추가할 수 있습니다.
`src/pages/` 디렉터리는 [Astro의 파일 기반 라우팅](https://docs.astro.build/ko/basics/astro-pages/#파일-기반-라우팅)을 사용하며 다른 페이지 형식에서 `.astro` 파일에 대한 지원을 포함합니다.
이는 완전히 사용자 정의된 레이아웃으로 페이지를 작성하거나 대체 데이터 소스에서 페이지를 생성해야 하는 경우에 유용합니다.

예를 들어, 이 프로젝트는 `src/content/docs/`의 Markdown 콘텐츠를 `src/pages/`의 Astro 및 HTML 경로와 혼합합니다.

<FileTree>

- src/
  - content/
    - docs/
      - hello-world.md
  - pages/
    - custom.astro
    - archived.html

</FileTree>

[Astro 문서의 "페이지" 가이드](https://docs.astro.build/ko/basics/astro-pages/)에서 자세한 내용을 읽어보세요.

### 사용자 정의 페이지에서 Starlight 디자인 사용

사용자 정의 페이지에서 Starlight 레이아웃을 사용하려면 [`<StarlightPage>` 컴포넌트](#starlightpage-컴포넌트)로 페이지 콘텐츠를 감싸세요.
이는 콘텐츠를 동적으로 생성하지만 여전히 Starlight의 디자인을 사용하려는 경우 유용할 수 있습니다.

사용자 정의 페이지에서 [`<AnchorHeading>` 컴포넌트](#anchorheading-컴포넌트)를 사용하여 Starlight의 Markdown 앵커 링크 스타일과 일치하는 앵커 링크를 제목에 추가할 수 있습니다.

```astro
---
// src/pages/custom-page/example.astro
import StarlightPage from '@astrojs/starlight/components/StarlightPage.astro';
import AnchorHeading from '@astrojs/starlight/components/AnchorHeading.astro';
import CustomComponent from './CustomComponent.astro';
---

<StarlightPage frontmatter={{ title: '사용자 정의 페이지' }}>
	<p>사용자 정의 컴포넌트가 있는 사용자 정의 페이지입니다.</p>
	<CustomComponent />

	<AnchorHeading level="2" id="learn-more">자세히 알아보기</AnchorHeading>
	<p>
		<a href="https://starlight.astro.build/">
			Starlight 문서에서 자세히 알아보기
		</a>
	</p>
</StarlightPage>
```

#### `<StarlightPage>` 컴포넌트

`<StarlightPage />` 컴포넌트는 Starlight의 레이아웃과 스타일을 사용하여 전체 페이지 콘텐츠를 렌더링합니다.

```astro
---
import StarlightPage from '@astrojs/starlight/components/StarlightPage.astro';
---

<StarlightPage frontmatter={{ title: '사용자 정의 페이지' }}>
	<!-- 사용자 정의 페이지 콘텐츠 -->
</StarlightPage>
```

`<StarlightPage />` 컴포넌트는 다음 props를 허용합니다.

##### `frontmatter`

**필수**  
**타입:** `StarlightPageFrontmatter`

Markdown 페이지의 프론트매터와 유사하게 이 페이지에 대한 [프론트매터 속성](/ko/reference/frontmatter/)을 설정합니다.
[`title`](/ko/reference/frontmatter/#title-필수) 속성은 필수이며 다른 모든 속성은 선택 사항입니다.

다음 속성은 Markdown 프론트매터와 다릅니다.

- [`slug`](/ko/reference/frontmatter/#slug) 속성은 지원되지 않으며 사용자 정의 페이지의 URL을 기반으로 자동 설정됩니다.
- [`editUrl`](/ko/reference/frontmatter/#editurl) 옵션에는 편집 링크를 표시하기 위한 URL이 필요합니다.
- [자동 생성된 링크 그룹](/ko/reference/configuration/#sidebar)에서 페이지가 표시되는 방식을 사용자 정의하기 위한 [`sidebar`](/ko/reference/frontmatter/#sidebar) 프론트매터 속성을 사용할 수 없습니다. `<StarlightPage />` 컴포넌트를 사용하는 페이지는 컬렉션의 일부가 아니며 자동 생성된 사이드바 그룹에 추가될 수 없습니다.
- [`draft`](/ko/reference/frontmatter/#draft) 옵션은 페이지가 초안이라는 [알림](/ko/reference/overrides/#draftcontentnotice)만 표시할 뿐 프로덕션 빌드에서 자동으로 제외하지는 않습니다.

##### `sidebar`

**타입:** [`SidebarItem[]`](/ko/reference/configuration/#sidebaritem)  
**기본값:** [전역 `sidebar` 구성](/ko/reference/configuration/#sidebar)을 기반으로 생성된 사이드바

이 페이지에 대한 사용자 정의 사이트 탐색 사이드바를 제공합니다.
설정하지 않으면 페이지에서 기본 전역 사이드바를 사용합니다.

예를 들어, 다음 페이지는 홈페이지 링크와 다양한 다른 사용자 지정 페이지로 연결되는 링크 그룹으로 기본 사이드바를 재정의합니다.

```astro {3-13}
<StarlightPage
	frontmatter={{ title: '오리온' }}
	sidebar={[
		{ label: '홈', link: '/' },
		{
			label: '별자리',
			items: [
				{ label: '안드로메다', link: '/andromeda/' },
				{ label: '오리온', link: '/orion/' },
				{ label: '작은곰자리', link: '/ursa-minor/', badge: 'Stub' },
			],
		},
	]}
>
	예시 콘텐츠
</StarlightPage>
```

사이드바를 사용자 정의하기 위해 사용할 수 있는 옵션에 대해 자세히 알아보려면 [“사이드바 탐색”](/ko/guides/sidebar/) 가이드를 참조하세요.

##### `hasSidebar`

**타입:** `boolean`  
**기본값:** [`frontmatter.template`](/ko/reference/frontmatter/#template)의 값이 `'splash'`라면 `false`, 그렇지 않다면 `true`

이 페이지에 사이드바를 표시할지 여부를 제어합니다.

##### `headings`

**타입:** `{ depth: number; slug: string; text: string }[]`  
**기본값:** `[]`

이 페이지의 모든 제목 배열을 제공하세요.
제공된 경우 Starlight는 이 제목에서 페이지 목차를 생성합니다.

##### `dir`

**타입:** `'ltr' | 'rtl'`  
**기본값:** 현재 로케일의 쓰기 방향

이 페이지 콘텐츠의 쓰기 방향을 설정합니다.

##### `lang`

**타입:** `string`  
**기본값:** 현재 로케일의 언어

이 페이지 콘텐츠에 대해 BCP-47 언어 태그를 설정합니다. 예: `en`, `zh-CN` 또는 `pt-BR`.

##### `isFallback`

**타입:** `boolean`  
**기본값:** `false`

현재 언어에 대한 번역이 존재하지 않아 이 페이지가 [대체 콘텐츠](/ko/guides/i18n/#대체-콘텐츠)를 사용하고 있는지 표시합니다.

#### `<AnchorHeading>` 컴포넌트

`<AnchorHeading />` 컴포넌트는 Starlight의 Markdown 스타일과 일치하는 클릭 가능한 앵커 링크가 있는 HTML 제목 요소를 렌더링합니다.

```astro
---
import AnchorHeading from '@astrojs/starlight/components/AnchorHeading.astro';
---

<AnchorHeading level="2" id="sub-heading">하위 제목</AnchorHeading>
```

이 컴포넌트는 다음과 같은 props 뿐만 아니라 다른 유효한 [전역 HTML 속성](https://developer.mozilla.org/ko/docs/Web/HTML/Reference/Global_attributes)도 허용합니다.

##### `level`

**필수**  
**타입:** `1 | 2 | 3 | 4 | 5 | 6`

렌더링할 제목 수준입니다.
예를 들어, `level="1"`은 `<h1>` 요소를 렌더링합니다.

##### `id`

**필수**  
**타입:** `string`

이 제목의 고유 ID입니다.
이는 렌더링된 제목의 `id` 속성으로 사용되며, 앵커 아이콘은 이 ID로 연결됩니다.


================================================
FILE: docs/src/content/docs/ko/guides/project-structure.mdx
================================================
---
title: 프로젝트 구조
description: Starlight 프로젝트에서 파일을 구성하는 방법을 알아보세요.
---

이 가이드에서는 Starlight 프로젝트가 구성되는 방법과 프로젝트의 다양한 파일이 수행하는 작업을 보여줍니다.

Starlight 프로젝트는 일반적으로 다른 Astro 프로젝트와 동일한 파일 및 디렉터리 구조를 따릅니다. 자세한 내용은 [Astro의 프로젝트 구조 문서](https://docs.astro.build/ko/basics/project-structure/)를 참조하세요.

## 파일 및 디렉터리

- `astro.config.mjs` — Starlight 통합 및 구성이 포함된 Astro 구성 파일 입니다.
- `src/content.config.ts` — Starlight의 프론트매터 스키마를 프로젝트에 추가하는 콘텐츠 컬렉션 구성 파일입니다.
- `src/content/docs/` — 콘텐츠 파일들이 포함된 디렉터리입니다. Starlight는 이 디렉터리에 있는 `.md`, `.mdx` 또는 `.mdoc` 파일을 사이트의 페이지로 변환합니다.
- `src/content/i18n/` (선택적) — [국제화](/ko/guides/i18n/)를 지원하는 번역 데이터들이 포함된 디렉터리입니다.
- `src/` — 프로젝트의 기타 소스 코드 및 파일(컴포넌트, 스타일, 이미지 등)이 포함된 디렉터리입니다.
- `public/` — Astro에서 처리되지 않는 정적 자산(글꼴, 파비콘, PDF 등)이 포함된 디렉터리입니다.

## 예시 프로젝트

Starlight 프로젝트 디렉터리는 다음과 같습니다.

import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- public/
  - favicon.svg
- src/
  - assets/
    - logo.svg
    - screenshot.jpg
  - components/
    - CustomButton.astro
    - InteractiveWidget.jsx
  - content/
    - docs/
      - guides/
        - 01-getting-started.md
        - 02-advanced.md
      - index.mdx
  - content.config.ts
- astro.config.mjs
- package.json
- tsconfig.json

</FileTree>


================================================
FILE: docs/src/content/docs/ko/guides/route-data.mdx
================================================
---
title: 경로 데이터
description: Starlight의 페이지 데이터 모델이 페이지를 렌더링하는 데 어떻게 사용되는지, 그리고 이를 어떻게 사용자 정의할 수 있는지 알아보세요.
---

import { Steps } from '@astrojs/starlight/components';

Starlight가 문서에서 페이지를 렌더링할 때, 먼저 해당 페이지의 내용을 나타내는 경로 데이터 객체를 생성합니다.
이 가이드에서는 경로 데이터가 어떻게 생성되는지, 어떻게 사용하는지, 그리고 Starlight의 기본 동작을 수정하기 위해 어떻게 사용자 정의할 수 있는지 설명합니다.

사용 가능한 속성의 전체 목록은 ["경로 데이터 참조"](/ko/reference/route-data/)를 확인하세요.

## 경로 데이터란 무엇인가요?

Starlight 경로 데이터는 단일 페이지를 렌더링하는 데 필요한 모든 정보를 담고 있는 객체입니다.
여기에는 현재 페이지에 대한 정보뿐만 아니라 Starlight 구성에서 생성된 데이터도 포함됩니다.

## 경로 데이터 사용하기

Starlight의 모든 컴포넌트는 경로 데이터를 사용하여 각 페이지에 무엇을 렌더링할지 결정합니다. 예를 들어, [`siteTitle`](/ko/reference/route-data/#sitetitle) 문자열은 사이트 제목을 표시하는 데 사용되고, [`sidebar`](/ko/reference/route-data/#sidebar) 배열은 전역 사이드바 탐색을 렌더링하는 데 사용됩니다.

Astro 컴포넌트에서 `Astro.locals.starlightRoute` 전역 변수를 통해 이 데이터에 접근할 수 있습니다.

```astro title="example.astro" {2}
---
const { siteTitle } = Astro.locals.starlightRoute;
---

<p>The title of this site is “{siteTitle}”</p>
```

예를 들어, [컴포넌트 재정의](/ko/guides/overriding-components/)를 구축하여 표시되는 내용을 사용자 정의할 때 유용할 수 있습니다.

## 경로 데이터 사용자 정의

Starlight의 경로 데이터는 별도의 구성 없이 바로 작동합니다.
하지만 고급 사용 사례의 경우, 일부 또는 모든 페이지에 대한 경로 데이터를 사용자 정의하여 사이트 표시 방식을 변경할 수 있습니다.

이는 [컴포넌트 재정의](/ko/guides/overriding-components/)와 유사한 개념이지만, Starlight가 데이터를 렌더링하는 방식을 수정하는 대신 Starlight가 렌더링하는 데이터를 수정합니다.

### 경로 데이터 사용자 정의가 필요한 경우

경로 데이터 사용자 정의는 Starlight가 데이터를 처리하는 방식을 기존 구성 옵션으로는 불가능한 방식으로 수정하고 싶을 때 유용할 수 있습니다.

예를 들어, 특정 페이지의 사이드바 항목을 필터링하거나 제목을 사용자 정의할 수 있습니다. 이와 같은 변경 사항은 Starlight의 기본 컴포넌트를 수정할 필요 없이 해당 컴포넌트에 전달되는 데이터만 수정하면 됩니다.

### 경로 데이터를 사용자 정의하는 방법

"미들웨어"의 특수한 형태를 사용하여 경로 데이터를 사용자 정의할 수 있습니다.
이는 Starlight가 페이지를 렌더링할 때마다 호출되는 함수로, 경로 데이터 객체의 값을 수정할 수 있습니다.

<Steps>

1. Starlight의 `defineRouteMiddleware()` 유틸리티를 사용하여 `onRequest` 함수를 내보내는 새 파일을 만듭니다.

   ```ts
   // src/routeData.ts
   import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

   export const onRequest = defineRouteMiddleware(() => {});
   ```

2. `astro.config.mjs`에서 경로 데이터 미들웨어 파일의 위치를 Starlight에 알려줍니다.

   ```js ins={9}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: '나의 즐거운 문서 사이트',
   			routeMiddleware: './src/routeData.ts',
   		}),
   	],
   });
   ```

3. `onRequest` 함수를 업데이트하여 경로 데이터를 수정합니다.

   미들웨어가 받는 첫 번째 인자는 [Astro의 `context` 객체](https://docs.astro.build/ko/reference/api-reference/)입니다.
   여기에는 현재 URL과 `locals`를 포함하여 현재 페이지 렌더링에 대한 모든 정보가 포함되어 있습니다.

   이 예제에서는 모든 페이지 제목의 끝에 느낌표를 추가하여 문서를 더욱 흥미롭게 만들 것입니다.

   ```ts
   // src/routeData.ts
   import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

   export const onRequest = defineRouteMiddleware((context) => {
   	// 이 페이지의 콘텐츠 컬렉션 항목을 가져옵니다.
   	const { entry } = context.locals.starlightRoute;
   	// 제목에 느낌표를 추가하여 업데이트합니다.
   	entry.data.title = entry.data.title + '!';
   });
   ```

</Steps>

#### 여러 경로 미들웨어

Starlight는 여러 개의 미들웨어 제공도 지원합니다.
둘 이상의 미들웨어 핸들러를 추가하려면 `routeMiddleware`를 경로 배열로 설정하세요.

```js {9}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: '여러 미들웨어가 있는 내 사이트',
			routeMiddleware: ['./src/middleware-one.ts', './src/middleware-two.ts'],
		}),
	],
});
```

#### 추가된 경로 미들웨어 대기

코드 실행 전에 스택에 추가된 미들웨어가 실행될 때까지 기다리려면 미들웨어 함수에 두 번째 인자로 전달되는 `next()` 콜백을 await할 수 있습니다.
예를 들어, 변경하기 전에 플러그인의 미들웨어가 실행될 때까지 기다리는 데 유용할 수 있습니다.

```ts "next" "await next();"
// src/routeData.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

export const onRequest = defineRouteMiddleware(async (context, next) => {
	// 추가된 미들웨어가 실행될 때까지 기다립니다.
	await next();
	// 경로 데이터를 수정합니다.
	const { entry } = context.locals.starlightRoute;
	entry.data.title = entry.data.title + '!';
});
```


================================================
FILE: docs/src/content/docs/ko/guides/sidebar.mdx
================================================
---
title: 사이드바 탐색
description: Starlight 사이트의 사이드바 탐색 링크를 설정하고 사용자 정의하는 방법을 알아보세요.
---

import { FileTree } from '@astrojs/starlight/components';
import SidebarPreview from '~/components/sidebar-preview.astro';

잘 구성된 사이드바는 사용자가 사이트를 탐색하는 주요 방법 중 하나이므로 좋은 문서의 핵심입니다. Starlight는 사이드바 레이아웃과 콘텐츠를 변경할 수 있는 완전한 옵션 세트를 제공합니다.

## 기본 사이드바

기본적으로 Starlight는 각 파일의 `title` 속성을 사이드바 항목으로 사용하여 자동으로 문서의 파일 시스템 구조 기반의 사이드바를 생성합니다.

예를 들어, 다음과 같은 파일 구조가 있다고 가정합니다.

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - andromeda.md
        - orion.md
      - stars/
        - betelgeuse.md

</FileTree>

다음 사이드바가 자동으로 생성됩니다.

<SidebarPreview
	config={[
		{
			label: 'constellations',
			items: [
				{ label: '안드로메다', link: '' },
				{ label: '오리온', link: '' },
			],
		},
		{
			label: 'stars',
			items: [{ label: '베텔게우스', link: '' }],
		},
	]}
/>

[자동 생성 그룹](#자동-생성-그룹) 섹션에서 자동으로 생성된 사이드바에 대해 자세히 알아보세요.

## 링크 및 링크 그룹 추가

`astro.config.mjs` 파일의 [`starlight.sidebar`](/ko/reference/configuration/#sidebar) 속성을 사용하여 사이드바 링크 및 링크 그룹 (접이식 헤더 및 하위 항목들)을 구성할 수 있습니다.

링크와 그룹을 결합하여 다양한 사이드바 레이아웃을 만들 수 있습니다.

### 내부 링크

`src/content/docs/`에서 `slug` 속성이 있는 객체를 사용하여 페이지로 이동하는 링크를 추가합니다.
링크된 페이지의 제목은 기본적으로 라벨로 사용됩니다.

예를 들어, 구성은 다음과 같습니다.

```js "slug:"
starlight({
	sidebar: [
		{ slug: 'constellations/andromeda' },
		{ slug: 'constellations/orion' },
	],
});
```

파일 구조는 다음과 같습니다.

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - andromeda.md
        - orion.md

</FileTree>

다음 사이드바가 생성됩니다.

<SidebarPreview
	config={[
		{ label: '안드로메다', link: '' },
		{ label: '오리온', link: '' },
	]}
/>

링크된 페이지의 프런트매터에서 추론된 값을 재정의하기 위해 `label`, [`translations`](#국제화) 및 [`attrs`](#사용자-정의-html-속성) 속성을 추가할 수 있습니다.

페이지 프런트매터에서 사이드바 모양을 제어하는 방법에 대한 자세한 내용은 ["자동 생성된 링크 사용자 정의"](#프런트매터에서-자동-생성된-링크-사용자-정의)를 참조하세요.

#### 내부 링크의 약어

페이지 슬러그에 대한 문자열만 약식으로 제공하여 내부 링크를 지정할 수도 있습니다.

예를 들어, 다음 구성은 `slug`를 사용한 위 구성과 동일합니다.

```js "slug:"
starlight({
	sidebar: ['constellations/andromeda', 'constellations/orion'],
});
```

### 기타 링크

`label` 및 `link` 속성이 있는 객체를 사용하여 외부 또는 문서가 아닌 페이지에 대한 링크를 추가합니다.

```js "label:" "link:"
starlight({
	sidebar: [
		// 이 사이트에서 문서가 아닌 페이지로 이동하는 링크
		{ label: '유성 상점', link: '/shop/' },
		// NASA 웹사이트로 이동하는 외부 링크
		{ label: 'NASA', link: 'https://www.nasa.gov/' },
	],
});
```

위 구성은 다음 사이드바를 생성합니다.

<SidebarPreview
	config={[
		{ label: '유성 상점', link: '/shop/' },
		{ label: 'NASA', link: 'https://www.nasa.gov/' },
	]}
/>

### 그룹

접을 수 있는 제목 아래 관련 링크를 그룹화하여 사이드바에 구조를 추가할 수 있습니다. 그룹에는 링크와 기타 하위 그룹이 모두 포함될 수 있습니다.

`label` 및 `items` 속성이 있는 객체를 사용하여 그룹을 추가합니다. `label`은 그룹의 제목으로 사용됩니다. `items` 배열에 링크나 하위 그룹을 추가할 수 있습니다.

```js /^\s*(label:|items:)/
starlight({
	sidebar: [
		// '별자리' 라벨이 붙은 링크 그룹
		{
			label: '별자리',
			items: [
				'constellations/carina',
				'constellations/centaurus',
				// 계절별 별자리에 대한 중첩된 링크 그룹
				{
					label: '계절별',
					items: [
						'constellations/andromeda',
						'constellations/orion',
						'constellations/ursa-minor',
					],
				},
			],
		},
	],
});
```

위 구성은 다음 사이드바를 생성합니다.

<SidebarPreview
	config={[
		{
			label: '별자리',
			items: [
				{ label: '용골자리', link: '' },
				{ label: '켄타우루스', link: '' },
				{
					label: '계절별',
					items: [
						{ label: '안드로메다', link: '' },
						{ label: '오리온', link: '' },
						{ label: '작은곰자리', link: '' },
					],
				},
			],
		},
	]}
/>

### 자동 생성 그룹

Starlight는 문서 디렉터리를 기반해서 자동으로 사이드바에 그룹을 생성할 수 있습니다. 이는 그룹의 각 사이드바 항목을 수동으로 입력하고 싶지 않을 때 유용합니다.

기본적으로 페이지는 파일 [`slug`](/ko/reference/route-data/#slug)에 따라 알파벳순으로 정렬됩니다.

`label` 및 `autogenerate` 속성이 있는 객체를 사용하여 자동 생성 그룹을 추가합니다. `autogenerate` 구성은 사이드바 항목에 사용할 디렉터리를 지정해야 합니다. 예를 들어, 다음 구성을 사용할 수 있습니다.

```js "label:" "autogenerate:"
starlight({
	sidebar: [
		{
			label: '별자리',
			// '별자리' 디렉토리에 대한 링크 그룹을 자동 생성
			autogenerate: { directory: 'constellations' },
		},
	],
});
```

파일 구조는 다음과 같습니다.

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - carina.md
        - centaurus.md
        - seasonal/
          - andromeda.md

</FileTree>

다음 사이드바가 생성됩니다:

<SidebarPreview
	config={[
		{
			label: '별자리',
			items: [
				{ label: '용골자리', link: '' },
				{ label: '켄타우루스', link: '' },
				{
					label: 'seasonal',
					items: [{ label: '안드로메다', link: '' }],
				},
			],
		},
	]}
/>

## 프런트매터에서 자동 생성된 링크 사용자 정의

자동으로 생성된 링크를 변경하려면 개별 페이지의 [`sidebar` 프런트매터 필드](/ko/reference/frontmatter/#sidebar)를 사용하세요.

프런트매터에서 sidebar 옵션을 사용하면 [사용자 정의 라벨](/ko/reference/frontmatter/#label)을 설정, [사용자 정의 속성](/ko/reference/frontmatter/#attrs) 사용, 링크에 [배지](/ko/reference/frontmatter/#badge) 추가, 사이드바에서 링크를 [숨기거나](/ko/reference/frontmatter/#hidden) [사용자 정의 정렬 기준](/ko/reference/frontmatter/#order)을 정의할 수 있습니다.

```md "sidebar:"
---
# src/content/docs/example.md
title: 나의 페이지
sidebar:
  # 링크에 대한 사용자 정의 라벨 설정
  label: 사용자 정의 사이드바 라벨
  # 링크에 대한 사용자 정의 순서 설정 (숫자가 낮을수록 더 위에 표시됩니다.)
  order: 2
  # 링크에 배지 추가
  badge:
    text: New
    variant: tip
---
```

위 프런트매터가 있는 페이지를 포함하는 자동 생성 그룹은 다음 사이드바를 생성합니다.

<SidebarPreview
	config={[
		{
			label: '안내서',
			items: [
				{ label: '페이지', link: '' },
				{
					label: '사용자 정의 사이드바 라벨',
					link: '',
					badge: { text: 'New', variant: 'tip' },
				},
				{ label: '기타 페이지', link: '' },
			],
		},
	]}
/>

:::note
`sidebar` 프런트매터 구성은 `slug` 속성으로 정의된 자동으로 생성된 그룹의 링크 및 문서 링크에만 사용됩니다. `link` 속성으로 정의된 링크에는 적용되지 않습니다.
:::

## 배지

링크, 그룹, 자동 생성된 그룹은 라벨 옆에 배지를 표시하기 위해 `badge` 속성을 포함할 수도 있습니다.

```js {9,16}
starlight({
	sidebar: [
		{
			label: '별',
			items: [
				// "초거성" 배지가 있는 링크
				{
					link: '/stars/persei/',
					badge: '초거성',
				},
			],
		},
		// "Outdated" 배지가 있는 자동 생성된 그룹
		{
			label: '위성',
			badge: 'Outdated',
			autogenerate: { directory: 'moons' },
		},
	],
});
```

위 구성은 다음 사이드바를 생성합니다.

<SidebarPreview
	config={[
		{
			label: '별',
			items: [
				{
					label: '페르세우스',
					link: '',
					badge: { text: '초거성', variant: 'default' },
				},
			],
		},
		{
			label: '위성',
			badge: { text: 'Outdated', variant: 'default' },
			items: [
				{
					label: '이오',
					link: '',
				},
				{
					label: '유로파',
					link: '',
				},
				{
					label: '가니메데',
					link: '',
				},
			],
		},
	]}
/>

### 배지 변형 및 맞춤 스타일

`text`, `variant`, `class` 속성이 있는 객체를 사용하여 배지 스타일을 맞춤설정하세요.

`text`는 표시할 콘텐츠 (예: "New")를 나타냅니다.
기본적으로 배지는 사이트의 강조 색상을 사용합니다. 내장된 배지 스타일을 사용하려면 `variant` 속성의 값을 `note`, `tip`, `danger`, `caution`, `success` 중 하나로 설정하세요.

선택적으로 `class` 속성을 CSS 클래스 이름으로 설정하여 사용자 정의 배지 스타일을 만들 수 있습니다.

```js {9}
starlight({
	sidebar: [
		{
			label: '별',
			items: [
				// 노란색 "Stub" 배지가 있는 링크
				{
					link: '/stars/sirius/',
					badge: { text: 'Stub', variant: 'caution' },
				},
			],
		},
	],
});
```

위 구성은 다음 사이드바를 생성합니다.

<SidebarPreview
	config={[
		{
			label: '별',
			items: [
				{
					label: '시리우스',
					link: '',
					badge: { text: 'Stub', variant: 'caution' },
				},
			],
		},
	]}
/>

[배지를 사용하고 사용자 정의하는 방법](/ko/components/badges/#사용)에 대해 자세히 알아보세요.

## 사용자 정의 HTML 속성

링크에는 사용자 정의 HTML 속성을 추가하기 위한 `attrs` 속성이 포함될 수도 있습니다.

다음 예에서는 `attrs`를 사용하여 링크가 새 탭에서 열리도록 `target="_blank"` 속성을 추가하고 사용자 정의 스타일 속성을 적용하여 링크 레이블을 기울임꼴로 표시합니다.

다음 예에서는 링크가 새 탭에서 열리도록 `target="_blank` 속성을 추가하고, 사용자 정의 `style` 속성을 적용하여 링크 레이블을 기울임꼴로 표시하기 위해 `attrs`를 사용합니다.

```js {10}
starlight({
	sidebar: [
		{
			label: '리소스',
			items: [
				// 새 탭에서 열리는 NASA 웹사이트로 이동하는 외부 링크
				{
					label: 'NASA',
					link: 'https://www.nasa.gov/',
					attrs: { target: '_blank', style: 'font-style: italic' },
				},
			],
		},
	],
});
```

위 구성은 다음 사이드바를 생성합니다.

<SidebarPreview
	config={[
		{
			label: '리소스',
			items: [
				{
					label: 'NASA',
					link: 'https://www.nasa.gov/',
					attrs: {
						target: '_blank',
						style: 'font-style: italic',
					},
				},
			],
		},
	]}
/>

### 자동 생성 링크의 사용자 정의 HTML 속성

`autogenerate` 구성의 `attrs` 속성을 정의하여 [자동 생성 그룹](#자동-생성-그룹)에 있는 모든 링크의 HTML 속성을 사용자 정의합니다.
개별 페이지에서는 [`sidebar.attrs` 프런트매터 필드](/ko/reference/frontmatter/#attrs)를 사용하여 사용자 정의 속성을 지정할 수 있으며, 이는 `autogenerate.attrs` 구성과 병합됩니다.

예를 들어, 다음과 같은 구성을 사용할 수 있습니다.

```js {9}
starlight({
	sidebar: [
		{
			label: '별자리',
			autogenerate: {
				// 'constellations' 디렉터리에 대한 링크 그룹을 자동으로 생성합니다.
				directory: 'constellations',
				// 이 그룹의 모든 링크 라벨을 이탤릭체로 표시합니다.
				attrs: { style: 'font-style: italic' },
			},
		},
	],
});
```

그리고 파일 구조는 다음과 같습니다.

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - carina.md
        - centaurus.md
        - seasonal/
          - andromeda.md

</FileTree>

다음과 같이 모든 자동 생성 링크가 이탤릭체로 표시된 사이드바가 생성됩니다.

<SidebarPreview
	config={[
		{
			label: '별자리',
			items: [
				{ label: '용골자리', link: '', attrs: { style: 'font-style: italic' } },
				{
					label: '켄타우루스',
					link: '',
					attrs: { style: 'font-style: italic' },
				},
				{
					label: 'seasonal',
					items: [
						{
							label: '안드로메다',
							link: '',
							attrs: { style: 'font-style: italic' },
						},
					],
				},
			],
		},
	]}
/>

## 국제화

[BCP-47](https://www.w3.org/International/questions/qa-choosing-language-tags) 언어 태그를 지정하여 지원되는 각 언어에 대한 링크 또는 그룹 라벨을 번역하려면 링크 및 그룹 항목의 `translations` 속성을 사용하세요. `"en"`, `"ar"` 또는 `"zh-CN"`을 키로, 번역된 라벨을 값으로 사용합니다.
`label` 속성은 기본 언어 및 번역이 제공되지 않는 언어를 위해 사용될 것입니다.

```js {5-7,11-13,18-20}
starlight({
	sidebar: [
		{
			label: '별자리',
			translations: {
				'pt-BR': 'Constelações',
			},
			items: [
				{
					label: '안드로메다',
					translations: {
						'pt-BR': 'Andrômeda',
					},
					slug: 'constellations/andromeda/',
				},
				{
					label: '전갈자리',
					translations: {
						'pt-BR': 'Escorpião',
					},
					slug: 'constellations/scorpius/',
				},
			],
		},
	],
});
```

브라질 포르투갈어로 문서를 검색하면 다음 사이드바가 생성됩니다.

<SidebarPreview
	config={[
		{
			label: 'Constelação',
			items: [
				{ label: 'Andrômeda', link: '' },
				{ label: 'Escorpião', link: '' },
			],
		},
	]}
/>

### 내부 링크 국제화

[내부 링크](#내부-링크)는 기본적으로 콘텐츠 프런트매터의 번역된 페이지 제목을 자동으로 사용합니다.

```js {9-10}
starlight({
	sidebar: [
		{
			label: '별자리',
			translations: {
				'pt-BR': 'Constelações',
			},
			items: [
				{ slug: 'constellations/andromeda' },
				{ slug: 'constellations/scorpius' },
			],
		},
	],
});
```

브라질 포르투갈어로 문서를 탐색하면 다음 사이드바가 생성됩니다.

<SidebarPreview
	config={[
		{
			label: 'Constelações',
			items: [
				{ label: 'Andrômeda', link: '' },
				{ label: 'Escorpião', link: '' },
			],
		},
	]}
/>

다국어 사이트에서는 `slug` 값에 URL의 언어 부분이 포함되지 않습니다.
예를 들어 `en/intro` 및 `pt-br/intro`에 페이지가 있는 경우, 사이드바를 구성할 때 슬러그는 `intro`입니다.

### 배지 국제화

[배지](#배지)의 경우 `text` 속성은 문자열이며, 다국어 사이트의 경우 각 로케일별 값이 포함된 객체일 수 있습니다.
객체 양식을 사용하는 경우 키는 [BCP-47](https://www.w3.org/International/questions/qa-choosing-language-tags) 태그 (예: `en`, `ar` 또는 `zh-CN`)여야 합니다:

```js {11-16}
starlight({
	sidebar: [
		{
			label: '별자리',
			translations: {
				'pt-BR': 'Constelações',
			},
			items: [
				{
					slug: 'constellations/andromeda',
					badge: {
						text: {
							ko: '새 항목',
							'pt-BR': 'Novo',
						},
					},
				},
			],
		},
	],
});
```

브라질 포르투갈어로 문서를 검색하면 다음과 같은 사이드바가 생성됩니다:

<SidebarPreview
	config={[
		{
			label: 'Constelações',
			items: [
				{
					label: 'Andrômeda',
					link: '',
					badge: { text: 'Novo', variant: 'default' },
				},
			],
		},
	]}
/>

## 그룹 축소

`collapsed` 속성을 `true`로 설정하면 링크 그룹의 기본 상태를 접힌 상태로 만들 수 있습니다.

```js {5-6}
starlight({
	sidebar: [
		{
			label: '별자리',
			// 기본적으로 그룹을 축소
			collapsed: true,
			items: ['constellations/andromeda', 'constellations/orion'],
		},
	],
});
```

위 구성은 다음 사이드바를 생성합니다.

<SidebarPreview
	config={[
		{
			label: '별자리',
			collapsed: true,
			items: [
				{ label: '안드로메다', link: '' },
				{ label: '오리온', link: '' },
			],
		},
	]}
/>

[자동 생성 그룹](#자동-생성-그룹)은 상위 그룹의 `collapsed` 값을 따릅니다.

```js {5-6}
starlight({
	sidebar: [
		{
			label: '별자리',
			// 그룹 및 자동으로 생성된 하위 그룹의 기본 상태가 접힌 상태가 됩니다.
			collapsed: true,
			autogenerate: { directory: 'constellations' },
		},
	],
});
```

위 구성은 다음 사이드바를 생성합니다.

<SidebarPreview
	config={[
		{
			label: '별자리',
			collapsed: true,
			items: [
				{ label: '용골자리', link: '' },
				{ label: '켄타우루스', link: '' },
				{
					label: 'seasonal',
					collapsed: true,
					items: [{ label: '안드로메다', link: '' }],
				},
			],
		},
	]}
/>

`autogenerate.collapsed` 속성을 정의하여 이 동작을 변경할 수 있습니다.

```js {5-7} "collapsed: true"
starlight({
	sidebar: [
		{
			label: '별자리',
			// "별자리" 그룹을 축소하지 말고 자동 생성된 하위 그룹을 축소합니다.
			collapsed: false,
			autogenerate: { directory: 'constellations', collapsed: true },
		},
	],
});
```

위 구성은 다음 사이드바를 생성합니다.

<SidebarPreview
	config={[
		{
			label: '별자리',
			items: [
				{ label: '용골자리', link: '' },
				{ label: '켄타우루스', link: '' },
				{
					label: 'seasonal',
					collapsed: true,
					items: [{ label: '안드로메다', link: '' }],
				},
			],
		},
	]}
/>


================================================
FILE: docs/src/content/docs/ko/guides/site-search.mdx
================================================
---
title: 사이트 검색
description: Starlight에 내장된 사이트 검색 기능과 이를 사용자 정의하는 방법에 대해 알아보세요.
tableOfContents:
  maxHeadingLevel: 4
---

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

기본적으로 Starlight 사이트에는 정적 사이트를 위한 빠르고 낮은 대역폭을 갖춘 검색 도구인 [Pagefind](https://pagefind.app/)에서 제공하는 전체 텍스트 검색이 포함되어 있습니다.

검색을 활성화하는 데 구성이 필요하지 않습니다. 사이트를 구축하고 배포한 다음, 사이트 헤더의 검색창을 사용하여 콘텐츠를 찾을 수 있습니다.

## 검색결과에서 콘텐츠 숨기기

### 페이지 제외

검색 색인에서 페이지를 제외하려면 페이지 프런트매터에 [`pagefind: false`](/ko/reference/frontmatter/#pagefind)를 추가하세요.

```md title="src/content/docs/not-indexed.md" ins={3}
---
title: 검색에서 숨길 콘텐츠
pagefind: false
---
```

### 페이지 일부 제외

Pagefind는 [`data-pagefind-ignore`](https://pagefind.app/docs/indexing/#removing-individual-elements-from-the-index) 속성이 있는 요소 내부의 콘텐츠를 무시합니다.

다음 예시에서 첫 번째 단락은 검색 결과에 표시되지만 `<div>`의 내용은 표시되지 않습니다.

```md title="src/content/docs/partially-indexed.md" ins="data-pagefind-ignore"
---
title: 부분적으로 색인이 생성된 페이지
---

이 텍스트는 검색을 통해 찾을 수 있습니다.

<div data-pagefind-ignore>

이 텍스트는 검색에서 숨겨집니다.

</div>
```

## 대체 검색 공급자

### Algolia DocSearch

[Algolia의 DocSearch 프로그램](https://docsearch.algolia.com/)에 대한 액세스 권한이 있고, 이를 Pagefind 대신 사용하려는 경우, 공식 Starlight DocSearch 플러그인을 사용할 수 있습니다.

<Steps>

1. `@astrojs/starlight-docsearch`를 설치합니다.

   <Tabs syncKey="pkg">

   <TabItem label="npm">

   ```sh
   npm install @astrojs/starlight-docsearch
   ```

   </TabItem>

   <TabItem label="pnpm">

   ```sh
   pnpm add @astrojs/starlight-docsearch
   ```

   </TabItem>

   <TabItem label="Yarn">

   ```sh
   yarn add @astrojs/starlight-docsearch
   ```

   </TabItem>

   </Tabs>

2. `astro.config.mjs` 파일의 Starlight [`plugins`](/ko/reference/configuration/#plugins) 구성에 DocSearch를 추가하고 Algolia `appId`, `apiKey`, `indexName`를 전달합니다.

   ```js ins={4,10-16}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';
   import starlightDocSearch from '@astrojs/starlight-docsearch';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'DocSearch를 사용하는 사이트',
   			plugins: [
   				starlightDocSearch({
   					appId: 'YOUR_APP_ID',
   					apiKey: 'YOUR_SEARCH_API_KEY',
   					indexName: 'YOUR_INDEX_NAME',
   				}),
   			],
   		}),
   	],
   });
   ```

</Steps>

이 업데이트된 구성을 사용하면 사이트의 검색 창에서 기본 검색 모달 대신 Algolia 모달이 열립니다.

#### DocSearch 구성

Starlight DocSearch 플러그인은 다음과 같은 인라인 옵션을 통해 DocSearch 컴포넌트를 사용자 지정할 수 있습니다:

- `maxResultsPerGroup`: 각 검색 그룹에 표시되는 결과 수를 제한합니다. 기본값은 `5`입니다.
- `disableUserPersonalization`: DocSearch가 사용자의 최근 검색 및 즐겨찾기를 로컬 스토리지에 저장하지 못하도록 합니다. 기본값은 `false`입니다.
- `insights`: Algolia Insights 플러그인을 활성화하고 검색 이벤트를 DocSearch 인덱스로 보냅니다. 기본값은 `false`입니다.
- `searchParameters`: [Algolia Search Parameters](https://www.algolia.com/doc/api-reference/search-api-parameters/)를 사용자 정의하는 객체입니다.

##### 추가 DocSearch 옵션

`transformItems()` 또는 `resultsFooterComponent()`와 같은 함수 옵션을 DocSearch 컴포넌트에 전달하려면 별도의 구성 파일이 필요합니다.

<Steps>

1. DocSearch 구성을 내보내는 TypeScript 파일을 만듭니다.

   ```ts
   // src/config/docsearch.ts
   import type { DocSearchClientOptions } from '@astrojs/starlight-docsearch';

   export default {
   	appId: 'YOUR_APP_ID',
   	apiKey: 'YOUR_SEARCH_API_KEY',
   	indexName: 'YOUR_INDEX_NAME',
   	getMissingResultsUrl({ query }) {
   		return `https://github.com/algolia/docsearch/issues/new?title=${query}`;
   	},
   	// ...
   } satisfies DocSearchClientOptions;
   ```

2. `astro.config.mjs`의 Starlight DocSearch 플러그인에 구성 파일 경로를 전달합니다.

   ```js {11-13}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';
   import starlightDocSearch from '@astrojs/starlight-docsearch';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Site with DocSearch',
   			plugins: [
   				starlightDocSearch({
   					clientOptionsModule: './src/config/docsearch.ts',
   				}),
   			],
   		}),
   	],
   });
   ```

</Steps>

지원되는 모든 옵션은 [DocSearch JavaScript 클라이언트 API 참조](https://docsearch.algolia.com/docs/api/)를 확인하세요.

#### DocSearch UI 번역

DocSearch는 기본적으로 영어 UI 문자열만 제공합니다.
Starlight에 내장된 [국제화 시스템](/ko/guides/i18n/#starlight-ui-번역)을 사용하여 모달 UI 번역을 추가하세요.

<Steps>

1. `src/content.config.ts` 파일의 DocSearch 스키마를 사용하여 Starlight의 `i18n` 콘텐츠 컬렉션 정의를 확장합니다.

   ```js ins={5} ins=/{ extend: .+ }/
   // src/content.config.ts
   import { defineCollection } from 'astro:content';
   import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
   import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';
   import { docSearchI18nSchema } from '@astrojs/starlight-docsearch/schema';

   export const collections = {
   	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
   	i18n: defineCollection({
   		loader: i18nLoader(),
   		schema: i18nSchema({ extend: docSearchI18nSchema() }),
   	}),
   };
   ```

2. `src/content/i18n/` 디렉터리에 있는 JSON 파일에 번역을 추가하세요.

   DocSearch에서 사용되는 영어 기본값은 다음과 같습니다.

   ```json title="src/content/i18n/en.json"
   {
   	"docsearch.searchBox.resetButtonTitle": "Clear the query",
   	"docsearch.searchBox.resetButtonAriaLabel": "Clear the query",
   	"docsearch.searchBox.cancelButtonText": "Cancel",
   	"docsearch.searchBox.cancelButtonAriaLabel": "Cancel",
   	"docsearch.searchBox.searchInputLabel": "Search",

   	"docsearch.startScreen.recentSearchesTitle": "Recent",
   	"docsearch.startScreen.noRecentSearchesText": "No recent searches",
   	"docsearch.startScreen.saveRecentSearchButtonTitle": "Save this search",
   	"docsearch.startScreen.removeRecentSearchButtonTitle": "Remove this search from history",
   	"docsearch.startScreen.favoriteSearchesTitle": "Favorite",
   	"docsearch.startScreen.removeFavoriteSearchButtonTitle": "Remove this search from favorites",

   	"docsearch.errorScreen.titleText": "Unable to fetch results",
   	"docsearch.errorScreen.helpText": "You might want to check your network connection.",

   	"docsearch.footer.selectText": "to select",
   	"docsearch.footer.selectKeyAriaLabel": "Enter key",
   	"docsearch.footer.navigateText": "to navigate",
   	"docsearch.footer.navigateUpKeyAriaLabel": "Arrow up",
   	"docsearch.footer.navigateDownKeyAriaLabel": "Arrow down",
   	"docsearch.footer.closeText": "to close",
   	"docsearch.footer.closeKeyAriaLabel": "Escape key",
   	"docsearch.footer.searchByText": "Search by",

   	"docsearch.noResultsScreen.noResultsText": "No results for",
   	"docsearch.noResultsScreen.suggestedQueryText": "Try searching for",
   	"docsearch.noResultsScreen.reportMissingResultsText": "Believe this query should return results?",
   	"docsearch.noResultsScreen.reportMissingResultsLinkText": "Let us know."
   }
   ```

</Steps>

### 커뮤니티 검색 공급자

[커뮤니티 플러그인](/ko/resources/plugins/#커뮤니티-플러그인)은 Starlight의 기본 Pagefind 검색 공급자에 대한 대안을 제공할 수도 있습니다.

#### Typesense DocSearch

[Starlight DocSearch Typesense](https://starlight-docsearch.typesense.org/) 커뮤니티 플러그인은 [DocSearch](https://github.com/typesense/typesense-docsearch.js) 인터페이스와 [Typesense](https://typesense.org/) 백엔드를 통합하는 자체 호스팅 가능한 오픈 소스 대안을 제공합니다.

프로젝트에서 사용하는 방법을 알아보려면 Starlight DocSearch Typesense 문서의 [“시작하기”](https://starlight-docsearch.typesense.org/getting-started/) 가이드를 참조하세요.


================================================
FILE: docs/src/content/docs/ko/index.mdx
================================================
---
title: Starlight 🌟 Astro 문서 웹 사이트를 만드세요
head:
  - tag: title
    content: Starlight 🌟 Astro 문서 웹 사이트를 만드세요
description: Starlight로 아름답고 성능이 좋은 Astro 문서 웹 사이트를 만들 수 있습니다.
template: splash
editUrl: false
lastUpdated: false
hero:
  title: Starlight로 멋진 문서를 만드세요
  tagline: 아름다운 문서 웹 사이트를 만드는데 필요한 모든 것. 빠르고, 접근성이 좋으며 사용하기 쉽습니다.
  image:
    file: ~/assets/hero-star.webp
  actions:
    - text: 시작하기
      icon: right-arrow
      link: /ko/getting-started/
    - text: GitHub에서 보기
      icon: external
      variant: minimal
      link: https://github.com/withastro/starlight
---

import { CardGrid, Card } from '@astrojs/starlight/components';
import AboutAstro from '~/components/about-astro.astro';
import TestimonialGrid from '~/components/testimonial-grid.astro';
import Testimonial from '~/components/testimonial.astro';

<CardGrid stagger>
	<Card title="아름다운 문서" icon="open-book">
		사이트 탐색, 검색, 국제화, SEO, 읽기 쉬운 타이포그래피, 구문 강조, 어두운
		테마 등이 포함되어 있습니다.
	</Card>
	<Card title="Astro 기반" icon="rocket">
		Astro의 힘과 성능을 활용하세요. 선호하는 Astro 통합 및 라이브러리로
		Starlight를 확장하세요.
	</Card>
	<Card title="Markdown, Markdoc, MDX" icon="document">
		선호하는 마크업 언어를 사용하세요. Starlight는 TypeScript 타입 안정성을 갖춘
		내장 프론트매터 유효성 검사를 제공합니다.
	</Card>
	<Card title="선호하는 UI 컴포넌트 사용" icon="puzzle">
		Starlight는 프레임워크에 구애받지 않는 완벽한 문서 솔루션으로 제공됩니다.
		React, Vue, Svelte, Solid 등으로 확장하세요.
	</Card>
</CardGrid>

<TestimonialGrid title="사용 후기를 들어보세요">
  <Testimonial
    name="Rachel"
    handle="rachelnabors"
    cite="https://twitter.com/astrodotbuild/status/1724934718745915558"
  >
    Astro 팀은 문서 작성 방법을 발전시켰으며 Starlight 프로젝트를 통해 모든 것을 즉시 사용할 수 있습니다.
  </Testimonial>
  <Testimonial
    name="Flavio"
    handle="flaviocopes"
    cite="https://twitter.com/flaviocopes/status/1738237658717905108"
  >
    Astro의 공식 시작 키트인 Starlight는 문서 웹 사이트 구축을 위한 정말 놀라운 도구입니다.
  </Testimonial>
  <Testimonial
    name="Tomek"
    handle="sulco"
    cite="https://twitter.com/sulco/status/1735610348730802342"
  >
    Starlight는 훌륭한 DX의 대표적인 예시입니다. 속도, 편리함, 세부 사항에 대한 관심이 인상적입니다. 기술과 디자인을 모두 관리하므로 콘텐츠에 집중할 수 있습니다 👏

    StackBlitz 팀은 이 프로젝트를 정말 좋아합니다!

  </Testimonial>
  <Testimonial
    name="Roberto"
    handle="RmeetsH"
    cite="https://twitter.com/RmeetsH/status/1735783992018760090"
  >
    Starlight는 제가 콘텐츠 제작에 집중할 수 있게 해준 게임 체인저였습니다.

    직관적인 디자인은 작업 흐름을 간소화할 뿐만 아니라 오픈 소스 개발자의 온보딩 시간도 줄여줍니다.

  </Testimonial>
  <Testimonial
    name="Joel"
    handle="jhooks"
    cite="https://twitter.com/jhooks/status/1727405160547418405"
  >
    Course Builder 문서를 구축하기 위해 Starlight를 오래 사용하였으며 지금까지는 훌륭합니다. 많은 부분이 잘 만들어져 있기 때문에 사이트를 만지작거리지 않고 Markdown을 작성하는 데 집중할 수 있습니다.
  </Testimonial>
  <Testimonial
    name="Rick"
    handle="rick_viscomi"
    cite="https://twitter.com/rick_viscomi/status/1665867447910510593"
  >
    Starlight를 사용하기 시작했습니다. 기본적으로 제공되는 성능에 깊은 인상을 받았습니다.

    💯💯💯💯

  </Testimonial>
  <Testimonial
    name="Nicolas"
    handle="beaussan"
    cite="https://twitter.com/beaussan/status/1735625189583466893"
  >
    Starlight는 문서화를 시작하는 가장 좋은 방법입니다. Astro의 성능과 속도 및 Starlight 도구는 환상의 조합입니다.

    한동안 계속 사용하였고, 계속해서 좋아하고 있어요!

  </Testimonial>
  <Testimonial
    name="Sylwia"
    handle="SylwiaVargas"
    cite="https://x.com/SylwiaVargas/status/1726556825741578286"
  >
    나는 지난 직장에서 Starlight를 사용했고 정말 좋아했습니다. 훌륭한 컴포넌트, 직관적인 디자인, 반응이 빠른 커뮤니티 (누군가 필요한 것이 있을 때마다 즉시 배송하거나 해결 방법을 알려줍니다). 매우 즐거운 경험이었어요.
  </Testimonial>
  <Testimonial
    name="Lou Cyx"
    handle="loucyx"
    cite="https://elk.zone/m.webtoo.ls/@loucyx@mastodon.social/111587380021362284"
  >
    내 모노레포 사이트의 문서는 Starlight 덕분에 그 어느 때보다 좋아 보입니다. Astro의 모든 기능을 잃지 않고 사용하기가 매우 쉽습니다. 작업해 주셔서 감사합니다!
  </Testimonial>
  <Testimonial
    name="BowTiedWebReaper"
    handle="BowTiedWebReapr"
    cite="https://twitter.com/BowTiedWebReapr/status/1735633399501697517"
  >
    Starlight는 문서화를 위해 제가 즐겨 사용하는 도구입니다. 다른 도구와 함께 사용하기 위해 하위 도메인이 필요한 것에 비해 기존 Astro 제품 웹사이트에 문서를 추가하는 것이 매우 쉬워졌습니다.
  </Testimonial>
  <Testimonial
    name="Jeff"
    handle="J_Everhart383"
    cite="https://twitter.com/J_Everhart383/status/1691900590048292908"
  >
    저는 WPEngine Atlas 플랫폼 문서를 다시 작성했습니다. Starlight에 A+ 문서 플랫폼을 만드는 데 필요한 모든 것이 있다고 말할 때 저를 믿으십시오. 🙌
  </Testimonial>
  <Testimonial
    name="Chloe"
    handle="solelychloe"
    cite="https://twitter.com/solelychloe/status/1695115277602628082"
  >
    Starlight를 사용해 보세요!

    나는 내 사이트 중 일부에 이 프로젝트를 사용하고 있으며 훌륭합니다.

  </Testimonial>
</TestimonialGrid>

<AboutAstro title="제공">
Astro는 빠른 속도를 위해 설계된 올인원 웹 프레임워크입니다. 선호하는 UI 컴포넌트와 라이브러리를 사용하여 어디서든 콘텐츠를 가져와 배포하세요.

[Astro에 대해 알아보기](https://astro.build/)

</AboutAstro>


================================================
FILE: docs/src/content/docs/ko/manual-setup.mdx
================================================
---
title: 수동으로 설정하기
description: Starlight를 기존 Astro 프로젝트에 추가하기 위해 수동으로 구성하는 방법을 알아보세요.
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

새로운 Starlight 사이트를 시작하는 가장 빠른 방법은 [시작하기](/ko/getting-started/#새-프로젝트-생성)에 나와있는 것처럼 `create astro`를 사용하는 것입니다. 이 가이드에서는 기존 Astro 프로젝트에 Starlight를 추가하는 방법을 설명합니다.

## Starlight 설정

이 가이드를 따르기 위해서는 기존 Astro 프로젝트가 필요합니다.

### Starlight 통합 추가

Starlight는 [Astro 통합](https://docs.astro.build/ko/guides/integrations-guide/)입니다. 사이트에 이를 추가하기 위해 프로젝트의 루트 디렉터리에서 `astro add` 명령을 실행하세요.

<Tabs syncKey="pkg">
    <TabItem label="npm">
        ```sh
        npx astro add starlight
        ```

    </TabItem>
    <TabItem label="pnpm">
        ```sh
        pnpm astro add starlight
        ```
    </TabItem>
    <TabItem label="Yarn">
        ```sh
        yarn astro add starlight
        ```
    </TabItem>

</Tabs>

그러면 필요한 종속성이 설치되고 Astro 구성 파일의 `integrations` 배열에 Starlight가 추가됩니다.

### 통합 구성

Starlight 통합은 `astro.config.mjs` 파일에서 구성됩니다.

시작하려면 `title`을 추가하세요.

```js ins={8}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: '나만의 멋진 문서 사이트',
		}),
	],
});
```

[Starlight 구성 참조](/ko/reference/configuration/)에서 사용 가능한 모든 옵션을 찾아보세요.

### 콘텐츠 컬렉션 구성

Starlight는 `src/content.config.ts` 파일에 구성된 Astro의 [콘텐츠 컬렉션](https://docs.astro.build/ko/guides/content-collections/) 위에 구축되었습니다.

Starlight의 [`docsLoader`](/ko/reference/configuration/#docsloader) 및 [`docsSchema`](/ko/reference/configuration/#docsschema)를 사용하는 `docs` 컬렉션을 추가하여 콘텐츠 구성 파일을 생성하거나 업데이트하세요.

```js ins={3-4,7}
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
};
```

Starlight는 레거시 콘텐츠 컬렉션 구현을 사용하여 컬렉션을 처리하는 [`legacy.collections` 플래그](https://docs.astro.build/ko/reference/legacy-flags/)도 지원합니다.
이 플래그는 기존 Astro 프로젝트가 있고 현재 로더를 사용하기 위해 컬렉션을 변경할 수 없는 경우에 유용합니다.

### 콘텐츠 추가

이제 Starlight가 구성되었으며 콘텐츠를 추가할 시간입니다!

`src/content/docs/` 디렉터리를 생성한 후 `index.md` 파일을 추가하여 시작하세요.
이것은 웹 사이트의 홈페이지가 됩니다.

```md
---
# src/content/docs/index.md
title: 나의 문서
description: Starlight로 구축된 이 문서 사이트에서 내 프로젝트에 대해 자세히 알아보세요.
---

내 프로젝트에 오신 것을 환영합니다!
```

Starlight는 파일 기반 라우팅을 사용합니다. 즉, `src/content/docs/`에 있는 모든 Markdown, MDX 또는 Markdoc 파일이 사이트의 페이지로 전환됩니다. Frontmatter 메타데이터(위 예시에서 `title` 및 `description` 필드)는 각 페이지가 표시되는 방식을 변경할 수 있습니다. [Frontmatter 참조](/ko/reference/frontmatter/)에서 사용 가능한 모든 옵션을 확인하세요.

## 기존 웹 사이트에 대한 팁

기존 Astro 프로젝트가 존재하는 경우 Starlight를 사용하여 사이트에 문서 섹션을 빠르게 추가할 수 있습니다.

### 하위 경로에서 Starlight 사용

모든 Starlight 페이지를 하위 경로에 추가하려면 모든 문서 콘텐츠를 `src/content/docs/`의 하위 디렉터리에 배치하세요.

예를 들어, Starlight의 모든 페이지가 `/guides/`에서 시작해야 하는 경우 `src/content/docs/guides/` 디렉터리에 콘텐츠를 추가하세요.

import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src/
  - content/
    - docs/
      - **guides/**
        - guide.md
        - index.md
  - pages/
- astro.config.mjs

</FileTree>

앞으로 우리는 `src/content/docs/`에 추가로 중첩된 디렉터리가 필요하지 않도록 이 사용 사례에 대한 지원을 더 늘릴 예정입니다.

### SSR과 함께 Starlight 사용

SSR을 사용하려면 Astro 문서에 있는 ["요청 시 렌더링 어댑터"](https://docs.astro.build/ko/guides/on-demand-rendering/) 가이드에 따라 Starlight 프로젝트에 서버 어댑터를 추가하세요.

Starlight에서 생성된 문서 페이지는 프로젝트의 출력 모드에 관계없이 기본적으로 미리 렌더링됩니다. Starlight 페이지의 사전 렌더링을 선택 해제하려면 [`prerender` 구성 옵션](/ko/reference/configuration/#prerender)을 `false`로 설정하세요.


================================================
FILE: docs/src/content/docs/ko/reference/configuration.mdx
================================================
---
title: 구성 참조
description: Starlight가 지원하는 모든 구성 옵션에 대한 개요입니다.
---

## `starlight` 통합 구성

Starlight는 [Astro](https://astro.build) 웹 프레임워크 위에 구축된 통합입니다. `astro.config.mjs` 구성 파일에서 프로젝트를 구성할 수 있습니다.

```js
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: '즐거운 문서 사이트',
		}),
	],
});
```

`starlight` 통합에 다음 옵션을 전달할 수 있습니다.

### `title` (필수)

**타입:** `string | Record<string, string>`

웹사이트의 제목을 설정합니다. 메타데이터 및 브라우저 탭 제목에 사용됩니다.

값은 문자열일 수도 있고, 다국어 사이트의 경우 각기 다른 로케일에 대한 값이 포함된 객체일 수도 있습니다.
객체 형식을 사용할 때 키는 BCP-47 태그(예: `en`, `ar` 또는 `zh-CN`)여야 합니다.

```ts
starlight({
	title: {
		en: 'My delightful docs site',
		de: 'Meine bezaubernde Dokumentationsseite',
	},
});
```

### `description`

**타입:** `string`

웹사이트에 대한 설명을 설정합니다. 페이지의 프론트매터에 `description`이 설정되지 않은 경우, `<meta name="description">` 태그에서 검색 엔진과 공유되는 메타데이터로 사용됩니다.

### `logo`

**타입:** [`LogoConfig`](#logoconfig)

사이트 제목을 대체하거나 사이트 제목과 함께 네비게이션 바에 표시되는 로고 이미지를 설정합니다. 단일 `src` 속성을 설정하거나 `light` 및 `dark` 속성에 다른 이미지 소스를 전달할 수 있습니다.

```js
starlight({
	logo: {
		src: './src/assets/my-logo.svg',
	},
});
```

#### `LogoConfig`

```ts
type LogoConfig = { alt?: string; replacesTitle?: boolean } & (
	| { src: string }
	| { light: string; dark: string }
);
```

### `tableOfContents`

**타입:** `false | { minHeadingLevel?: number; maxHeadingLevel?: number }`  
**기본값:** `{ minHeadingLevel: 2, maxHeadingLevel: 3 }`

각 페이지 오른쪽에 표시되는 목차를 구성합니다. 기본적으로 `<h2>` 및 `<h3>` 제목이 이 목차에 포함됩니다.

### `editLink`

**타입:** `{ baseUrl: string }`

기본 URL을 설정하여 "페이지 편집" 링크를 활성화합니다. 최종 링크는 `editLink.baseUrl` + 현재 페이지 경로가 됩니다. 예를 들어, 다음 코드를 통해 GitHub의 `withastro/starlight` 저장소의 페이지 편집 기능을 활성화할 수 있습니다.

```js
starlight({
	editLink: {
		baseUrl: 'https://github.com/withastro/starlight/edit/main/',
	},
});
```

이 구성을 통해 `/introduction` 페이지에 있는 편집 링크는 `https://github.com/withastro/starlight/edit/main/src/content/docs/introduction.md`를 가리킵니다.

### `sidebar`

**타입:** [`SidebarItem[]`](#sidebaritem)

사이트의 사이드바 탐색 항목을 구성합니다.

사이드바는 링크의 배열과 링크 그룹입니다.
`slug`를 사용하는 항목을 제외하고, 각 항목은 `label`과 함께 다음 속성 중 하나를 반드시 포함해야합니다.

- `link` — 특정 URL에 대한 단일 링크(예: `'/home'` 또는 `'https://example.com'`).

- `slug` — 내부 페이지에 대한 참조 (예: `'guides/getting-started'`).

- `items` — 더 많은 사이드바 링크와 하위 그룹을 포함하는 배열

- `autogenerate` — 링크 그룹을 자동으로 생성하기 위해 문서의 디렉터리를 지정하는 객체

내부 링크는 `slug` 속성이 있는 객체 대신 문자열로 지정할 수도 있습니다.

```js
starlight({
	sidebar: [
		// '홈'이라는 라벨이 붙은 단일 링크 항목
		{ label: '홈', link: '/' },
		// 네 개의 링크가 포함된 '여기서부터' 라는 라벨이 붙은 그룹
		{
			label: '여기서부터',
			items: [
				// 내부 링크에 `slug`를 사용합니다.
				{ slug: 'intro' },
				{ slug: 'installation' },
				// 또는 내부 링크에 대한 약칭을 사용합니다.
				'tutorial',
				'next-steps',
			],
		},
		// 'reference' 디렉터리의 모든 페이지에 연결되는 그룹
		{
			label: '참조',
			autogenerate: { directory: 'reference' },
		},
	],
});
```

#### 정렬

자동 생성된 사이드바 그룹은 파일 이름을 기준으로 알파벳순으로 정렬됩니다. 예를 들어 `astro.md`에서 생성된 페이지는 `starlight.md` 페이지 위에 표시됩니다.

#### 그룹 최소화

링크 그룹은 기본적으로 펼쳐져 있습니다. 그룹의 `collapsed` 속성을 `true`로 설정하여 이 동작을 변경할 수 있습니다.

자동 생성된 하위 그룹은 기본적으로 상위 그룹의 `collapsed` 속성을 따릅니다. 이를 변경하려면 `autogenerate.collapsed` 속성을 설정하세요.

```js {5,13}
sidebar: [
  // 최소화된 링크 그룹
  {
    label: '최소화된 링크 모음',
    collapsed: true,
    items: ['intro', 'next-steps'],
  },
  // 최소화된 자동 생성 하위 그룹을 포함하는 펼쳐진 그룹
  {
    label: '참조',
    autogenerate: {
      directory: 'reference',
      collapsed: true,
    },
  },
],
```

#### 라벨 번역

다국어 사이트의 경우, 각 항목의 `label`은 기본 언어로 설정됩니다. `translations` 속성을 설정하여 지원하는 다른 언어로 된 라벨을 제공할 수 있습니다.

```js {5,9,14}
sidebar: [
  // 브라질 포르투갈어로 번역된 라벨이 있는 예시 사이드바입니다.
  {
    label: '여기서부터',
    translations: { 'pt-BR': 'Comece Aqui' },
    items: [
      {
        label: '시작하기',
        translations: { 'pt-BR': 'Introdução' },
        link: '/getting-started',
      },
      {
        label: '프로젝트 구조',
        translations: { 'pt-BR': 'Estrutura de Projetos' },
        link: '/structure',
      },
    ],
  },
],
```

#### `SidebarItem`

```ts
type SidebarItem =
	| string
	| ({
			translations?: Record<string, string>;
			badge?: string | BadgeConfig;
	  } & (
			| {
					// 링크
					link: string;
					label: string;
					attrs?: Record<string, string | number | boolean | undefined>;
			  }
			| {
					// 내부 링크
					slug: string;
					label?: string;
					attrs?: Record<string, string | number | boolean | undefined>;
			  }
			| {
					// 링크 그룹
					label: string;
					items: SidebarItem[];
					collapsed?: boolean;
			  }
			| {
					// 자동으로 생성된 링크 그룹
					label: string;
					autogenerate: {
						directory: string;
						collapsed?: boolean;
						attrs?: Record<string, string | number | boolean | undefined>;
					};
					collapsed?: boolean;
			  }
	  ));
```

#### `BadgeConfig`

```ts
interface BadgeConfig {
	text: string;
	variant?: 'note' | 'tip' | 'caution' | 'danger' | 'success' | 'default';
	class?: string;
}
```

### `locales`

**타입:** <code>\{ \[dir: string\]: [LocaleConfig](#localeconfig) }</code>

지원되는 `locales`를 설정하여 사이트의 [국제화(i18n)를 구성](/ko/guides/i18n/)하세요.

각 항목은 언어 파일이 저장된 디렉터리를 키로 사용해야 합니다.

```js
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: '나의 사이트',
			// 이 사이트의 기본 언어를 한국어로 설정합니다.
			defaultLocale: 'ko',
			locales: {
				// 한국어 문서는 `src/content/docs/ko/`에 있습니다.
				ko: {
					label: '한국어',
				},
				// 영어 문서는 `src/content/docs/en/`에 있습니다.
				en: {
					label: 'English',
					lang: 'en',
				},
				// 중국어 간체 문서는 `src/content/docs/zh-cn/`에 있습니다.
				'zh-cn': {
					label: '简体中文',
					lang: 'zh-CN',
				},
				// 아랍어 문서는 `src/content/docs/ar/`에 있습니다.
				ar: {
					label: 'العربية',
					dir: 'rtl',
				},
			},
		}),
	],
});
```

#### `LocaleConfig`

```ts
interface LocaleConfig {
	label: string;
	lang?: string;
	dir?: 'ltr' | 'rtl';
}
```

각 언어에 대해 다음 옵션을 설정할 수 있습니다.

##### `label` (필수)

**타입:** `string`

언어의 라벨은 언어 변경 기능에서 사용자에게 보여지는 문자입니다. 대부분의 경우, `"English"`, `"العربية"`, 또는 `"简体中文"`와 같이 해당 언어를 사용하는 사용자가 읽을 것으로 예상되는 언어의 이름을 작성하는 것이 좋습니다.

##### `lang`

**타입:** `string`

`"en"`, `"ar"` 또는 `"zh-CN"`와 같은 언어의 BCP-47 태그입니다. 설정하지 않으면 기본적으로 해당 언어의 디렉터리 이름이 사용됩니다. 지역 하위 태그가 있는 언어 태그(예: `"pt-BR"` 또는 `"en-US"`)는 지역별 번역이 없는 경우에 내장된 기본 언어 UI 번역을 사용합니다.

##### `dir`

**타입:** `'ltr' | 'rtl'`

언어의 쓰기 방향입니다. `"ltr"`은 왼쪽에서 오른쪽으로 진행함을 나타내며 기본값입니다. `"rtl"`은 오른쪽에서 왼쪽으로 진행함을 나타냅니다.

#### 루트 로케일

`root` 로케일을 설정하면 `/lang/` 디렉터리 없이 기본 언어를 제공할 수 있습니다.

```js {3-6}
starlight({
	locales: {
		root: {
			label: '한국어',
			lang: 'ko',
		},
		fr: {
			label: 'Français',
		},
	},
});
```

예를 들어, `/getting-started/`를 한국어 경로로 제공하고, `/fr/getting-started/`를 동일한 페이지의 프랑스어 버전으로 제공할 수 있습니다.

### `defaultLocale`

**타입:** `string`

사이트의 기본 언어를 설정합니다.
값은 [`locales`](#locales) 객체의 키 중 하나와 일치해야 합니다.
(기본 언어가 [루트 로케일](#루트-로케일)인 경우 이 단계를 건너뛸 수 있습니다.)

이 값은 번역이 누락된 대체 콘텐츠를 제공하는 데 사용됩니다.

### `social`

**타입:** <code>{`Array<{ label: string; icon: `}[StarlightIcon](/ko/reference/icons/){`; href: string }>`}</code>

이 사이트의 소셜 미디어 계정에 대한 선택적 세부 정보입니다.
각 항목은 사이트 헤더에 아이콘 링크로 표시됩니다.

```js
starlight({
  social: [
		{ icon: 'codeberg', label: 'Codeberg', href: 'https://codeberg.org/knut' },
		{ icon: 'discord', label: 'Discord', href: 'https://astro.build/chat' },
		{ icon: 'github', label: 'GitHub', href: 'https://github.com/withastro' },
		{ icon: 'gitlab', label: 'GitLab', href: 'https://gitlab.com/delucis' },
		{ icon: 'mastodon', label: 'Mastodon', href: 'https://m.webtoo.ls/@astro' },
	],
}),
```

### `customCss`

**타입:** `string[]`

Starlight 사이트의 모양과 느낌을 변경하려면 CSS 파일을 제공하세요.

`'./src/custom.css'`와 같은 프로젝트 루트에서 상대 경로로 지정한 로컬 CSS 파일 및 `'@fontsource/roboto'`와 같은 npm 모듈로 설치한 CSS를 지원합니다.

```js
starlight({
	customCss: ['./src/custom-styles.css', '@fontsource/roboto'],
});
```

### `markdown`

**타입:** `{ headingLinks?: boolean; processedDirs?: string[] }`  
**기본값:** `{ headingLinks: true, processedDirs: [] }`

Starlight의 Markdown 처리를 구성합니다.

#### `headingLinks`

**타입:** `boolean`  
**기본값:** `true`

제목이 클릭 가능한 앵커 링크와 함께 렌더링될지 여부를 제어합니다.

```js
starlight({
	markdown: {
		// Starlight의 클릭 가능한 제목 앵커 링크를 비활성화합니다.
		headingLinks: false,
	},
}),
```

#### `processedDirs`

**타입:** `string[]`  
**기본값:** `[]`

Starlight의 Markdown 파이프라인에 의해 처리되어야 하는 파일들을 포함하는 디렉터리를 추가로 정의합니다.
기본적으로 Starlight는 [`docsLoader()`](/ko/reference/configuration/#docsloader)를 사용하여 로드된 Markdown 및 MDX 콘텐츠만 처리합니다.
프로젝트 루트를 기준으로 한 로컬 디렉터리(예: `'./src/data/comments/'`)를 지원합니다.

Starlight의 처리는 [클릭 가능한 제목 앵커 링크](#headinglinks), [Markdown의 asides 지시어 구문](/ko/guides/authoring-content/#보조-내용), 코드 블록에 대한 RTL 지원을 포함합니다.
이 옵션은 `<StarlightPage>` 컴포넌트를 사용하여 [사용자 정의 페이지](/ko/guides/pages/#사용자-정의-페이지)에서 사용자 정의 콘텐츠 컬렉션의 콘텐츠를 렌더링하고, Starlight의 Markdown 처리가 해당 콘텐츠에도 적용되기를 기대하는 경우에 유용할 수 있습니다.

```js
starlight({
	markdown: {
		// `src/data/reviews/` 디렉터리에 있는 `reviews` 콘텐츠 컬렉션의 Markdown 파일을 처리합니다.
		processedDirs: ['./src/data/reviews/'],
	},
}),
```

### `expressiveCode`

**타입:** `StarlightExpressiveCodeOptions | boolean`  
**기본값:** `true`

Starlight는 [Expressive Code](https://expressive-code.com)를 사용하여 코드 블록을 렌더링하고 코드 예시의 부분 강조 표시, 코드 블록에 파일 이름 추가 등 다양한 기능을 지원합니다.
Markdown 및 MDX 콘텐츠에서 Expressive Code 구문을 사용하는 방법을 알아보려면 [“코드 블록” 가이드](/ko/guides/authoring-content/#코드-블록)를 참조하세요.

Starlight의 `expressiveCode` 옵션을 설정하여 표준 [Expressive Code 구성 옵션](https://expressive-code.com/reference/configuration/)과 일부 Starlight 관련 속성을 사용할 수 있습니다.
예를 들어, Expressive Code의 `styleOverrides` 옵션을 설정하여 기본 CSS를 재정의할 수 있습니다. 이를 통해 코드 블록에 둥근 모서리를 제공하는 등의 사용자 정의가 가능해집니다.

```js ins={2-4}
starlight({
	expressiveCode: {
		styleOverrides: { borderRadius: '0.5rem' },
	},
});
```

Expressive Code를 비활성화하려면 Starlight 구성에서 `expressiveCode: false`를 설정하세요.

```js ins={2}
starlight({
	expressiveCode: false,
});
```

표준 Expressive Code 옵션 외에도 `expressiveCode` 구성에서 다음과 같은 Starlight 관련 속성을 설정하여 코드 블록에 대한 테마를 추가로 변경할 수도 있습니다.

#### `themes`

**타입:** `Array<string | ThemeObject | ExpressiveCodeTheme>`  
**기본값:** `['starlight-dark', 'starlight-light']`

코드 블록 스타일을 지정하는 데 사용되는 테마를 설정합니다.
지원되는 테마 형식에 대한 자세한 내용은 [Expressive Code `themes` 문서](https://expressive-code.com/guides/themes/)를 참조하세요.

Starlight는 기본적으로 Sarah Drasner가 제작한 [Night Owl theme](https://github.com/sdras/night-owl-vscode-theme)의 어둡고 밝은 변형을 사용합니다.

어두운 테마와 밝은 테마를 최소 하나씩 제공하는 경우 Starlight는 자동으로 활성 코드 블록 테마를 현재 사이트 테마와 동기화된 상태로 유지합니다.
[`useStarlightDarkModeSwitch`](#usestarlightdarkmodeswitch) 옵션을 사용하여 이 동작을 구성하세요.

#### `useStarlightDarkModeSwitch`

**타입:** `boolean`  
**기본값:** `true`

값이 `true`인 경우, 사이트 테마가 변경되면 코드 블록이 밝은 테마와 어두운 테마를 자동으로 전환합니다.
값이 `false`인 경우, 여러 테마 간 전환을 처리하기 위해 CSS를 수동으로 추가해야 합니다.

:::note
`themes`를 설정할 때, 최소 하나의 어두운 테마와 밝은 테마를 제공해야 Starlight 어두운 모드 스위치가 작동합니다.
:::

#### `useStarlightUiThemeColors`

**타입:** `boolean`  
**기본값:** `themes`가 설정되어 있지 않으면 `true`이고, 그렇지 않으면 `false`입니다.

값이 `true`인 경우, Starlight의 CSS 변수는 코드 블록의 UI 요소(배경, 버튼, 그림자 등)에 사용되며, [사이트 색상 테마](/ko/guides/css-and-tailwind/#테마)와 일치합니다.
값이 `false`인 경우, 활성 구문 강조 테마에서 제공하는 색상이 이러한 요소에 사용됩니다.

:::note
사용자 정의 테마를 사용하고 이를 `true`로 설정하는 경우, 적절한 색상 대비를 보장하기 위해 최소한 하나의 어두운 테마와 하나의 밝은 테마를 제공해야 합니다.
:::

### `pagefind`

**타입:** <code>boolean | <a href="#pagefindoptions">PagefindOptions</a></code>  
**기본값:** `true`

Starlight의 기본 사이트 검색 공급자인 [Pagefind](https://pagefind.app/)를 구성합니다.

Pagefind로 사이트 색인을 생성하지 않으려면 `false`로 설정하세요.
또한, 이는 기본 검색 UI도 숨깁니다.

[`prerender`](#prerender) 옵션이 `false`로 설정된 경우 Pagefind를 활성화할 수 없습니다.

`pagefind`를 객체로 설정하여 Pagefind 검색 클라이언트를 구성합니다:

- `pagefind.ranking` 옵션을 사용하여 검색 결과 순위 계산 방법을 제어하는 방법에 대한 자세한 내용은 Pagefind 문서의 ["Customize Pagefind's result ranking"](https://pagefind.app/docs/ranking/)을 참조하세요.
- 여러 사이트에서 검색하는 방법을 제어하기 위해 `pagefind.mergeIndex` 옵션을 사용하는 방법에 대한 자세한 내용은 Pagefind 문서의 ["Searching multiple sites"](https://pagefind.app/docs/multisite/)를 참조하세요.

#### `PagefindOptions`

```ts
interface PagefindOptions {
	ranking?: {
		pageLength?: number;
		termFrequency?: number;
		termSaturation?: number;
		termSimilarity?: number;
	};
	indexWeight?: number;
	mergeIndex?: Array<{
		bundlePath: string;
		indexWeight?: number;
		basePath?: string;
		baseUrl?: string;
		mergeFilter?: Record<string, string | string[]>;
		language?: string;
		ranking?: {
			pageLength?: number;
			termFrequency?: number;
			termSaturation?: number;
			termSimilarity?: number;
		};
	}>;
}
```

### `prerender`

**타입:** `boolean`  
**기본값:** `true`

Starlight 페이지를 정적 HTML로 사전 렌더링할지, 아니면 [SSR 어댑터](https://docs.astro.build/ko/guides/on-demand-rendering/)를 통해 주문형으로 렌더링할지 정의합니다.

Starlight 페이지는 기본적으로 사전 렌더링됩니다.
SSR 어댑터를 사용 중이고 Starlight 페이지를 주문형으로 렌더링하기를 원한다면 `prerender: false`를 설정하세요.

### `head`

**타입:** [`HeadConfig[]`](#headconfig)

Starlight 사이트의 `<head>`에 사용자 정의 태그를 추가합니다. 분석 및 기타 서드파티 스크립트와 리소스를 추가하는 데 유용할 수 있습니다.

```js
starlight({
	head: [
		// Fathom 분석 스크립트 태그를 추가하는 예시
		{
			tag: 'script',
			attrs: {
				src: 'https://cdn.usefathom.com/script.js',
				'data-site': 'MY-FATHOM-ID',
				defer: true,
			},
		},
	],
});
```

`head`의 항목은 HTML 요소로 직접 변환되며 Astro의 [스크립트](https://docs.astro.build/ko/guides/client-side-scripts/#스크립트-처리)나 [스타일](https://docs.astro.build/ko/guides/styling/#astro에서-스타일링하기) 처리를 거치지 않습니다.
스크립트, 스타일 또는 이미지와 같은 로컬 자산을 가져와야 하는 경우 [Head 컴포넌트를 재정의하세요](/ko/guides/overriding-components/#내장-컴포넌트-재사용).

#### `HeadConfig`

```ts
interface HeadConfig {
	tag: string;
	attrs?: Record<string, string | boolean | undefined>;
	content?: string;
}
```

### `lastUpdated`

**타입:** `boolean`  
**기본값:** `false`

페이지 하단에 최종 업데이트 날짜를 표시할지 여부를 제어합니다.

기본적으로 이 기능은 저장소의 Git 기록에 의존하며 [얕은 복제](https://git-scm.com/docs/git-clone#Documentation/git-clone.txt---depthltdepthgt)를 수행하는 일부 배포 플랫폼에서는 정확하지 않을 수 있습니다. 페이지는 [`lastUpdated` 프론트매터 필드](/ko/reference/frontmatter/#lastupdated)를 사용하여 이 설정이나 Git 기반 날짜를 변경할 수 있습니다.

### `pagination`

**타입:** `boolean`  
**기본값:** `true`

페이지 하단에 이전 페이지 링크와 다음 페이지 링크가 포함되어야 하는지 정의합니다.

페이지는 [`prev`](/ko/reference/frontmatter/#prev)와 [`next`](/ko/reference/frontmatter/#next) 프론트매터 필드를 통해 이 설정이나 링크 텍스트, URL을 변경할 수 있습니다.

### `favicon`

**타입:** `string`  
**기본값:** `'/favicon.svg'`

`public/` 디렉터리에 포함되어 있으며 유효한 아이콘 파일인 (`.ico`, `.gif`, `.jpg`, `.png`, 또는 `.svg`) 웹 사이트의 기본 파비콘 경로를 설정합니다.

```js
starlight({
  favicon: '/images/favicon.svg',
}),
```

추가 변형이나 대체 파비콘을 설정해야 하는 경우 [`head` 옵션](#head)을 사용하여 태그를 추가할 수 있습니다.

```js
starlight({
	favicon: '/images/favicon.svg',
	head: [
		// Safari용 대체 ICO 파비콘을 추가합니다.
		{
			tag: 'link',
			attrs: {
				rel: 'icon',
				href: '/images/favicon.ico',
				sizes: '32x32',
			},
		},
	],
});
```

### `titleDelimiter`

**타입:** `string`  
**기본값:** `'|'`

브라우저 탭에 표시되는 페이지의 `<title>` 태그에서 페이지 제목과 사이트 제목 사이의 구분 기호를 설정합니다.

기본적으로 모든 페이지에 설정된 `<title>` 태그의 내용은 `페이지 제목 | 사이트 제목`입니다.
예를 들어, 이 페이지의 제목이 "구성 참조"이고, 이 사이트의 제목이 "Starlight"라면, 이 페이지의 `<title>`의 내용은 `구성 참조 | Starlight`가 됩니다.

### `disable404Route`

**타입:** `boolean`  
**기본값:** `false`

Starlight의 기본 [404 페이지](https://docs.astro.build/ko/basics/astro-pages/#사용자-정의-404-오류-페이지) 삽입을 비활성화합니다. 프로젝트에서 사용자 정의 `src/pages/404.astro` 경로를 사용하려면 이 옵션을 `true`로 설정하세요.

### `routeMiddleware`

**타입:** `string | string[]`

Starlight가 데이터를 처리하는 방식을 수정할 수 있는 라우트 미들웨어 경로를 제공합니다.
이 파일 경로는 [Astro의 미들웨어](https://docs.astro.build/ko/guides/middleware/)와 충돌해서는 안 됩니다.

라우트 미들웨어를 만드는 방법에 대한 자세한 내용은 [라우트 데이터 가이드](/ko/guides/route-data/#경로-데이터-사용자-정의)를 참조하세요.

### `components`

**타입:** `Record<string, string>`

Starlight의 기본 구현을 재정의하기 위해 컴포넌트에 대한 경로를 제공합니다.

```js
starlight({
	components: {
		SocialLinks: './src/components/MySocialLinks.astro',
	},
});
```

재정의할 수 있는 모든 컴포넌트에 대한 자세한 내용은 [재정의 참조](/ko/reference/overrides/)를 확인하세요.

### `plugins`

**타입:** [`StarlightPlugin[]`](/ko/reference/plugins/#빠른-api-참조)

맞춤형 플러그인으로 Starlight를 확장하세요.
플러그인은 프로젝트에 변경 사항을 적용하여 Starlight의 기능을 수정하거나 추가합니다.

사용 가능한 플러그인 목록을 보려면 [플러그인 쇼케이스](/ko/resources/plugins/)를 방문하세요.

```js
starlight({
	plugins: [starlightPlugin()],
});
```

나만의 플러그인을 만드는 방법에 대한 자세한 내용은 [플러그인 참조](/ko/reference/plugins/)를 확인하세요.

### `credits`

**타입:** `boolean`  
**기본값:** `false`

사이트 바닥글에 “Starlight로 제작됨” 링크 표시를 활성화합니다.

```js
starlight({
	credits: true,
});
```

## 콘텐츠 컬렉션 구성

Starlight는 Astro의 [콘텐츠 컬렉션](https://docs.astro.build/ko/guides/content-collections/)을 사용하여 콘텐츠를 로드합니다.
Starlight의 콘텐츠 로더 및 스키마는 필요에 따라 컬렉션을 구성하는 데 도움이 됩니다.

```js
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';

export const collections = {
	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
	// 선택 사항: i18n 컬렉션은 다국어 사이트의 UI 번역에 사용됩니다.
	i18n: defineCollection({ loader: i18nLoader(), schema: i18nSchema() }),
};
```

### 로더

Starlight는 콘텐츠 컬렉션 구성을 간소화하기 위해 `@astrojs/starlight/loaders` 모듈에서 다음과 같은 [Astro 로더](https://docs.astro.build/ko/reference/content-loader-reference/)를 내보냅니다.

#### `docsLoader()`

`docsLoader()`는 `src/content/docs/` 디렉터리에서 로컬 Markdown, MDX 및 Markdoc 파일을 로드합니다.
밑줄 (`_`)로 시작하는 파일 이름은 무시됩니다.

##### 가져오기

```js
import { docsLoader } from '@astrojs/starlight/loaders';
```

##### 옵션

###### `generateId()`

**타입:** `({ entry: string; base: URL; data: Record<string, unknown> }) => string`

기본적으로 `docsLoader()`를 사용하여 생성된 페이지는 특수 문자를 제거하고 파일 이름을 소문자로 처리하는 sluggifier를 사용하여 파일 이름을 처리합니다. 이 기본 동작을 재정의하려면 사용자 정의 `generateId()` 함수를 제공하세요.

예를 들어, 이는 제거될 특수 문자를 보존하는 데 유용할 수 있습니다.
기본적으로 `Example.File.md`는 `/examplefile`에서 제공됩니다.
이를 `/Example.File`에서 제공하려면 사용자 정의 `generateId()` 함수를 정의하면 됩니다.

```js
docsLoader({
	// `.md` 또는 `.mdx` 확장자를 제거하되, 파일 이름은 그대로 유지합니다.
	generateId: ({ entry }) => entry.split('.').slice(0, -1).join('.'),
}),
```

자세한 내용은 [Astro 문서에서 `generateId()`](https://docs.astro.build/ko/reference/content-loader-reference/#generateid)를 참조하세요.

#### `i18nLoader()`

`i18nLoader()`는 `src/content/i18n/` 디렉터리에서 로컬 JSON 및 YAML 파일을 로드합니다.
밑줄 (`_`)로 시작하는 파일 이름은 무시됩니다.

##### 가져오기

```js
import { i18nLoader } from '@astrojs/starlight/loaders';
```

##### 옵션

현재 `i18nLoader()`를 구성하는 옵션은 없습니다.

### 스키마

Starlight는 `@astrojs/starlight/schema` 모듈에서 다음과 같은 [콘텐츠 컬렉션 스키마](https://docs.astro.build/ko/guides/content-collections/#컬렉션-스키마-정의)를 제공합니다.
이러한 스키마는 Starlight가 의존하는 `docs` 및 `i18n` 컬렉션에 사용해야 합니다.

#### `docsSchema()`

`docsSchema()`는 `docs` 컬렉션의 모든 콘텐츠에 대한 프런트매터를 구문 분석합니다.

##### 가져오기

```js
import { docsSchema } from '@astrojs/starlight/schema';
```

##### 옵션

###### `extend`

**타입:** Zod 스키마 또는 Zod 스키마를 반환하는 함수  
**기본값:** `z.object({})`

추가 필드를 사용하여 Starlight의 프런트매터 스키마를 확장합니다.
`extend` 옵션 사용에 대한 자세한 내용은 ["프런트매터 스키마 사용자 정의"](/ko/reference/frontmatter/#프런트매터-스키마-사용자-정의)를 참조하세요.

#### `i18nSchema()`

`i18nSchema()`는 `i18n` 컬렉션의 모든 데이터 파일을 구문 분석합니다.

##### 가져오기

```js
import { i18nSchema } from '@astrojs/starlight/schema';
```

##### 옵션

###### `extend`

**타입:** Zod 객체  
**기본값:** `z.object({})`

추가 필드를 사용하여 Starlight의 i18n 스키마를 확장합니다.
`extend` 옵션 사용에 대한 자세한 내용은 ["번역 스키마 확장하기"](/ko/guides/i18n/#번역-스키마-확장)를 참조하세요.


================================================
FILE: docs/src/content/docs/ko/reference/frontmatter.md
================================================
---
title: 프런트매터 참조
description: Starlight가 지원하는 기본 프런트매터 필드에 대한 개요입니다.
---

프런트매터의 값을 설정하여 Starlight에서 개별 Markdown 및 MDX 페이지를 변경할 수 있습니다. 예를 들어 일반 페이지에서는 `title` 및 `description` 필드를 설정할 수 있습니다.

```md {3-4}
---
# src/content/docs/example.md
title: 이 프로젝트에 대하여
description: 내가 진행 중인 프로젝트에 대해 자세히 알아보세요.
---

나를 소개하는 페이지에 오신 것을 환영합니다!
```

## 프런트매터 필드

### `title` (필수)

**타입:** `string`

모든 페이지에 제목을 제공해야 합니다. 이는 페이지 상단, 브라우저 탭 및 페이지 메타데이터에 표시됩니다.

### `description`

**타입:** `string`

페이지 설명은 페이지 메타데이터에 사용되며 검색 엔진과 소셜 미디어 미리 보기에서 선택됩니다.

### `slug`

**타입**: `string`

페이지의 슬러그를 재정의합니다. 자세한 내용은 Astro 공식문서의 [“사용자 지정 ID 정의”](https://docs.astro.build/ko/guides/content-collections/#사용자-지정-id-정의)를 참조하세요.

### `editUrl`

**타입:** `string | boolean`

[전역 editLink 구성](/ko/reference/configuration/#editlink)을 변경합니다. 특정 페이지에 대한 "페이지 편집" 링크를 비활성화하거나 이 페이지의 콘텐츠를 편집할 수 있는 대체 URL을 제공하려면 `false`로 설정합니다.

### `head`

**타입:** [`HeadConfig[]`](/ko/reference/configuration/#headconfig)

`head` 프런트매터 필드를 사용하여 페이지의 `<head>`에 태그를 추가할 수 있습니다. 이는 사용자 정의 스타일, 메타데이터 또는 기타 태그를 단일 페이지에 추가할 수 있음을 의미합니다. [전역 `head` 옵션](/ko/reference/configuration/#head)과 유사합니다.

```md
---
# src/content/docs/example.md
title: 회사 소개
head:
  # 사용자 정의 <title> 태그 사용
  - tag: title
    content: title에 대한 사용자 정의
---
```

### `tableOfContents`

**타입:** `false | { minHeadingLevel?: number; maxHeadingLevel?: number; }`

[전역 tableOfContents 구성](/ko/reference/configuration/#tableofcontents)을 변경합니다.
포함된 제목의 레벨을 변경하거나 값을 `false`로 설정하여 페이지에서 목차를 숨길 수 있습니다.

```md
---
# src/content/docs/example.md
title: 목차에 H2만 있는 페이지
tableOfContents:
  minHeadingLevel: 2
  maxHeadingLevel: 2
---
```

```md
---
# src/content/docs/example.md
title: 목차가 없는 페이지
tableOfContents: false
---
```

### `template`

**타입:** `'doc' | 'splash'`  
**기본값:** `'doc'`

이 페이지의 레이아웃 템플릿을 설정합니다. 페이지는 기본적으로 `'doc'` 레이아웃을 사용합니다. 랜딩 페이지용으로 설계된 사이드바 없이 더 넓은 레이아웃을 사용하려면 `'splash'`로 설정하세요.

### `hero`

**타입:** [`HeroConfig`](#heroconfig)

페이지 상단에 hero 컴포넌트를 추가합니다. `template: splash`와 잘 작동합니다.

예를 들어 이 구성은 저장소에서 이미지를 로드하는 것을 포함하여 몇 가지 일반적인 옵션을 보여줍니다.

```md
---
# src/content/docs/example.md
title: 나의 홈페이지
template: splash
hero:
  title: '내 프로젝트: Stellar Stuff Sooner'
  tagline: 물건을 달에 가져갔다가 눈 깜짝할 사이에 다시 가져올 수 있습니다.
  image:
    alt: 반짝이는 밝은 색상의 로고
    file: ../../assets/logo.png
  actions:
    - text: 더보기
      link: /getting-started/
      icon: right-arrow
    - text: Github에서 보기
      link: https://github.com/astronaut/my-project
      icon: external
      variant: minimal
      attrs:
        rel: me
---
```

밝은 모드와 어두운 모드에서 다양한 버전의 hero 이미지를 표시할 수 있습니다.

```md
---
# src/content/docs/example.md
hero:
  image:
    alt: 반짝이는 밝은 색상의 로고
    dark: ../../assets/logo-dark.png
    light: ../../assets/logo-light.png
---
```

#### `HeroConfig`

```ts
interface HeroConfig {
  title?: string;
  tagline?: string;
  image?:
    | {
        // 저장소에 있는 이미지의 상대 경로입니다.
        file: string;
        // 보조 기술이 이미지에 접근할 수 있도록 하는 대체 텍스트입니다.
        alt?: string;
      }
    | {
        // 어두운 모드에 사용할 저장소의 이미지에 대한 상대 경로입니다.
        dark: string;
        // 밝은 모드에 사용할 저장소의 이미지에 대한 상대 경로입니다.
        light: string;
        // 보조 기술이 이미지에 접근할 수 있도록 하는 대체 텍스트입니다.
        alt?: string;
      }
    | {
        // 이미지 슬롯에 사용할 원시 HTML입니다.
        // 사용자 정의 `<img>` 태그 또는 인라인 `<svg>` 태그일 수 있습니다.
        html: string;
      };
  actions?: Array<{
    text: string;
    link: string;
    variant?: 'primary' | 'secondary' | 'minimal';
    icon?: string;
    attrs?: Record<string, string | number | boolean>;
  }>;
}
```

### `banner`

**타입:** `{ content: string }`

이 페이지 상단에 공지 배너를 표시합니다.

`content` 값에는 링크나 다른 콘텐츠에 대한 HTML이 포함될 수 있습니다.
예를 들어, 이 페이지에서는 `example.com`으로 이동하는 링크가 포함된 배너가 표시됩니다.

```md
---
# src/content/docs/example.md
title: 배너가 포함된 페이지
banner:
  content: |
    방금 멋진 것을 출시했습니다!
    <a href="https://example.com">확인하러 가기</a>
---
```

### `lastUpdated`

**타입:** `Date | boolean`

[전역 `lastUpdated` 옵션](/ko/reference/configuration/#lastupdated)을 변경합니다. 날짜가 지정된 경우 유효한 [YAML 타임스탬프](https://yaml.org/type/timestamp.html)여야 하며 이 페이지의 Git 기록에 저장된 날짜를 변경합니다.

```md
---
# src/content/docs/example.md
title: 수정된 최종 업데이트 날짜가 포함된 페이지
lastUpdated: 2022-08-09
---
```

### `prev`

**타입:** `boolean | string | { link?: string; label?: string }`

[전역 `pagination` 옵션](/ko/reference/configuration/#pagination)을 변경합니다. 문자열로 설정하면 생성된 링크 텍스트가 대체되고, 객체로 설정하면 링크와 텍스트가 모두 변경됩니다.

```md
---
# src/content/docs/example.md
# 이전 페이지 링크 숨기기
prev: false
---
```

```md
---
# src/content/docs/example.md
# 이전 페이지 링크의 텍스트 변경
prev: 튜토리얼 계속하기
---
```

```md
---
# src/content/docs/example.md
# 이전 페이지 링크와 텍스트 모두 변경
prev:
  link: /unrelated-page/
  label: 다른 페이지를 확인하세요.
---
```

### `next`

**타입:** `boolean | string | { link?: string; label?: string }`

[`prev`](#prev)와 동일하지만 다음 페이지 링크용입니다.

```md
---
# src/content/docs/example.md
# 다음 페이지 링크 숨기기
next: false
---
```

### `pagefind`

**타입:** `boolean`  
**기본값:** `true`

이 페이지를 [Pagefind](https://pagefind.app/) 검색 색인에 포함할지 여부를 설정합니다. 검색 결과에서 페이지를 제외하려면 값을 `false`로 설정하세요.

```md
---
# src/content/docs/example.md
# 검색 색인에서 이 페이지 숨기기
pagefind: false
---
```

### `draft`

**타입:** `boolean`  
**기본값:** `false`

이 페이지를 초안으로 간주하여 [프로덕션 빌드](https://docs.astro.build/ko/reference/cli-reference/#astro-build)에서 제외할지 설정합니다. 페이지를 초안으로 표시하여 개발 중에만 표시하려면 `true`로 설정하세요.

```md
---
# src/content/docs/example.md
# 프로덕션 빌드에서 이 페이지 제외
draft: true
---
```

초안 페이지는 빌드 출력에 포함되지 않으므로 [슬러그](/ko/guides/sidebar/#내부-링크)를 사용하여 사이트 사이드바 구성에 직접 초안 페이지를 추가할 수 없습니다.
[자동 생성된 사이드바 그룹](/ko/guides/sidebar/#자동-생성-그룹)에 사용되는 디렉터리의 초안 페이지는 프로덕션 빌드에서 자동으로 제외됩니다.

### `sidebar`

**타입:** [`SidebarConfig`](#sidebarconfig)

자동 생성된 링크 그룹을 사용할 때 이 페이지가 [사이드바](/ko/reference/configuration/#sidebar)에 표시되는 방식을 제어합니다.

#### `SidebarConfig`

```ts
interface SidebarConfig {
  label?: string;
  order?: number;
  hidden?: boolean;
  badge?: string | BadgeConfig;
  attrs?: Record<string, string | number | boolean | undefined>;
}
```

#### `label`

**타입:** `string`  
**기본값:** 페이지의 [`title`](#title-필수)

자동 생성된 링크 그룹에 표시될 때 사이드바에서 이 페이지에 대한 라벨을 설정합니다.

```md
---
# src/content/docs/example.md
title: 이 프로젝트에 대하여
sidebar:
  label: 소개
---
```

#### `order`

**타입:** `number`

자동 생성된 링크 그룹을 정렬할 때 이 페이지의 순서를 제어합니다. 링크 그룹에서는 낮은 숫자가 위쪽에 표시됩니다.

```md
---
# src/content/docs/example.md
title: 첫 번째로 표시될 페이지
sidebar:
  order: 1
---
```

#### `hidden`

**타입:** `boolean`
**기본값:** `false`

이 페이지가 자동 생성된 사이드바 그룹에 포함되지 않도록 합니다.

```md
---
# src/content/docs/example.md
title: 자동 생성된 사이드바에서 숨길 페이지
sidebar:
  hidden: true
---
```

#### `badge`

**타입:** <code>string | <a href="/ko/reference/configuration/#badgeconfig">BadgeConfig</a></code>

자동 생성된 링크 그룹에 표시될 때 사이드바의 페이지에 배지를 추가합니다. 문자열을 사용하면 배지가 기본 강조 색상으로 표시됩니다. 선택적으로, `text`, `variant`, `class` 필드가 포함된 [BadgeConfig 객체](/ko/reference/configuration/#badgeconfig)를 전달하여 배지를 사용자가 원하는대로 변경할 수 있습니다.

```md
---
# src/content/docs/example.md
title: 배지를 사용하는 페이지
sidebar:
  # 사이트의 강조 색상과 일치하는 기본 변형을 사용합니다.
  badge: New
---
```

```md
---
# src/content/docs/example.md
title: 배지를 사용하는 페이지
sidebar:
  badge:
    text: 실험적 기능
    variant: caution
---
```

#### `attrs`

**타입:** `Record<string, string | number | boolean | undefined>`

사이드바에서 자동 생성된 링크 그룹을 사용할 때, 이 페이지의 링크에 추가할 HTML 속성을 설정합니다.
이 페이지가 속한 자동 생성 그룹에 [`autogenerate.attrs`](/ko/guides/sidebar/#자동-생성-링크의-사용자-정의-html-속성)가 설정되어 있으면 프런트매터 속성이 그룹 속성과 병합됩니다.

```md
---
# src/content/docs/example.md
title: 새 탭에서 열리는 페이지
sidebar:
  # 새 탭에서 페이지를 엽니다.
  attrs:
    target: _blank
---
```

## 프런트매터 스키마 사용자 정의

Starlight의 `docs` 콘텐츠 컬렉션에 대한 프런트매터 스키마는 `docsSchema()` 도우미를 사용하여 `src/content.config.ts`에 구성됩니다.

```ts {4,7}
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
  docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
};
```

Astro 공식문서의 ["컬렉션 스키마 정의"](https://docs.astro.build/ko/guides/content-collections/#컬렉션-스키마-정의)에서 콘텐츠 컬렉션 스키마에 대해 자세히 알아보세요.

`docsSchema()`는 다음 옵션을 사용합니다:

### `extend`

**타입:** Zod 스키마 또는 Zod 스키마를 반환하는 함수  
**기본값:** `z.object({})`

`docsSchema()` 옵션에서 `extend`를 설정하여 추가 필드로 Starlight의 스키마를 확장하세요.
값은 [Zod 스키마](https://docs.astro.build/ko/guides/content-collections/#zod를-사용한-데이터-타입-정의)여야 합니다.

다음 예시에서는 `description` 필드에 더 엄격한 타입을 제공하여 필수 항목으로 만들고, 새로운 선택적 필드인 `category`를 추가합니다.

```ts {10-15}
// src/content.config.ts
import { defineCollection, z } from 'astro:content';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
  docs: defineCollection({
    loader: docsLoader(),
    schema: docsSchema({
      extend: z.object({
        // 기본 제공 필드를 선택 사항이 아닌 필수 항목으로 변경합니다.
        description: z.string(),
        // 스키마에 새 필드를 추가합니다.
        category: z.enum(['tutorial', 'guide', 'reference']).optional(),
      }),
    }),
  }),
};
```

[Astro `image()` 도우미](https://docs.astro.build/ko/guides/images/#콘텐츠-컬렉션의-이미지)를 활용하려면 스키마 확장을 반환하는 함수를 사용하세요.

```ts {10-15}
// src/content.config.ts
import { defineCollection, z } from 'astro:content';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
  docs: defineCollection({
    loader: docsLoader(),
    schema: docsSchema({
      extend: ({ image }) => {
        return z.object({
          // 로컬 이미지로 확인되어야 하는 필드를 추가합니다.
          cover: image(),
        });
      },
    }),
  }),
};
```


================================================
FILE: docs/src/content/docs/ko/reference/icons.mdx
================================================
---
title: 아이콘 참조
description: Starlight에서 사용할 수 있는 모든 아이콘에 대한 개요입니다.
---

Starlight는 `<Icon>` 컴포넌트를 사용하여 콘텐츠에 표시할 수 있는 내장 아이콘 세트를 제공합니다.

## 아이콘 사용

아이콘은 [`<Icon>`](/ko/components/icons/) 컴포넌트를 사용하여 표시할 수 있습니다.
또한 [카드](/ko/components/cards/)와 같은 다른 컴포넌트나 [히어로 액션](/ko/reference/frontmatter/#hero)과 같은 설정에서도 자주 사용됩니다.

## `StarlightIcon` 타입

`StarlightIcon` TypeScript 타입을 사용하여 [Starlight의 기본 제공 아이콘](#모든-아이콘)의 이름을 참조할 수 있습니다.

```ts {2} /icon: (StarlightIcon)/
// src/icon.ts
import type { StarlightIcon } from '@astrojs/starlight/types';

function getIconLabel(icon: StarlightIcon) {
	// …
}
```

## 모든 아이콘

사용 가능한 모든 아이콘의 목록과 관련 이름이 아래에 나와 있습니다. 아이콘을 클릭하면 해당 이름을 클립보드에 복사할 수 있습니다.

import IconsList from '~/components/icons-list.astro';

<IconsList labels={{ copied: '복사되었습니다!' }} />


================================================
FILE: docs/src/content/docs/ko/reference/overrides.md
================================================
---
title: 재정의 참조
description: Starlight 재정의에서 지원하는 컴포넌트 및 속성에 대한 개요입니다.
tableOfContents:
  maxHeadingLevel: 4
---

Starlight의 [`components`](/ko/reference/configuration/#components) 구성 옵션에 대체 컴포넌트에 대한 경로를 제공하여 Starlight의 내장 컴포넌트를 재정의할 수 있습니다.
이 페이지에는 재정의할 수 있는 모든 컴포넌트와 기본 구현에 대한 Github 링크가 나열되어 있습니다.

[컴포넌트 재정의 가이드](/ko/guides/overriding-components/)에서 자세히 알아보세요.

## 컴포넌트

### 헤드

이 컴포넌트들은 각 페이지의 `<head>` 요소 내에 렌더링됩니다.
또한, 반드시 [`<head>` 내에서 사용하는 것이 허용되는 요소](https://developer.mozilla.org/ko/docs/Web/HTML/Element/head#%EA%B0%99%EC%9D%B4_%EB%B3%B4%EA%B8%B0)만 포함해야 합니다.

#### `Head`

**기본 컴포넌트:** [`Head.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Head.astro)

각 페이지의 `<head>` 내에서 렌더링되는 컴포넌트입니다.

최후의 수단으로 이 컴포넌트를 재정의합니다.
기본 컴포넌트에서 렌더링되는 라우트 데이터를 사용자 정의하려면 [`head` 구성 옵션](/ko/reference/configuration/#head), [`head` 프런트매터 필드](/ko/reference/frontmatter/#head), 또는 [라우트 데이터 미들웨어](/ko/guides/route-data/#경로-데이터-사용자-정의)를 사용하는 것이 좋습니다.

#### `ThemeProvider`

**기본 컴포넌트:** [`ThemeProvider.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/ThemeProvider.astro)

다크/라이트 테마를 설정하기 위해 `<head>` 내에서 렌더링되는 컴포넌트입니다.
기본 구현에는 [`<ThemeSelect />`](#themeselect)에서 사용되는 인라인 스크립트와 `<template>`이 포함되어 있습니다.

---

### 접근성

#### `SkipLink`

**기본 컴포넌트:** [`SkipLink.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/SkipLink.astro)

`<body>` 내부에서 첫 번째 요소로 렌더링되며 메인 페이지의 콘텐츠로 이동하는 접근성을 위한 컴포넌트입니다.
기본적으로 키보드의 탭을 통해 선택하기 전까지는 숨겨져 있습니다.

---

### 레이아웃

이 컴포넌트들은 Starlight 컴포넌트들을 배치하고 다양한 중단점에서 보이는 모습을 관리합니다.
이 컴포넌트들을 재정의하면 상당한 복잡성이 발생하므로, 가능하면 하위 수준의 컴포넌트를 재정의하는 것이 좋습니다.

#### `PageFrame`

**기본 컴포넌트:** [`PageFrame.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/PageFrame.astro)  
**명명된 슬롯:** `header`, `sidebar`

대부분의 페이지 콘텐츠를 감싸는 레이아웃 컴포넌트입니다.
기본적으로 header-sidebar-main 레이아웃을 설정하고 슬롯으로 명명된 `header`와 `sidebar` 및 메인 콘텐츠에 대한 기본 슬롯을 포함합니다.
또한, 작은 (모바일) 뷰포트에서 사이드바 탐색 토글을 지원하기 위해 [`<MobileMenuToggle />`](#mobilemenutoggle)를 렌더링합니다.

#### `MobileMenuToggle`

**기본 컴포넌트:** [`MobileMenuToggle.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MobileMenuToggle.astro)

작은 (모바일) 뷰포트에서 사이드바 탐색 토글을 수행하는 [`<PageFrame>`](#pageframe) 내부에서 렌더링되는 컴포넌트입니다.

#### `TwoColumnContent`

**기본 컴포넌트:** [`TwoColumnContent.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/TwoColumnContent.astro)  
**명명된 슬롯:** `right-sidebar`

메인 콘텐츠 열과 오른쪽 사이드바 (목차)를 감싸는 레이아웃 컴포넌트입니다.
기본적으로 작은 뷰포트에서 하나의 열로 이루어진 레이아웃과 큰 뷰포트에서 두 개의 열로 이루어진 레이아웃 간 전환을 처리합니다.

---

### 헤더

Starlight의 상단 탐색 바를 렌더링하는 컴포넌트입니다.

#### `Header`

**기본 컴포넌트:** [`Header.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Header.astro)

Header 컴포넌트는 모든 페이지 상단에 표시됩니다.
기본적으로 [`<SiteTitle />`](#sitetitle), [`<Search />`](#search), [`<SocialIcons />`](#socialicons), [`<ThemeSelect />`](#themeselect), 와 [`<LanguageSelect />`](#languageselect)를 표시합니다.

#### `SiteTitle`

**기본 컴포넌트:** [`SiteTitle.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/SiteTitle.astro)

사이트 제목을 렌더링하기 위해 사이트 헤더 시작 부분에 렌더링되는 컴포넌트입니다.
기본적으로 Starlight 구성에 정의된 로고를 렌더링하는 논리가 포함합니다.

#### `Search`

**기본 컴포넌트:** [`Search.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Search.astro)

Starlight의 검색 UI를 렌더링하기 위해 사용되는 컴포넌트입니다. 기본적으로 헤더의 버튼과 클릭하면 [Pagefind의 UI](https://pagefind.app/)를 불러오는 검색 모달을 나타내는 코드가 포함되어 있습니다.

[`pagefind`](/ko/reference/configuration/#pagefind)가 비활성화되면 기본 검색 컴포넌트가 렌더링되지 않습니다.
그러나, `Search`를 재정의하면 `pagefind` 구성 옵션이 `false`인 경우에도 사용자 정의 컴포넌트가 항상 렌더링됩니다.
이를 통해, Pagefind가 활성화되지 않았을 때 대체 검색 공급자에 대한 UI를 추가할 수 있습니다.

#### `SocialIcons`

**기본 컴포넌트:** [`SocialIcons.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/SocialIcons.astro)

사이트 헤더에 렌더링되며 소셜 아이콘 링크를 포함하는 컴포넌트입니다.
기본적으로 아이콘과 링크를 렌더링하기 위해 Starlight 구성에서 [`social`](/ko/reference/configuration/#social) 옵션을 사용합니다.

#### `ThemeSelect`

**기본 컴포넌트:** [`ThemeSelect.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/ThemeSelect.astro)

사용자가 선호하는 색 구성표를 선택할 수 있도록 사이트 헤더에 렌더링되는 컴포넌트입니다.

#### `LanguageSelect`

**기본 컴포넌트:** [`LanguageSelect.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/LanguageSelect.astro)

사용자가 다른 언어로 전환할 수 있도록 사이트 헤더에 렌더링되는 컴포넌트입니다.

---

### 전역 사이드바

Starlight의 전역 사이드바에는 메인 사이트 탐색이 포함되어 있습니다.
좁은 뷰포트에서는 드롭다운 메뉴 뒤에 숨겨져 있습니다.

#### `Sidebar`

**기본 컴포넌트:** [`Sidebar.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Sidebar.astro)

전역 탐색이 포함된 페이지 콘텐츠 앞에 렌더링되는 컴포넌트입니다.
기본적으로 충분히 넓은 뷰포트에서는 사이드바로 나타나고, 작은 (모바일) 뷰포트에서는 드롭다운 메뉴로 나타납니다.
또한, 모바일 메뉴 내부에 추가 항목을 표시하기 위해 [`<MobileMenuFooter />`](#mobilemenufooter)를 렌더링합니다.

#### `MobileMenuFooter`

**기본 컴포넌트:** [`MobileMenuFooter.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MobileMenuFooter.astro)

모바일 드롭다운 메뉴 하단에 렌더링되는 컴포넌트입니다.
기본적으로 [`<ThemeSelect />`](#themeselect)와 [`<LanguageSelect />`](#languageselect)를 렌더링합니다.

---

### 페이지 사이드바

Starlight의 페이지 사이드바는 현재 페이지의 하위 제목을 간략하게 설명하는 목차를 표시합니다.
좁은 뷰포트에서는 고정된 드롭다운 메뉴로 축소됩니다.

#### `PageSidebar`

**기본 컴포넌트:** [`PageSidebar.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/PageSidebar.astro)

목차를 나타내기 위해 메인 페이지의 콘텐츠 앞에 렌더링되는 컴포넌트입니다.
기본적으로 [`<TableOfContents />`](#tableofcontents)와 [`<MobileTableOfContents />`](#mobiletableofcontents)를 렌더링합니다.

#### `TableOfContents`

**기본 컴포넌트:** [`TableOfContents.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/TableOfContents.astro)

더 넓은 뷰포트에서 현재 페이지의 목차를 렌더링하는 컴포넌트입니다.

#### `MobileTableOfContents`

**기본 컴포넌트:** [`MobileTableOfContents.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MobileTableOfContents.astro)

작은 (모바일) 뷰포트에서 현재 페이지의 목차를 렌더링하는 컴포넌트입니다.

---

### 콘텐츠

이 컴포넌트들은 페이지 콘텐츠의 메인 열에 렌더링됩니다.

#### `Banner`

**기본 컴포넌트:** [`Banner.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Banner.astro)

각 페이지 상단에 렌더링되는 배너 컴포넌트입니다.
기본적으로 페이지의 [`banner`](/ko/reference/frontmatter/#banner) 프론트매터 속성을 사용하여 렌더링 여부를 결정합니다.

#### `ContentPanel`

**기본 컴포넌트:** [`ContentPanel.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/ContentPanel.astro)

메인 콘텐츠 열의 섹션을 감싸는 레이아웃 컴포넌트입니다.

#### `PageTitle`

**기본 컴포넌트:** [`PageTitle.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/PageTitle.astro)

현재 페이지의 `<h1>` 요소를 포함하는 컴포넌트입니다.
기본 구현과 같이 `<h1>` 요소에 `id="_top"`을 설정해야 합니다.

#### `DraftContentNotice`

**기본 컴포넌트:** [`DraftContentNotice.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/DraftContentNotice.astro)

현재 페이지가 초안으로 표시되면 개발 중에 사용자에게 표시되는 알림입니다.

#### `FallbackContentNotice`

**기본 컴포넌트:** [`FallbackContentNotice.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/FallbackContentNotice.astro)

현재 언어에 대한 번역이 제공되지 않는 페이지에서 사용자에게 표시되는 알림입니다.
다국어 사이트에서만 사용됩니다.

#### `Hero`

**기본 컴포넌트:** [`Hero.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Hero.astro)

프론트매터에서 [`hero`](/ko/reference/frontmatter/#hero)를 설정했을 때, 페이지 상단에 렌더링되는 컴포넌트입니다.
기본적으로 큰 제목, 태그라인, 클릭 유도 문구 링크와 선택적 이미지를 표시합니다.

#### `MarkdownContent`

**기본 컴포넌트:** [`MarkdownContent.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MarkdownContent.astro)

각 페이지의 메인 콘텐츠 주위에 렌더링되는 컴포넌트입니다.
기본적으로 마크다운 콘텐츠에 적용할 기본 스타일을 설정합니다.

Markdown 콘텐츠 스타일은 `@astrojs/starlight/style/markdown.css`에도 노출되며 `.sl-markdown-content` CSS 클래스로 범위가 지정됩니다.

---

### 바닥글

이 컴포넌트들은 페이지 콘텐츠의 메인 열 하단에 렌더링됩니다.

#### `Footer`

**기본 컴포넌트:** [`Footer.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Footer.astro)

각 페이지 하단에 표시되는 바닥글 컴포넌트입니다.
기본적으로 [`<LastUpdated />`](#lastupdated), [`<Pagination />`](#pagination), 그리고 [`<EditLink />`](#editlink)를 표시합니다.

#### `LastUpdated`

**기본 컴포넌트:** [`LastUpdated.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/LastUpdated.astro)

마지막 업데이트 날짜를 표시하기 위해 페이지 바닥글에 렌더링되는 컴포넌트입니다.

#### `EditLink`

**기본 컴포넌트:** [`EditLink.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/EditLink.astro)

페이지를 편집할 수 있는 링크를 표시하기 위해 페이지 바닥글에 렌더링되는 컴포넌트입니다.

#### `Pagination`

**기본 컴포넌트:** [`Pagination.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Pagination.astro)

Component rendered in the page footer to display navigation arrows between previous/next pages.

이전/다음 페이지 사이에 탐색 화살표를 표시하기 위해 페이지 바닥글에 렌더링되는 컴포넌트입니다.


================================================
FILE: docs/src/content/docs/ko/reference/plugins.md
================================================
---
title: 플러그인 참조
description: Starlight 플러그인 API의 개요입니다.
tableOfContents:
  maxHeadingLevel: 4
---

Starlight 플러그인은 Starlight 구성, UI, 동작을 사용자 정의할 수 있을 뿐만 아니라 공유 및 재사용하기도 쉽습니다.
이 참조 페이지에는 플러그인이 액세스할 수 있는 API가 문서화되어 있습니다.

[구성 참조](/ko/reference/configuration/#plugins)에서 Starlight 플러그인 사용에 대해 자세히 알아보거나 [플러그인 쇼케이스](/ko/resources/plugins/)를 방문하여 사용 가능한 플러그인 목록을 확인하세요.

## 빠른 API 참조

Starlight 플러그인은 다음과 같은 형태를 가지고 있습니다.
다양한 속성과 훅 매개변수에 대한 자세한 내용은 아래를 참조하세요.

<!-- prettier-ignore-start -->
```ts
interface StarlightPlugin {
  name: string;
  hooks: {
    'i18n:setup'?: (options: {
      injectTranslations: (
        translations: Record<string, Record<string, string>>
      ) => void;
    }) => void | Promise<void>;
    'config:setup': (options: {
      config: StarlightUserConfig;
      updateConfig: (newConfig: StarlightUserConfig) => void;
      addIntegration: (integration: AstroIntegration) => void;
      addRouteMiddleware: (config: { entrypoint: string; order?: 'pre' | 'post' | 'default' }) => void;
      astroConfig: AstroConfig;
      command: 'dev' | 'build' | 'preview';
      isRestart: boolean;
      logger: AstroIntegrationLogger;
      useTranslations: (lang: string) => I18nT;
      absolutePathToLang: (path: string) => string;
    }) => void | Promise<void>;
  };
}
```
<!-- prettier-ignore-end -->

## `name`

**타입:** `string`

플러그인은 자신을 설명하는 고유한 이름을 제공해야 합니다. 이름은 이 플러그인과 관련된 [메시지를 로깅](#logger)할 때 사용되며 다른 플러그인에서 이 플러그인의 존재를 감지하는 데 사용될 수도 있습니다.

## `hooks`

훅은 Starlight가 특정 시간에 플러그인 코드를 실행하기 위해 호출하는 함수입니다.

훅의 인자 타입을 얻으려면 `HookParameters` 유틸리티 타입을 사용하고 훅 이름을 전달하세요.
다음 예제에서 `options` 매개변수는 `config:setup` 훅에 전달된 인자와 일치하도록 타입이 지정됩니다.

```ts
import type { HookParameters } from '@astrojs/starlight/types';

function configSetup(options: HookParameters['config:setup']) {
  options.useTranslations('ko');
}
```

### `i18n:setup`

Starlight가 초기화될 때 호출되는 플러그인 국제화 설정 함수입니다.
`i18n:setup` 훅을 사용하여 번역 문자열을 삽입할 수 있으므로 플러그인이 다른 로케일을 지원할 수 있습니다.
이러한 번역은 `config:setup` 훅에서 [`useTranslations()`](#usetranslations)를 통해, UI 컴포넌트에서 [`Astro.locals.t()`](/ko/guides/i18n/#ui-번역-사용)를 통해 사용할 수 있습니다.

`i18n:setup` 훅은 다음 옵션과 함께 호출됩니다:

#### `injectTranslations`

**타입:** `(translations: Record<string, Record<string, string>>) => void`

Starlight의 [지역화 API](/ko/guides/i18n/#ui-번역-사용)에서 사용되는 번역 문자열을 추가하거나 업데이트하는 콜백 함수입니다.

다음 예제에서 플러그인은 `en` 및 `fr` 로케일에 대해 `myPlugin.doThing`이라는 사용자 지정 UI 문자열에 대한 번역을 삽입합니다.

```ts {6-13} /(injectTranslations)[^(]/
// plugin.ts
export default {
  name: 'plugin-with-translations',
  hooks: {
    'i18n:setup'({ injectTranslations }) {
      injectTranslations({
        en: {
          'myPlugin.doThing': 'Do the thing',
        },
        fr: {
          'myPlugin.doThing': 'Faire le truc',
        },
      });
    },
  },
};
```

플러그인 UI에서 삽입된 번역을 사용하려면 ["UI 번역 사용" 가이드](/ko/guides/i18n/#ui-번역-사용)를 따르세요.
플러그인의 [`config:setup`](#configsetup) 훅의 컨텍스트에서 UI 문자열을 사용해야 하는 경우, [`useTranslations()`](#usetranslations) 콜백을 사용할 수 있습니다.

플러그인에 삽입된 번역 문자열의 타입은 사용자 프로젝트에서 자동으로 생성되지만, 플러그인 코드베이스에서 작업할 때는 아직 사용할 수 없습니다.
플러그인의 컨텍스트에서 `locals.t` 객체의 타입을 지정하려면 TypeScript 선언 파일에서 다음 전역 네임스페이스를 선언하세요:

```ts
// env.d.ts
declare namespace App {
  type StarlightLocals = import('@astrojs/starlight').StarlightLocals;
  // 플러그인 컨텍스트에서 `locals.t` 객체를 정의합니다.
  interface Locals extends StarlightLocals {}
}

declare namespace StarlightApp {
  // `I18n` 인터페이스에서 추가 플러그인 번역을 정의합니다.
  interface I18n {
    'myPlugin.doThing': string;
  }
}
```

번역이 포함된 객체가 있는 경우 소스 파일에서 `StarlightApp.I18n` 인터페이스의 타입을 추론할 수도 있습니다.

예를 들어, 다음 소스 파일이 주어졌을 때:

```ts title="ui-strings.ts"
export const UIStrings = {
  en: { 'myPlugin.doThing': 'Do the thing' },
  fr: { 'myPlugin.doThing': 'Faire le truc' },
};
```

다음 선언은 소스 파일의 영어 키에서 타입을 추론합니다:

```ts title="env.d.ts"
declare namespace StarlightApp {
  type UIStrings = typeof import('./ui-strings').UIStrings.en;
  interface I18n extends UIStrings {}
}
```

### `config:setup`

Starlight가 초기화될 때 호출되는 플러그인 구성 설정 함수입니다 ([`astro:config:setup`](https://docs.astro.build/ko/reference/integrations-reference/#astroconfigsetup) 통합 훅 실행 중 호출).
`config:setup` 훅을 사용하여 Starlight 구성을 업데이트하거나 Astro 통합을 추가할 수 있습니다.

이 훅은 다음 옵션들과 함께 호출됩니다.

#### `config`

**타입:** `StarlightUserConfig`

사용자 제공 [Starlight 구성](/ko/reference/configuration/)의 읽기 전용 복사본입니다.
이 구성은 현재 플러그인 이전에 구성된 다른 플러그인에 의해 업데이트되었을 수 있습니다.

#### `updateConfig`

**타입:** `(newConfig: StarlightUserConfig) => void`

사용자가 제공한 [Starlight 구성](/ko/reference/configuration/)을 업데이트하는 콜백 함수입니다.
재정의하려는 루트 수준 구성 키를 제공합니다.
중첩된 구성 값을 업데이트하려면 전체 중첩 객체를 제공해야 합니다.

기존 구성 옵션을 재정의하지 않고 확장하려면 기존 값을 새 값에 전개하여 확장하세요.
다음 예시에서는 `config.social`에 전개 연산자를 사용하여 새로운 `social` 배열을 확장합니다. 이를 통해, 새로운 [`social`](/ko/reference/configuration/#social) 미디어 계정을 기존 구성에 추가합니다.

```ts {6-15}
// plugin.ts
export default {
  name: 'add-twitter-plugin',
  hooks: {
    'config:setup'({ config, updateConfig }) {
      updateConfig({
        social: [
          ...config.social,
          {
            icon: 'twitter',
            label: 'Twitter',
            href: 'https://twitter.com/astrodotbuild',
          },
        ],
      });
    },
  },
};
```

#### `addIntegration`

**타입:** `(integration: AstroIntegration) => void`

플러그인에 필요한 [Astro 통합](https://docs.astro.build/ko/reference/integrations-reference/)을 추가하기 위한 콜백 함수입니다.

다음 예시에서 플러그인은 먼저 [Astro의 React 통합](https://docs.astro.build/ko/guides/integrations-guide/react/)이 구성되어 있는지 확인하고, 구성되어 있지 않으면 `addIntegration()`을 사용하여 이를 추가합니다.

```ts {14} "addIntegration,"
// plugin.ts
import react from '@astrojs/react';

export default {
  name: 'plugin-using-react',
  hooks: {
    'config:setup'({ addIntegration, astroConfig }) {
      const isReactLoaded = astroConfig.integrations.find(
        ({ name }) => name === '@astrojs/react'
      );

      // 아직 불러오지 않은 경우에만 React 통합을 추가합니다.
      if (!isReactLoaded) {
        addIntegration(react());
      }
    },
  },
};
```

#### `addRouteMiddleware`

**타입:** `(config: { entrypoint: string; order?: 'pre' | 'post' | 'default' }) => void`

사이트에 [경로 미들웨어 핸들러](/ko/guides/route-data/)를 추가하는 콜백 함수입니다.

`entrypoint` 속성은 `onRequest` 핸들러를 내보내는 플러그인 미들웨어 파일의 모듈 지정자여야 합니다.

다음 예제에서 `@example/starlight-plugin`으로 게시된 플러그인은 npm 모듈 지정자를 사용하여 경로 미들웨어를 추가합니다.

```js {6-9}
// plugin.ts
export default {
  name: '@example/starlight-plugin',
  hooks: {
    'config:setup'({ addRouteMiddleware }) {
      addRouteMiddleware({
        entrypoint: '@example/starlight-plugin/route-middleware',
      });
    },
  },
};
```

##### 실행 순서 제어

기본적으로 플러그인 미들웨어는 플러그인이 추가된 순서대로 실행됩니다.

미들웨어가 언제 실행되는지 더 세밀하게 제어해야 하는 경우 선택적 `order` 속성을 사용하세요.
사용자 미들웨어보다 먼저 실행하려면 `order: "pre"`를 설정하세요.
다른 모든 미들웨어 후에 실행하려면 `order: "post"`를 설정하세요.

두 플러그인이 동일한 `order` 값으로 미들웨어를 추가하는 경우 먼저 추가된 플러그인이 먼저 실행됩니다.

#### `astroConfig`

**타입:** `AstroConfig`

사용자 제공 [Astro 구성](https://docs.astro.build/ko/reference/configuration-reference/)의 읽기 전용 복사본입니다.

#### `command`

**타입:** `'dev' | 'build' | 'preview'`

Starlight를 실행하는 데 사용되는 명령:

- `dev` - 프로젝트는 `astro dev`로 실행
- `build` - 프로젝트는 `astro build`로 실행
- `preview` - 프로젝트는 `astro preview`로 실행

#### `isRestart`

**타입:** `boolean`

개발 서버가 시작되면 `false`, 서버가 다시 시작되면 `true`입니다.
개발 서버 재시작의 일반적인 이유에는 개발 서버가 실행되는 동안 사용자가 `astro.config.mjs`를 편집하는 경우가 포함됩니다.

#### `logger`

**타입:** `AstroIntegrationLogger`

로그를 작성하는 데 사용할 수 있는 [Astro 통합 로거](https://docs.astro.build/ko/reference/integrations-reference/#astrointegrationlogger)의 인스턴스입니다.
기록된 모든 메시지에는 플러그인 이름이 앞에 추가됩니다.

```ts {6}
// plugin.ts
export default {
  name: 'long-process-plugin',
  hooks: {
    'config:setup'({ logger }) {
      logger.info('시간이 오래 걸리는 작업 진행 중…');
      // 오래 걸리는 작업…
    },
  },
};
```

위 예시에서는 제공된 정보를 포함하는 메시지를 기록합니다.

```shell
[long-process-plugin] 시간이 오래 걸리는 작업 진행 중…
```

#### `useTranslations`

**타입:** `(lang: string) => I18nT`

BCP-47 언어 태그와 함께 `useTranslations()`를 호출하여 해당 언어의 UI 문자열에 접근할 수 있는 유틸리티 함수를 생성합니다.
`useTranslations()`는 Astro 컴포넌트에서 사용 가능한 `Astro.locals.t()` API와 동일한 기능을 반환합니다.
사용 가능한 API에 대한 자세한 내용은 ["UI 번역 사용"](/ko/guides/i18n/#ui-번역-사용) 가이드를 참조하세요.

```ts {6}
// plugin.ts
export default {
  name: 'plugin-use-translations',
  hooks: {
    'config:setup'({ useTranslations, logger }) {
      const t = useTranslations('zh-CN');
      logger.info(t('builtWithStarlight.label'));
    },
  },
};
```

위의 예제는 중국어 간체에 대한 내장 UI 문자열을 포함하는 메시지를 기록합니다.

```shell
[plugin-use-translations] 基于 Starlight 构建
```

#### `absolutePathToLang`

**타입:** `(path: string) => string`

절대 파일 경로와 함께 `absolutePathToLang()`을 호출하여 해당 파일의 언어를 가져옵니다.

이는 Markdown 또는 MDX 파일을 처리하기 위해 [remark 또는 rehype 플러그인](https://docs.astro.build/ko/guides/markdown-content/#markdown-플러그인)을 추가할 때 특히 유용할 수 있습니다.
이러한 플러그인에서 사용하는 [가상 파일 형식](https://github.com/vfile/vfile)에는 처리 중인 파일의 [절대 경로](https://github.com/vfile/vfile#filepath)가 포함되어 있으며, 이는 `absolutePathToLang()`과 함께 사용하여 파일의 언어를 확인할 수 있습니다.
반환된 언어는 해당 언어에 대한 UI 문자열을 가져오기 위해 [`useTranslations()`](#usetranslations) 도우미와 함께 사용할 수 있습니다.

예를 들어, 다음 Starlight 구성이 주어졌을 때:

```js
starlight({
  title: 'My Docs',
  defaultLocale: 'en',
  locales: {
    // `src/content/docs/en/`에서 영어 문서
    en: { label: 'English' },
    // `src/content/docs/fr/`에서 프랑스어 문서
    fr: { label: 'Français', lang: 'fr' },
  },
});
```

플러그인은 절대 경로를 사용하여 파일의 언어를 확인할 수 있습니다.

```ts {6-8} /fr/
// plugin.ts
export default {
  name: 'plugin-use-translations',
  hooks: {
    'config:setup'({ absolutePathToLang, useTranslations, logger }) {
      const lang = absolutePathToLang(
        '/absolute/path/to/project/src/content/docs/fr/index.mdx'
      );
      const t = useTranslations(lang);
      logger.info(t('aside.tip'));
    },
  },
};
```

위의 예제는 프랑스어에 대한 내장 UI 문자열을 포함하는 메시지를 기록합니다.

```shell
[plugin-use-translations] Astuce
```


================================================
FILE: docs/src/content/docs/ko/reference/route-data.mdx
================================================
---
title: 경로 데이터 참조
description: Starlight의 경로 데이터 객체에 대한 전체 참조 문서입니다.
---

Starlight의 경로 데이터 객체는 현재 페이지에 대한 정보를 담고 있습니다.
Starlight의 데이터 모델 작동 방식에 대한 자세한 내용은 ["경로 데이터" 가이드](/ko/guides/route-data/)에서 확인하세요.

Astro 컴포넌트에서는 `Astro.locals.starlightRoute`를 통해 경로 데이터에 접근할 수 있습니다.

```astro {4}
---
// src/components/Custom.astro

const { hasSidebar } = Astro.locals.starlightRoute;
---
```

[경로 미들웨어](/ko/guides/route-data/#경로-데이터-사용자-정의)에서는 미들웨어 함수에 전달된 컨텍스트 객체에서 경로 데이터에 접근합니다.

```ts {5}
// src/routeData.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

export const onRequest = defineRouteMiddleware((context) => {
	const { hasSidebar } = context.locals.starlightRoute;
});
```

## `starlightRoute`

`starlightRoute` 객체는 다음 속성을 가집니다.

### `dir`

**타입:** `'ltr' | 'rtl'`

페이지 작성 방향입니다.

### `lang`

**타입:** `string`

이 페이지의 로케일에 대한 BCP-47 언어 태그입니다. 예: `en`, `zh-CN` 또는 `pt-BR`

### `locale`

**타입:** `string | undefined`

언어가 제공되는 기본 경로입니다. 루트 로케일 슬러그의 경우 `undefined`입니다.

### `siteTitle`

**타입:** `string`

이 페이지의 로케일에 대한 사이트 제목입니다.

### `siteTitleHref`

**타입:** `string`

`/`처럼 홈페이지와 연결되는 사이트 제목 `href` 속성의 값입니다.
다국어 사이트의 경우 `/en/` 또는 `/zh-cn/`과 같은 현재 로케일이 포함됩니다.

### `slug`

**타입:** `string`

콘텐츠 파일 이름에서 생성된 이 페이지의 슬러그입니다.

이 속성은 더 이상 사용되지 않으며 향후 버전의 Starlight에서 제거될 예정입니다.
[Starlight의 `docsLoader`](/ko/manual-setup/#콘텐츠-컬렉션-구성)를 사용하여 새 콘텐츠 레이어 API로 마이그레이션하고 대신 [`id`](#id) 속성을 사용하세요.

### `id`

**타입:** `string`

이 페이지의 슬러그 또는 [`legacy.collections`](https://docs.astro.build/ko/reference/legacy-flags/#collections) 플래그를 사용하는 경우 콘텐츠 파일명을 기준으로 한 이 페이지의 고유 ID입니다.

### `isFallback`

**타입:** `boolean | undefined`

이 페이지가 현재 언어로 번역되지 않고 기본 로케일의 대체 콘텐츠를 사용하는 경우 `true`입니다.
다국어 사이트에서만 사용됩니다.

### `entryMeta`

**타입:** `{ dir: 'ltr' | 'rtl'; lang: string }`

페이지 콘텐츠의 로케일 메타데이터입니다. 페이지가 대체 콘텐츠를 사용하는 경우 최상위 로케일 값과 다를 수 있습니다.

### `entry`

현재 페이지에 대한 Astro 콘텐츠 컬렉션 항목입니다.
`entry.data`는 현재 페이지에 대한 프론트매터 값을 포함합니다.

```ts
entry: {
	data: {
		title: string;
		description: string | undefined;
		// 기타
	}
}
```

[Astro 컬렉션 엔트리 타입](https://docs.astro.build/ko/reference/modules/astro-content/#collectionentry) 참조에서 이 객체의 형태에 대해 자세히 알아보세요.

### `sidebar`

**타입:** `SidebarEntry[]`

페이지에 대한 사이트 탐색 사이드바 엔트리입니다.

### `hasSidebar`

**타입:** `boolean`

이 페이지에 사이드바를 표시할지 여부입니다.

### `pagination`

**타입:** `{ prev?: Link; next?: Link }`

활성화된 경우 사이드바의 이전 및 다음 페이지로 이동하는 링크를 표시합니다.

### `toc`

**타입:** `{ minHeadingLevel: number; maxHeadingLevel: number; items: TocItem[] } | undefined`

활성화된 경우 이 페이지의 목차를 표시합니다.

### `headings`

**타입:** `{ depth: number; slug: string; text: string }[]`

현재 페이지에서 추출된 모든 Markdown 제목의 배열입니다.
Starlight의 구성 옵션을 준수하는 콘텐츠 목차 컴포넌트를 생성하기 위해서는 [`toc`](#toc)를 사용하세요.

### `lastUpdated`

**타입:** `Date | undefined`

활성화된 경우 이 페이지가 마지막으로 업데이트된 날짜를 나타내기 위해 JavaScript `Date`객체가 사용됩니다.

### `editUrl`

**타입:** `URL | undefined`

활성화된 경우 이 페이지를 편집할 수 있는 주소를 나타내기 위해 `URL` 객체가 사용됩니다.

### `head`

**타입:** [`HeadConfig[]`](/ko/reference/configuration/#headconfig)

현재 페이지의 `<head>`에 포함할 모든 태그의 배열입니다.
`<title>` 및 `<meta charset="utf-8">`과 같은 중요한 태그를 포함합니다.

## 유틸리티

### `defineRouteMiddleware()`

`defineRouteMiddleware()` 유틸리티를 사용하여 경로 미들웨어 모듈의 타입을 지정하세요:

```ts "defineRouteMiddleware"
// src/routeData.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

export const onRequest = defineRouteMiddleware((context) => {
	// ...
});
```

### `StarlightRouteData` 타입

Starlight의 경로 데이터를 사용해야 하는 코드를 작성하는 경우, `StarlightRouteData` 타입을 가져와 `Astro.locals.starlightRoute`의 형태와 일치시킬 수 있습니다.

다음 예제에서 `usePageTitleInTOC()` 함수는 경로 데이터를 업데이트하여 현재 페이지의 제목을 목차의 첫 번째 항목 레이블로 사용하고 기본 "개요" 레이블을 대체합니다. `StarlightRouteData` 타입을 사용하면 경로 데이터 변경 사항이 유효한지 확인할 수 있습니다.

```ts "StarlightRouteData"
// src/route-utils.ts
import type { StarlightRouteData } from '@astrojs/starlight/route-data';

export function usePageTitleInTOC(starlightRoute: StarlightRouteData) {
	const overviewLink = starlightRoute.toc?.items[0];
	if (overviewLink) {
		overviewLink.text = starlightRoute.entry.data.title;
	}
}
```

이 함수는 경로 미들웨어에서 호출할 수 있습니다.

```ts {3,6}
// src/route-middleware.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';
import { usePageTitleInTOC } from './route-utils';

export const onRequest = defineRouteMiddleware((context) => {
	usePageTitleInTOC(context.locals.starlightRoute);
});
```


================================================
FILE: docs/src/content/docs/ko/resources/community-content.mdx
================================================
---
title: 커뮤니티 콘텐츠
description: Starlight를 배우고 구축하는 데 도움이 되는 커뮤니티 제작 가이드, 기사 및 비디오를 찾아보세요!
---

:::tip[직접 추가하세요!]
Starlight에 대한 콘텐츠를 제작한 적이 있나요?
이 페이지에 링크를 추가하여 PR을 열어보세요!
:::

import { CardGrid, LinkCard } from '@astrojs/starlight/components';

## 기사 및 리뷰

다음은 Starlight와 다른 사람들의 경험에 대해 자세히 알아볼 수 있는 게시물과 기사 모음입니다.

<CardGrid>
	<LinkCard
		href="https://devm.io/open-source/starlight-astro"
		title="Starlight를 사용한 정적 사이트 생성"
		description="“컴포넌트를 설계할 때 아이디어가 너무 크거나 너무 작으면 안 됩니다.” — Starlight 리드 개발자인 Chris Swithinbank와의 인터뷰"
	/>
	<LinkCard
		href="https://frontendatscale.com/blog/hybrid-frontend-architecture/"
		title="Astro와 Starlight를 사용한 하이브리드 프런트엔드 아키텍처"
		description="Maxi Ferreira와 Ben Holmes는 Starlight, TinaCMS 및 인증 기능이 있는 대화형 API 플레이그라운드를 사용하여 문서 사이트를 구축합니다."
	/>
	<LinkCard
		href="https://www.olets.dev/posts/comparing-docs-site-builders-vuepress-vs-starlight/"
		title="문서 사이트 빌더 비교: VuePress vs Starlight"
		description="이 두 프레임워크는 어떻게 비교되나요?"
	/>
	<LinkCard
		href="https://astro.build/case-studies/wp-engine/"
		title="사례 연구: 개발 비용 절감"
		description="WP Engine이 Astro의 Starlight로 개발 비용을 50% 이상 절감한 방법"
	/>
	<LinkCard
		href="https://maciekpalmowski.dev/blog/building-a-documentation-site-using-astro-starlight/"
		title="Astro의 Starlight를 사용한 문서 사이트 구축"
		description="Patchstack 문서를 Starlight로 마이그레이션하는 과정 - Maciek Palmowski"
	/>
	<LinkCard
		href="https://blog.cloudflare.com/open-source-all-the-way-down-upgrading-our-developer-documentation/"
		title="오픈소스의 힘으로"
		description="Cloudflare가 Starlight로 개발자 문서를 개선한 방법"
	/>
	<LinkCard
		href="https://starlight-changelog.netlify.app/"
		title="Starlight 변경 로그"
		description="@astrojs/starlight 패키지의 모든 릴리스를 한눈에 볼 수 있는 멋진 페이지"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/contributing-to-starlight"
		title="Starlight에 기여하기"
		description="Starlight와 같은 오픈 소스 프로젝트에 기여하는 것에 대한 개인적인 경험과 제안"
	/>
</CardGrid>

## 레시피 및 가이드

레시피는 일반적으로 특정 작업의 실제 예시를 완료하는 과정을 독자에게 안내하는 짧고 집중적인 가이드입니다. 레시피는 단계별 지침에 따라 Starlight 프로젝트에 새로운 기능이나 동작을 추가할 수 있는 좋은 방법입니다! 다른 가이드에서는 이미지 사용이나 MDX 작업 등 콘텐츠 영역과 관련된 개념을 설명할 수도 있습니다.

Starlight 사용자들이 관리하는 커뮤니티 제작 콘텐츠를 살펴보세요.

<CardGrid>
	<LinkCard
		href="https://www.webpro.nl/scraps/versioned-docs-with-starlight-and-vercel"
		title="Starlight & Vercel을 사용한 버전별 문서"
		description="프로젝트의 각 주요 버전에 대해 별도의 문서 버전을 구현하는 방법에 대한 가이드"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-heading-links"
		title="Starlight 제목에 링크 추가"
		description="문서의 특정 섹션에 대한 링크를 공유하기 위한 rehype 플러그인 사용 가이드"
	/>
	<LinkCard
		href="https://blog.otterlord.dev/posts/starlight-sponsors/"
		title="Starlight 사이트에 스폰서 추가"
		description="문서 사이드바에 맞춤 스폰서 컴포넌트를 구현하기 위한 가이드"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-og-images"
		title="Starlight에 Open Graph 이미지 추가"
		description="페이지에 대한 소셜 이미지 및 해당 메타 태그 생성에 대한 가이드"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-third-party-icon-sets"
		title="Starlight에서 타사 아이콘 세트 사용"
		description="unplugin-icons를 사용하여 Starlight에 사용 가능한 아이콘 선택 범위를 확장하는 방법에 대한 가이드"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-custom-html-head"
		title="Starlight 페이지의 HTML 헤드 편집"
		description="웹 분석, 글꼴, 스크립트 등 일반적인 헤드 콘텐츠를 추가하는 방법을 알아보세요."
	/>
	<LinkCard
		href="https://dev.to/mrrobot/publishing-documentation-with-astro-starlight-691"
		title="Astro Starlight로 문서 게시"
		description="Starlight 문서 시작하기"
	/>
	<LinkCard
		href="https://events-3bg.pages.dev/jotter/starlight/"
		title="뷰 전환 활성화"
		description="Starlight 문서 사이트에 뷰 전환, 클라이언트 측 라우팅 및 SPA와 유사한 탐색 지원을 추가합니다."
	/>
	<LinkCard
		href="https://jamcomments.com/posts/structured-data-with-starlight"
		title="Starlight 페이지에 구조화된 데이터 추가"
		description="문서 페이지에 대한 동적 JSON-LD 구조화된 데이터를 구축하는 방법을 알아보세요."
	/>
	<LinkCard
		href="https://starlight-examples.netlify.app/"
		title="Starlight 예시"
		description="Starlight 문서 사이트에서 작업을 수행하는 실용적인 방법을 보여주는 StackBlitz 임베드 모음입니다."
	/>
	<LinkCard
		href="https://hideoo.dev/notebooks/starlight-plugins-by-example"
		title="Starlight Plugins 예시"
		description="Starlight 플러그인과 이를 빌드하는 데 사용되는 일반적인 패턴에 대한 정보와 예시 모음입니다."
	/>
	<LinkCard
		href="https://blog.trueberryless.org/blog/starlight-progress-indicator/"
		title="읽기 진행률 표시기 추가"
		description="Starlight 사이트에 가로 읽기 진행률 표시줄을 추가하는 방법을 알아보세요."
	/>
	<LinkCard
		href="https://blog.trueberryless.org/blog/starlight-sidebar-whitespace/"
		title="Starlight 사이드바에 사용자 정의 스타일 적용"
		description="Starlight 사이드바의 글꼴, 색상 등을 조정하기 위한 약간의 CSS를 사용합니다."
	/>
	<LinkCard
		href="https://blog.trueberryless.org/blog/starlight-dropdown-and-list-together/"
		title="모바일에서는 Starlight 주제 드롭다운, 데스크톱에서는 목록"
		description="데스크톱 및 모바일 장치 모두에서 최고의 경험을 제공하기 위해 두 가지 플러그인을 결합합니다."
	/>
	<LinkCard
		href="https://blog.trueberryless.org/blog/starlight-autogenerate-whole-sidebar/"
		title="미들웨어를 사용하여 Starlight 사이드바 처리"
		description="라우트 미들웨어를 사용하여 사이드바 순서와 그룹 레이블을 제어합니다. 이는 Nuxt Content의 규칙에서 영감을 얻었습니다."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-custom-social-links"
		title="사용자 정의 아이콘을 사용하여 Starlight에 소셜 링크 추가"
		description="Starlight 웹사이트 헤더에 소셜 링크용 사용자 정의 아이콘을 사용하는 방법을 알아보세요."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-paste-images-with-visual-studio-code"
		title="Visual Studio Code를 사용하여 Starlight 페이지에 이미지 붙여넣기"
		description="Visual Studio Code를 사용하여 Starlight 문서 페이지에 이미지를 붙여넣어 Starlight 문서 워크플로를 개선하세요."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-add-diagrams-using-d2"
		title="D2를 사용하여 Starlight 문서에 다이어그램 추가"
		description="D2를 사용하여 Starlight 문서에 다이어그램을 추가하는 방법을 알아보세요."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-og-images-cloudinary-astro-sdk"
		title="Cloudinary Astro SDK를 사용하여 Starlight용 오픈 그래프 이미지 생성"
		description="Cloudinary Astro SDK를 사용하여 Starlight 문서 웹사이트용 오픈 그래프 이미지를 생성하는 방법을 알아보세요."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-list-recent-github-releases"
		title="Astro의 Content Layer API를 사용하여 Starlight에 최근 GitHub 릴리스 나열"
		description="Astro의 Content Layer API를 사용하여 Starlight 프로젝트에 최근 GitHub 릴리스를 나열하는 방법을 알아보세요."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-sitewide-banner"
		title="Starlight에 사이트 전체 배너 추가"
		description="Starlight의 페이지별 배너 기능을 사용하여 사이트 전체 배너를 만드는 방법을 알아보세요."
	/>
	<LinkCard
		href="https://lirantal.com/blog/customizing-astro-starlight-sidebar-gated-content-auth"
		title="인증을 통해 게이트된 콘텐츠용 Astro Starlight 사이드바 사용자 정의"
		description="Clerk 및 SSR을 사용하여 사용자 로그인 여부에 따라 Starlight 사이드바 챕터를 동적으로 숨기거나 표시하여 강의 자료를 보호하세요."
	/>
</CardGrid>

## 영상 콘텐츠

라이브 스트림, 교육 콘텐츠 등 Starlight 콘텐츠가 포함된 비디오와 채널을 찾아보세요.

import YouTubeGrid from '~/components/youtube-grid.astro';

### 공식 동영상

<YouTubeGrid
	videos={[
		{
			href: 'https://www.youtube.com/watch?v=5u0Ds7wzUeI',
			title: 'Astro의 Starlight',
			description: '공식 Starlight 출시 영상을 시청합니다.',
		},
		{
			href: 'https://www.youtube.com/watch?v=j8K-ESJF814',
			title: 'Starlight 1주년!',
			description:
				'Sarah가 Astro의 커뮤니티 제작 문서 테마에 대해 이야기합니다.',
		},
	]}
/>

### 커뮤니티 동영상 및 스트림

<YouTubeGrid
	videos={[
		{
			href: 'https://www.youtube.com/shorts/zjOWezSzd18',
			title: '🌟 1분 안에 시작하기',
			description:
				'Ben이 1분 안에 새로운 Starlight 사이트를 시작하는 것을 확인하세요!',
		},
		{
			href: 'https://www.youtube.com/watch?v=sF6UcV3moZg',
			title: 'Starlight 및 Astro를 사용하여 문서 작성',
			description:
				'CodingCat.dev를 통해 Chris와 Alex가 Code에서 Starlight에 대해 알아보는 모습을 시청하세요.',
		},
		{
			href: 'https://www.youtube.com/watch?v=sWkkHbwDeQc',
			title: 'Astro Starlight',
			description: '1분 안에 Starlight 소개',
		},
		{
			href: 'https://www.youtube.com/watch?v=-Ki-1E5gNCk',
			title: 'Astro Starlight 문서 템플릿 (맞춤형 앱 문서 구축!)',
			description: '약 5분 안에 새로운 Starlight 사이트를 시작하고 실행하세요.',
		},
		{
			href: 'https://www.youtube.com/watch?v=12o7WxjAxjM',
			title: '프록시를 사용하여 Next.js 프로젝트에 Starlight 문서 포함',
			description:
				'Next.js 웹사이트 내 하위 디렉터리 프로젝트로 Starlight 설정',
		},
		{
			href: 'https://www.youtube.com/watch?v=5pq80drDrNs',
			title:
				'이 놀라운 도구를 사용하여 Shadcn의 문서를 30분 만에 다시 만들었습니다.',
			description:
				'이 비디오에서는 Starlight가 왜 그렇게 멋진지, 그리고 왜 다음 프로젝트에서 Starlight를 사용해 보고 싶은지 설명합니다.',
		},
		{
			href: 'https://www.youtube.com/watch?v=Q1E4Gkt63ko',
			title: 'Astro Starlight와 emoji-blast - Chris Swithinbank',
			description:
				'프레임워크 온 프레임워크인 Astro Starlight의 창시자 Chris가 새로운 emoji-blast 웹사이트를 설정하는 과정을 안내합니다. 🌟 🎇',
		},
	]}
/>


================================================
FILE: docs/src/content/docs/ko/resources/plugins.mdx
================================================
---
title: 플러그인 및 통합
description: Starlight를 확장하는 플러그인 및 통합과 같은 커뮤니티 도구를 찾아보세요!
sidebar:
  order: 1
---

:::tip[직접 추가하세요!]
Starlight용 플러그인이나 도구를 구축하셨나요?
이 페이지에 링크를 추가하여 PR을 열어보세요!
:::

## 플러그인

[플러그인](/ko/reference/plugins/)은 Starlight 구성, UI 및 동작을 사용자 정의하는 동시에 쉽게 공유하고 재사용할 수 있습니다.
Starlight 팀이 지원하는 공식 플러그인과 Starlight 사용자가 관리하는 커뮤니티 플러그인으로 사이트를 확장하세요.

### 공식 플러그인

<CardGrid>
	<LinkCard
		href="/ko/guides/site-search/#algolia-docsearch"
		title="Algolia DocSearch"
		description="기본 검색 공급자인 Pagefind를 Algolia DocSearch로 바꾸세요."
	/>
</CardGrid>

### 커뮤니티 플러그인

<CardGrid>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-links-validator"
		title="starlight-links-validator"
		description="Starlight 페이지에 끊어진 링크가 있는지 확인하세요."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-typedoc"
		title="starlight-typedoc"
		description="TypeDoc을 사용하여 TypeScript로 Starlight 페이지를 생성하세요."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-blog"
		title="starlight-blog"
		description="문서 사이트에 블로그를 추가하세요."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-openapi"
		title="starlight-openapi"
		description="OpenAPI/Swagger 사양에서 문서 페이지를 만드세요."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-obsidian"
		title="starlight-obsidian"
		description="Starlight 사이트에 Obsidian Vault를 게시하세요."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-image-zoom"
		title="starlight-image-zoom"
		description="문서 이미지에 확대/축소 기능을 추가하세요."
	/>
	<LinkCard
		href="https://github.com/lorenzolewis/starlight-utils"
		title="starlight-utils"
		description="일반적인 유틸리티 모음으로 Starlight를 확장하세요."
	/>
	<LinkCard
		href="https://github.com/trueberryless/starlight-view-modes"
		title="starlight-view-modes"
		description="문서 웹사이트에 다양한 보기 모드 기능을 추가하세요."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-versions"
		title="starlight-versions"
		description="Starlight 문서 페이지 버전을 지정하세요."
	/>
	<LinkCard
		href="https://inox-tools.fryuni.dev/star-warp"
		title="star-warp"
		description="문서에서 검색 결과를 워프 드라이브합니다."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-heading-badges"
		title="starlight-heading-badges"
		description="Markdown 및 MDX 제목에 배지를 추가합니다."
	/>
	<LinkCard
		href="https://github.com/Fevol/starlight-site-graph"
		title="starlight-site-graph"
		description="페이지 사이드바에 대화형 사이트 그래프를 추가합니다."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-sidebar-topics"
		title="starlight-sidebar-topics"
		description="문서를 각각 고유한 사이드바가 있는 여러 섹션으로 분할하세요."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-cooler-credit"
		title="starlight-cooler-credit"
		description="Starlight 또는 Astro 목차 하단에 멋진 크레딧을 추가하세요."
	/>
	<LinkCard
		href="https://github.com/dragomano/starlight-giscus"
		title="starlight-giscus"
		description="문서 사이트에 Giscus 댓글을 추가하세요."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-videos"
		title="starlight-videos"
		description="비디오 가이드와 강좌로 문서를 개선하세요."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-kbd"
		title="starlight-kbd"
		description="키보드 단축키를 쉽게 문서화하세요."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-auto-sidebar"
		title="starlight-auto-sidebar"
		description="자동 생성된 사이드바 그룹을 자유롭게 수정하세요."
	/>
	<LinkCard
		href="https://github.com/delucis/starlight-llms-txt"
		title="starlight-llms-txt"
		description="llmstxt.org를 기반으로 llms.txt를 문서 사이트에 추가하세요."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-toc-overview-customizer"
		title="starlight-toc-overview-customizer"
		description="사용자 정의 가능한 개요 제목으로 Starlight의 목차를 자유롭게 수정하세요."
	/>
	<LinkCard
		href="https://delucis.github.io/starlight-markdown-blocks/"
		title="starlight-markdown-blocks"
		description="사용자 지정 블록 타입으로 Starlight의 Markdown 보조 내용 (Asides) 구문을 확장하세요."
	/>
	<LinkCard
		href="https://github.com/WindMillCode/starlight-fullview-mode"
		title="starlight-fullview-mode"
		description="전체 화면 경험을 위해 사이드바를 접고 콘텐츠를 확장합니다."
	/>
	<LinkCard
		href="https://github.com/frostybee/starlight-scroll-to-top"
		title="starlight-scroll-to-top"
		description="문서 사이트에 맨 위로 이동하는 버튼을 추가하세요."
	/>
	<LinkCard
		href="https://github.com/frostybee/starlight-codeblock-fullscreen"
		title="starlight-codeblock-fullscreen"
		description="문서에 있는 Expressive Code 블록에 전체 화면 토글 기능을 추가하세요."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-auto-drafts"
		title="starlight-auto-drafts"
		description="초안 페이지의 기본 동작을 조정하여 프로덕션 모드에서 초안 페이지에 대한 사이드바 링크를 자동으로 제거합니다."
	/>
	<LinkCard
		href="https://github.com/corsfix/starlight-contextual-menu"
		title="starlight-contextual-menu"
		description="Starlight 문서에 컨텍스트 메뉴를 추가하세요."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-changelogs"
		title="starlight-changelogs"
		description="프로젝트 문서와 함께 변경 로그를 표시하세요."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-github-alerts"
		title="starlight-github-alerts"
		description="Starlight에서 GitHub 알림을 렌더링합니다."
	/>
	<LinkCard
		href="https://github.com/dlcastillop/starlight-page-actions"
		title="starlight-page-actions"
		description="문서에 페이지 작업 버튼을 추가합니다."
	/>
	<LinkCard
		href="https://github.com/typesense/starlight-docsearch-typesense"
		title="starlight-docsearch-typesense"
		description="공식 Algolia DocSearch 플러그인에 대한 Typesense 기반 대안입니다."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-sidebar-swipe/"
		title="starlight-sidebar-swipe"
		description="모바일 Discord 앱처럼, 모바일 장치에서 왼쪽 사이드바를 스와이프할 수 있게 만듭니다."
	/>
	<LinkCard
		href="https://github.com/Rettend/starlight-plugin-icons"
		title="starlight-plugin-icons"
		description="Astro Starlight의 사이드바, 코드 블록, 파일 트리에 아이콘을 추가합니다."
	/>
	<LinkCard
		href="https://github.com/dlcastillop/starlight-ui-tweaks"
		title="starlight-ui-tweaks"
		description="사용자 정의 탐색 링크, 광고, 마케팅 푸터, 더 깔끔한 테마 토글로 핵심 UI 컴포넌트를 확장합니다."
	/>
	<LinkCard
		href="https://frostybee.github.io/starlight-tags/"
		title="starlight-tags"
		description="Starlight 문서 페이지에 콘텐츠 조직 및 탐색을 위한 태그를 추가하세요."
	/>
	<LinkCard
		href="https://github.com/dionysuzx/starlight-copy-button"
		title="starlight-copy-button"
		description="페이지 제목에 세련된 버튼을 추가해, 문서 전체 페이지를 Markdown 형식으로 한 번에 복사할 수 있습니다."
	/>
	<LinkCard
		href="https://frostybee.github.io/starlight-telescope/"
		title="starlight-telescope"
		description="퍼지 검색과 키보드 중심 탐색을 통해 Starlight 문서의 모든 페이지로 빠르게 이동할 수 있습니다."
	/>
	<LinkCard
		href="https://frostybee.github.io/starlight-announcement/"
		title="starlight-announcement"
		description="닫기 기능, 다양한 스타일, 예약 설정, 특정 페이지 지정 기능을 지원하는 향상된 공지 배너를 Starlight 문서에 추가할 수 있습니다."
	/>
</CardGrid>

## 커뮤니티 도구 및 통합

import { CardGrid, LinkCard } from '@astrojs/starlight/components';

이러한 커뮤니티 도구 및 통합을 사용하여 Starlight 사이트에 기능을 추가할 수 있습니다.

<CardGrid>
	<LinkCard
		href="https://www.feelback.dev/blog/new-astro-starlight-integration/"
		title="FeelBack"
		description="문서 페이지에 사용자 피드백 시스템을 추가하세요."
	/>
	<LinkCard
		href="https://github.com/val-town/notion-to-astro"
		title="notion-to-astro"
		description="Notion 내보내기를 Astro Starlight 문서로 변환하세요"
	/>
	<LinkCard
		href="https://github.com/mattjennings/astro-live-code"
		title="astro-live-code"
		description="MDX 코드 블록을 대화형 컴포넌트로 렌더링하세요"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-i18n"
		title="starlight-i18n"
		description="Starlight 페이지를 번역하는 데 도움이 되는 Visual Studio Code 확장입니다."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-package-managers"
		title="starlight-package-managers"
		description="여러 패키지 관리자에 대한 npm 관련 명령을 빠르게 표시합니다."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-showcases"
		title="starlight-showcases"
		description="쇼케이스 페이지를 작성하기 위한 Starlight 컴포넌트의 집합입니다."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/generator-starlight-plugin"
		title="@hideoo/starlight-plugin"
		description="Starlight 플러그인을 빠르게 스캐폴딩할 수 있는 생성기입니다."
	/>
	<LinkCard
		href="https://github.com/Linkerin/starlight-to-pdf"
		title="starlight-to-pdf"
		description="Starlight 웹사이트들을 PDF 파일들로 변환하기 위한 CLI 도구입니다."
	/>
	<LinkCard
		href="https://github.com/joesaby/astro-plantuml"
		title="astro-plantuml"
		description="Markdown 코드 블록에서 PlantUML 콘텐츠를 렌더링합니다."
	/>
	<LinkCard
		href="https://github.com/joesaby/astro-mermaid"
		title="astro-mermaid"
		description="Markdown 코드 블록의 Mermaid 콘텐츠를 클라이언트 측에서 렌더링합니다."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/astro-d2"
		title="astro-d2"
		description="D2 Markdown 코드 블록을 다이어그램으로 변환합니다."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-links"
		title="starlight-links"
		description="Starlight의 Markdown 및 MDX 콘텐츠 링크에 대한 IntelliSense를 제공하는 Visual Studio Code 확장 프로그램입니다."
	/>
	<LinkCard
		href="https://docs.contentisland.net/templates/starlight/"
		title="contentisland-cli"
		description="Starlight 프로젝트를 Content Island Headless CMS에 연결하고 동기화하여 문서를 편집하고 관리하세요."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-sidebar-topics-dropdown"
		title="starlight-sidebar-topics-dropdown"
		description="문서 페이지를 여러 하위 페이지로 분할하고 이를 사이드바의 드롭다운 메뉴로 전환합니다."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-save-file-component"
		title="starlight-save-file-component"
		description="Starlight 사이트에서 다운로드 가능한 자산의 링크를 빠르게 표시합니다."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-contributor-list"
		title="starlight-contributor-list"
		description="프로젝트의 모든 기여자 목록을 표시합니다."
	/>
</CardGrid>


================================================
FILE: docs/src/content/docs/ko/resources/showcase.mdx
================================================
---
title: Starlight 쇼케이스
description: Starlight로 구축된 사이트를 찾아보세요!
sidebar:
  label: 사이트 쇼케이스
---

:::tip[직접 추가하세요!]
Starlight 사이트를 구축하셨나요?
이 페이지에 링크를 추가하는 [PR을 오픈하세요](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md#showcase)!
:::

## 사이트

import ShowcaseSites from '~/components/showcase-sites.astro';

Starlight는 이미 프로덕션에 사용되고 있습니다. 다음은 웹사이트 중 일부입니다.

<ShowcaseSites />

[GitHub에서 Starlight를 사용하는 공개 프로젝트 저장소](https://github.com/withastro/starlight/network/dependents)를 모두 확인하세요.


================================================
FILE: docs/src/content/docs/ko/resources/themes.mdx
================================================
---
title: 테마
description: Starlight의 커뮤니티 테마로 문서를 스타일링하세요.
tableOfContents: false
sidebar:
  order: 2
head:
  - tag: style
    content: |
      body { --sl-content-width: 66.75rem; }
---

import ThemeGrid from '~/components/theme-grid.astro';

테마는 [사용자 정의 CSS](/ko/guides/css-and-tailwind/), [컴포넌트 재정의](/ko/guides/overriding-components/) 또는 기타 새로운 기능을 사용하여 사이트의 시각적 모양을 변경하는 Starlight 플러그인입니다.

## 커뮤니티 테마

커뮤니티에서 빌드한 테마를 설치하여 사이트의 모양과 느낌을 빠르게 사용자 정의하세요.

아래에서 모든 테마 목록을 확인하거나 [Starlight 테마 데모 사이트](https://starlight-themes.netlify.app/)에서 직접 사용해 보세요.

<ThemeGrid
	labels={{
		/** 테마 전환을 위한 접근성 레이블입니다. */
		legend: '미리보기',
		/** 어두운 색상 체계 변형에 대한 접근성 레이블입니다. */
		dark: '다크',
		/** 밝은 색상 체계 변형에 대한 접근성 레이블입니다. */
		light: '라이트',
	}}
	themes={[
		{
			title: 'Starlight Rapide',
			description:
				'Visual Studio Code Vitesse 테마에서 영감을 받은 Starlight 테마',
			href: 'https://starlight-theme-rapide.vercel.app/',
			previews: { light: 'rapide-light.png', dark: 'rapide-dark.png' },
		},
		{
			title: 'Starlight Obsidian',
			description:
				'Obsidian Publish 사이트 스타일에서 영감을 받은 Starlight 테마',
			href: 'https://fevol.github.io/starlight-theme-obsidian/',
			previews: { light: 'obsidian-light.png', dark: 'obsidian-dark.png' },
		},
		{
			title: 'Catppuccin for Starlight',
			description: 'Starlight를 위한 편안한 파스텔 테마',
			href: 'https://starlight.catppuccin.com/',
			previews: { light: 'catppuccin-light.png', dark: 'catppuccin-dark.png' },
		},
		{
			title: 'Ion',
			description: 'Starlight를 위한 세련되고 현대적인 테마',
			href: 'https://louisescher.github.io/starlight-ion-theme/',
			previews: { light: 'ion-light.png', dark: 'ion-dark.png' },
		},
		{
			title: 'Starlight Black',
			description: 'shadcn 문서에서 영감을 받은 Starlight 테마',
			href: 'https://starlight-theme-black.vercel.app/',
			previews: { light: 'black-light.png', dark: 'black-dark.png' },
		},
		{
			title: 'Starlight Flexoki',
			description: 'Flexoki 색상 팔레트를 기반으로 한 따뜻하고 친근한 테마',
			href: 'https://delucis.github.io/starlight-theme-flexoki/',
			previews: { light: 'flexoki-light.png', dark: 'flexoki-dark.png' },
		},
		{
			title: 'Starlight Nova',
			description: 'Starlight를 위한 현대적이고 아름다운 테마',
			href: 'https://starlight-theme-nova.pages.dev/',
			previews: { light: 'nova-light.png', dark: 'nova-dark.png' },
		},
		{
			title: 'Starlight Next.js',
			description: 'Next.js 문서에서 영감을 받은 Starlight 테마',
			href: 'https://starlight-theme-next.trueberryless.org/',
			previews: { light: 'nextjs-light.png', dark: 'nextjs-dark.png' },
		},
		{
			title: 'Starlight Galaxy',
			description:
				'문서 및 교육 콘텐츠 게시를 위한 맞춤형 Astro Starlight 테마',
			href: 'https://frostybee.github.io/starlight-theme-galaxy/',
			previews: { light: 'galaxy-light.png', dark: 'galaxy-dark.png' },
		},
		{
			title: 'Starlight Page',
			description:
				'직관적이고 현대적이며, 부드러운 플로팅 애니메이션을 갖춘 Starlight 테마',
			href: 'https://pelagornis-page.netlify.app/',
			previews: { light: 'page-light.png', dark: 'page-dark.png' },
		},
		{
			title: 'Starlight Gruvbox',
			description: 'Starlight를 위한 레트로 그루브 테마',
			href: 'https://starlight-theme-gruvbox.otterlord.dev/',
			previews: { light: 'gruvbox-light.png', dark: 'gruvbox-dark.png' },
		},
		{
			title: 'Starlight Six',
			description:
				'Six Technology가 만든 깔끔하고 현대적인 Astro.js Starlight 테마',
			href: 'https://six-tech.github.io/Six.StarlightTheme/',
			previews: { light: 'six-light.png', dark: 'six-dark.png' },
		},
		{
			title: 'Starlight Vintage',
			description:
				'기존 Astro 문서의 시대를 초월한 디자인에서 큰 영감을 받은 Starlight 테마',
			href: 'https://starlight-theme-vintage.netlify.app/',
			previews: { light: 'vintage-light.png', dark: 'vintage-dark.png' },
		},
	]}
/>

:::tip[여러분의 테마를 추가하세요!]
Starlight 테마를 만드셨나요?
이 페이지에 테마를 추가하는 [PR을 여세요](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md#themes)!
:::


================================================
FILE: docs/src/content/docs/manual-setup.mdx
================================================
---
title: Manual Setup
description: Learn how to configure Starlight manually to add it to an existing Astro project.
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

The quickest way to create a new Starlight site is using `create astro` as shown in the [Getting Started guide](/getting-started/#create-a-new-project).
If you want to add Starlight to an existing Astro project, this guide will explain how.

## Set up Starlight

To follow this guide, you’ll need an existing Astro project.

### Add the Starlight integration

Starlight is an [Astro integration](https://docs.astro.build/en/guides/integrations-guide/). Add it to your site by running the `astro add` command in your project’s root directory:

<Tabs syncKey="pkg">
    <TabItem label="npm">
        ```sh
        npx astro add starlight
        ```

    </TabItem>
    <TabItem label="pnpm">
        ```sh
        pnpm astro add starlight
        ```
    </TabItem>
    <TabItem label="Yarn">
        ```sh
        yarn astro add starlight
        ```
    </TabItem>

</Tabs>

This will install the required dependencies and add Starlight to the `integrations` array in your Astro config file.

### Configure the integration

The Starlight integration is configured in your `astro.config.mjs` file.

Add a `title` to get started:

```js ins={8}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'My delightful docs site',
		}),
	],
});
```

Find all available options in the [Starlight configuration reference](/reference/configuration/).

### Configure content collections

Starlight is built on top of Astro’s [content collections](https://docs.astro.build/en/guides/content-collections/), which are configured in the `src/content.config.ts` file.

Create or update the content config file, adding a `docs` collection that uses Starlight’s [`docsLoader`](/reference/configuration/#docsloader) and [`docsSchema`](/reference/configuration/#docsschema):

```js ins={3-4,7}
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
};
```

Starlight also supports the [`legacy.collectionsBackwardsCompat` flag](https://docs.astro.build/en/reference/legacy-flags/#collectionsbackwardscompat) which preserves some legacy v4 content collections features.
This is useful if you have an existing Astro project and are unable to make any changes to collections at this time to migrate to the Content Layer API introduced in v5.0.

### Add content

Starlight is now configured and it’s time to add some content!

Create a `src/content/docs/` directory and start by adding an `index.md` file.
This will be the homepage of your new site:

```md
---
# src/content/docs/index.md
title: My docs
description: Learn more about my project in this docs site built with Starlight.
---

Welcome to my project!
```

Starlight uses file-based routing, which means every Markdown, MDX, or Markdoc file in `src/content/docs/` will turn into a page on your site. Frontmatter metadata (the `title` and `description` fields in the example above) can change how each page is displayed.
See all the available options in the [frontmatter reference](/reference/frontmatter/).

## Tips for existing sites

If you have an existing Astro project, you can use Starlight to quickly add a documentation section to your site.

### Use Starlight at a subpath

To add all Starlight pages at a subpath, place all your docs content inside a subdirectory of `src/content/docs/`.

For example, if Starlight pages should all start with `/guides/`, add your content in the `src/content/docs/guides/` directory:

import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src/
  - content/
    - docs/
      - **guides/**
        - guide.md
        - index.md
  - pages/
- astro.config.mjs

</FileTree>

In the future, we plan to support this use case better to avoid the need for the extra nested directory in `src/content/docs/`.

### Use Starlight with SSR

To enable SSR, follow the [“On-demand Rendering Adapters”](https://docs.astro.build/en/guides/on-demand-rendering/) guide in Astro’s docs to add a server adapter to your Starlight project.

Documentation pages generated by Starlight are pre-rendered by default regardless of your project's output mode. To opt out of pre-rendering your Starlight pages, set the [`prerender` config option](/reference/configuration/#prerender) to `false`.

If you are using the [Cloudflare adapter](https://docs.astro.build/en/guides/integrations-guide/cloudflare/) to enable server-rendering in your documentation project, make sure to also [add the `nodejs_compat` compatibility flag to your Wrangler configuration file](https://developers.cloudflare.com/workers/runtime-apis/nodejs/#get-started).


================================================
FILE: docs/src/content/docs/pt-br/404.md
================================================
---
title: Não encontrado
template: splash
editUrl: false
lastUpdated: false
hero:
  title: '404'
  tagline: <strong>Houston, temos um problema.</strong> Não conseguimos encontrar essa página.<br>Verifique a URL ou tente utilizar a barra de pesquisa.
  actions:
    - text: Ir para o início
      icon: right-arrow
      link: /pt-br/
      variant: primary
---


================================================
FILE: docs/src/content/docs/pt-br/environmental-impact.md
================================================
---
title: Documentação amigável ao meio ambiente
description: Aprenda como Starlight pode te ajudar a construir sites de documentação mais verdes e reduzir sua pegada de carbono.
---

Estimativas para o impacto climático da indústria web variam entre [2%][sf] e [4% da emissão global de carbono][bbc], aproximadamente equivalente as emissões da indústria aeronáutica.
Há vários fatores complexos no cálculo do impacto ecológico de um website, mas este guia inclui algumas dicas para reduzir a pegada ambiental do seu site de documentação.

A boa noticía é, escolher Starlight é um bom começo.
De acordo com o "Website Carbon Calculator", este site é [mais limpo que 99% das páginas web testadas][sl-carbon], produzindo 0.01g de CO₂ por visita da página.

## Peso da página

Quanto mais dados uma página web transfere, mais recursos energéticos são necessários.
Em Abril de 2023, uma página web mediana necessitava que o usuário baixasse mais que 2,000 KB de acordo com [dados do HTTP Archive][http].

Starlight constrói páginas que são o mais leve possível.
Por exemplo, em uma primeira visita, um usuário vai baixar menos do que 50 KB de dados comprimidos — apenas 2.5% da mediana do HTTP Archive.
Com uma boa estratégia de cacheamento, navegações subsequentes podem baixar tão pouco quanto 10 KB.

### Imagens

Enquanto Starlight providencia uma boa base, imagens que você adiciona a sua documentação podem rapidamente aumentar o peso da sua página.
Starlight usa o [suporte a assets otimizados][assets] do Astro para otimizar imagens locais em seus arquivos Markdown e MDX.

### Componentes de UI

Componentes construídos com frameworks de UI como React ou Vue podem facilmente adicionar grandes quantidades de JavaScript a uma página.
Pelo Starlight ser construído com Astro, componentes assim carregam **zero JavaScript no lado do cliente por padrão** graças a [Ilhas Astro][islands].

### Cacheamento

Cacheamento é usado para controlar por quanto tempo um navegador armazena e reutiliza dados já baixados.
Uma boa estratégia de cacheamento garante que um usuário receba conteúdo novo o mais cedo possível quando ele muda, mas também evita baixar inutilmente o mesmo conteúdo de novo e de novo enquanto ele não mudou.

A forma mais comum de configurar cacheamento é com o [header HTTP `Cache-Control`][cache].
Enquanto utiliza Starlight, você pode definir um grande tempo de cache para tudo no diretório `/_astro/`.
Esse diretório contém CSS, JavaScript e outros assets em bundle que podem ser seguramente cacheados para sempre, reduzindo downloads desnecessários:

```
Cache-Control: public, max-age=604800, immutable
```

Como configurar cacheamento depende da sua hospedagem web. Por exemplo, a Vercel aplica essa estratégia de cacheamento para você sem nenhuma configuração necessária, enquanto você pode definir [cabeçalhos customizados para Netlify][ntl-headers] ao adicionar um arquivo `public/_headers` ao seu projeto:

```
/_astro/*
  Cache-Control: public
  Cache-Control: max-age=604800
  Cache-Control: immutable
```

[cache]: https://csswizardry.com/2019/03/cache-control-for-civilians/
[ntl-headers]: https://docs.netlify.com/routing/headers/

## Consumo de energia

A forma com que uma página web é construída pode impactar a energia necessária para executá-la no dispositivo de um usuário.
Por utilizar JavaScript ao mínimo, Starlight reduz a quantidade de poder de processamento que o celular, tablet ou computador de um usuário precisa para carregar e renderizar páginas.

Seja cuidadoso ao adicionar funcionalidades como scripts de rastreamento de analytics ou conteúdo cheio de JavaScript como embeds de vídeo já que estes podem aumentar o consumo de energia da página.
Se você precisa de analytics, considere escolher uma opção leve como [Cabin][cabin], [Fathom][fathom] ou [Plausible][plausible].
Embeds como vídeos do YouTube e Vimeo podem ser melhorados por esperar para [carregar o vídeo conforme interação do usuário][lazy-video].
Pacotes como [`astro-embed`][embed] podem ajudar com serviços comuns.

:::tip[Você sabia?]
Fazer parse e compilação de JavaScript é uma das tarefas mais caras que navegadores tem que fazer.
Comparado a renderizar uma imagem JPEG de mesmo tamanho, [JavaScript pode levar mais do que 30 vezes mais tempo para processar][cost-of-js].
:::

[cabin]: https://withcabin.com/
[fathom]: https://usefathom.com/
[plausible]: https://plausible.io/
[lazy-video]: https://web.dev/iframe-lazy-loading/
[embed]: https://www.npmjs.com/package/astro-embed
[cost-of-js]: https://medium.com/dev-channel/the-cost-of-javascript-84009f51e99e

## Hospedagem

O lugar onde uma página web é hospedada podem ter um grande impacto no quão amigável ao ambiente seu site de documentação é.
Centro de dados e fazendas de servidores podem ter um grande impacto ecológico, incluindo alto consumo de eletricidade e uso intensivo de água.

Escolher uma hospedagem que utiliza energia renovável significará menos emissões de carbono para o seu site. A [Green Web Directory][gwb] é uma ferramenta que pode ajudá-lo a encontrar empresas de hospedagem.

[gwb]: https://www.thegreenwebfoundation.org/directory/

## Comparações

Curioso para saber como outros frameworks de documentação se comparam?
Esses testes com o [Website Carbon Calculator][wcc] comparam páginas similares construídas com diferentes ferramentas.

| Framework                   | CO₂ por visita da página |
| --------------------------- | ------------------------ |
| [Starlight][sl-carbon]      | 0.01g                    |
| [VitePress][vp-carbon]      | 0.05g                    |
| [Docus][dc-carbon]          | 0.05g                    |
| [Sphinx][sx-carbon]         | 0.07g                    |
| [MkDocs][mk-carbon]         | 0.10g                    |
| [Nextra][nx-carbon]         | 0.11g                    |
| [docsify][dy-carbon]        | 0.11g                    |
| [Docusaurus][ds-carbon]     | 0.24g                    |
| [Read the Docs][rtd-carbon] | 0.24g                    |
| [GitBook][gb-carbon]        | 0.71g                    |

<small>Dados coletados em 14 de Maio de 2023. Clique num dos links para ver valores atualizados.</small>

[sl-carbon]: https://www.websitecarbon.com/website/starlight-astro-build-getting-started/
[vp-carbon]: https://www.websitecarbon.com/website/vitepress-dev-guide-what-is-vitepress/
[dc-carbon]: https://www.websitecarbon.com/website/docus-dev-introduction-getting-started/
[sx-carbon]: https://www.websitecarbon.com/website/sphinx-doc-org-en-master-usage-quickstart-html/
[mk-carbon]: https://www.websitecarbon.com/website/mkdocs-org-getting-started/
[nx-carbon]: https://www.websitecarbon.com/website/nextra-site-docs-docs-theme-start/
[dy-carbon]: https://www.websitecarbon.com/website/docsify-js-org/
[ds-carbon]: https://www.websitecarbon.com/website/docusaurus-io-docs/
[rtd-carbon]: https://www.websitecarbon.com/website/docs-readthedocs-io-en-stable-index-html/
[gb-carbon]: https://www.websitecarbon.com/website/docs-gitbook-com/

## Mais recursos

### Ferramentas

- [Website Carbon Calculator][wcc]
- [GreenFrame](https://greenframe.io/)
- [Ecograder](https://ecograder.com/)
- [WebPageTest Carbon Control](https://www.webpagetest.org/carbon-control/)
- [Ecoping](https://ecoping.earth/)

### Artigos e palestras

- [“Building a greener web”](https://youtu.be/EfPoOt7T5lg), palestra por Michelle Barker
- [“Sustainable Web Development Strategies Within An Organization”](https://www.smashingmagazine.com/2022/10/sustainable-web-development-strategies-organization/), artigo por Michelle Barker
- [“A sustainable web for everyone”](https://2021.stateofthebrowser.com/speakers/tom-greenwood/), palestra por Tom Greenwood
- [“How Web Content Can Affect Power Usage”](https://webkit.org/blog/8970/how-web-content-can-affect-power-usage/), artigo por Benjamin Poulain e Simon Fraser

[sf]: https://www.sciencefocus.com/science/what-is-the-carbon-footprint-of-the-internet/
[bbc]: https://www.bbc.com/future/article/20200305-why-your-internet-habits-are-not-as-clean-as-you-think
[http]: https://httparchive.org/reports/state-of-the-web
[assets]: https://docs.astro.build/pt-br/guides/assets/
[islands]: https://docs.astro.build/pt-br/concepts/islands/
[wcc]: https://www.websitecarbon.com/


================================================
FILE: docs/src/content/docs/pt-br/getting-started.mdx
================================================
---
title: Introdução
description: Aprenda como começar a construir seu próximo site de documentação com Starlight pelo Astro.
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

Starlight é um tema de documentação cheio de funcionalidades construído em cima do framework [Astro](https://astro.build).
Esse guia o ajudará a iniciar um novo projeto.
Consulte as [instruções de instalação manual](/pt-br/manual-setup/) para adicionar Starlight a um projeto Astro existente.

## Início Rápido

### Crie um novo projeto

Crie um novo projeto Astro + Starlight executando o seguinte comando em seu terminal:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight
```

</TabItem>
</Tabs>

Isso irá criar um novo [diretório de projeto](/pt-br/guides/project-structure/) com todos os arquivos e configurações necessárias para o seu site.

:::tip[Veja-o em ação]
Experimente Starlight no seu navegador:
[abrir o template no StackBlitz](https://stackblitz.com/github/withastro/starlight/tree/main/examples/basics).
:::

### Inicie o servidor de desenvolvimento

Quando estiver trabalhando localmente, o [servidor de desenvolvimento do Astro](https://docs.astro.build/pt-br/reference/cli-reference/#astro-dev) permite visualizar seu trabalho e atualizar automaticamente seu navegador ao fazer alterações.

Dentro do diretório do seu projeto, execute o seguinte comando para iniciar o servidor de desenvolvimento:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm run dev
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dev
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dev
```

</TabItem>
</Tabs>

Será exibida uma mensagem em seu terminal com a URL para visualização local.
Abra esta URL para começar a navegar no seu site.

### Crie conteúdo

Starlight está pronto para você adicionar novo conteúdo, ou trazer seus arquivos existentes!

Adicione novas páginas ao seu site criando arquivos Markdown na pasta `src/content/docs/`.

Leia mais sobre roteamento baseado em arquivos e suporte para arquivos MDX e Markdoc no guia de [“Páginas”](/pt-br/guides/pages/).

### Próximos passos

- **Configurar:** Descubra opções comuns em ["Customizando Starlight"](/pt-br/guides/customization/).
- **Navegar:** Configure a barra lateral com o guia [“Barra lateral de navegação”](/pt-br/guides/sidebar/).
- **Componentes:** Conheça os cartões, abas e outros componentes integrados no guia [“Componentes”](/pt-br/components/using-components/).
- **Deploy:** Publique seu projeto com o guia [“Deploy do seu site Astro”](https://docs.astro.build/pt-br/guides/deploy/) na documentação do Astro.

## Atualizando Starlight

:::tip
Como o Starlight é um software em beta, haverá frequentes atualizações e melhorias.
Certifique-se de atualizar Starlight constantemente!
:::

Starlight é uma integração Astro. Você pode atualiza-lo e outros pacotes Astro com o seguinte comando em seu terminal:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npx @astrojs/upgrade
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dlx @astrojs/upgrade
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dlx @astrojs/upgrade
```

</TabItem>
</Tabs>

Consulte o [histórico de mudanças do Starlight](https://github.com/withastro/starlight/blob/main/packages/starlight/CHANGELOG.md) para ver a lista completa das alterações feitas em cada versão.

## Solucionando Problemas no Starlight

Use as páginas de referência [configuração do projeto](/pt-br/reference/configuration/) e [configuração do frontmatter para cada página](/pt-br/reference/frontmatter/) para garantir que seu site Starlight esteja configurado e funcionando corretamente.
Confira os guias na barra lateral para ajudá-lo a adicionar conteúdo e personalizar seu site Starlight.

Se a sua resposta não pôde ser encontrada nessa documentação, por favor visite a [documentação do Astro](https://docs.astro.build/pt-br/) para uma documentação mais completa sobre o Astro.
Sua pergunta pode ser respondida ao entender como o Astro funciona no geral, por debaixo do tema Starlight.

Você também pode checar por quaisquer [problemas conhecidos do Starlight no GitHub](https://github.com/withastro/starlight/issues), e conseguir ajuda no [Discord do Astro](https://astro.build/chat/) da nossa ativa e amigável comunidade! Envie perguntas em nosso fórum `#support` com a tag "starlight", ou visite nosso canal dedicado `#starlight` para discutir o desenvolvimento atual e mais!


================================================
FILE: docs/src/content/docs/pt-br/index.mdx
================================================
---
title: Starlight 🌟 Construa sites de documentação com Astro
head:
  - tag: title
    content: Starlight 🌟 Construa sites de documentação com Astro
description: Starlight te ajuda a construir belos e performáticos websites de documentação com Astro.
template: splash
editUrl: false
lastUpdated: false
hero:
  title: Faça sua documentação brilhar com Starlight
  tagline: Tudo o que você precisa para construir um site de documentação brilhante. Rápido, acessível e fácil de usar.
  image:
    file: ~/assets/hero-star.webp
  actions:
    - text: Começar
      icon: right-arrow
      link: /pt-br/getting-started/
    - text: Veja no GitHub
      icon: external
      variant: minimal
      link: https://github.com/withastro/starlight
---

import { CardGrid, Card } from '@astrojs/starlight/components';
import AboutAstro from '~/components/about-astro.astro';

<CardGrid stagger>
	<Card title="Documentação de iluminar os olhos" icon="open-book">
		Inclui: Navegação do site, pesquisa, internacionalização, SEO, tipografia
		fácil de ler, highlighting de código, modo escuro e mais.
	</Card>
	<Card title="Possibilitado por Astro" icon="rocket">
		Aproveite todo o poder e performance do Astro. Estenda Starlight com suas
		integrações e bibliotecas favoritas do Astro.
	</Card>
	<Card title="Markdown, Markdoc e MDX" icon="document">
		Traga a sua linguagem de marcação favorita. Starlight te dá validação de
		frontmatter com segurança de tipos do TypeScript integrada.
	</Card>
	<Card title="Traga seus componentes de UI" icon="puzzle">
		Starlight é uma solução completa de documentação agnóstica a frameworks.
		Estenda-o com React, Vue, Svelte, Solid e mais.
	</Card>
</CardGrid>

<AboutAstro title="Trazido a você por">
Astro é o framework web tudo-em-um projetado para velocidade.
Traga seu conteúdo de qualquer lugar e faça deploy em todo lugar, tudo fornecido pelos seus componentes de UI e bibliotecas favoritas.

[Aprenda sobre Astro](https://astro.build/)

</AboutAstro>


================================================
FILE: docs/src/content/docs/pt-br/resources/community-content.mdx
================================================
---
title: Conteúdo da Comunidade
description: Descubra guias produzidos pela comunidade, artigos e vídeos para ajudar a aprender e construir com Starlight!
---

:::tip[Adicione o seu!]
Você já produziu conteúdo sobre Starlight?
Abra um PR adicionando um link para esta página!
:::

import { CardGrid, LinkCard } from '@astrojs/starlight/components';

## Artigos e Avaliações

Aqui há uma coletânea de posts e artigos para aprender mais sobre Starlight e sobre a experiência de outras pessoas:

<CardGrid>
	<LinkCard
		href="https://devm.io/open-source/starlight-astro"
		title="Geração de Site Estático com Starlight"
		description="Nenhuma ideia é tão grande ou pequena ao projetar componentes” — uma entrevista com Chris Swithinbank, Líder Starlight"
	/>
	<LinkCard
		href="https://frontendatscale.com/blog/hybrid-frontend-architecture/"
		title="Arquitetura Frontend Híbrida com Astro e Starlight"
		description="Maxi Ferreira e Ben Holmes constroem um site de documentação com Starlight, TinaCMS, e um Playground de API interativo com autenticação."
	/>
	<LinkCard
		href="https://www.olets.dev/posts/comparing-docs-site-builders-vuepress-vs-starlight/"
		title="Comparando construtores de site de documentação: VuePress vs Starlight"
		description="Como esses dois frameworks se correspondem?"
	/>
</CardGrid>

## Receitas e Guias

Receitas são tipicamente guias passo a passo, curtos e focados, que levam o leitor a completar um exemplo funcional de uma tarefa específica. Receitas são uma ótima maneira de adicionar novas funcionalidades ou comportamentos para seu projeto Starlight ao seguir receitas passo a passo! Outros guias podem explicar conceitos relacionados a determinada área de conteúdo, como usar imagens ou trabalhar com MDX.

Explore conteúdo produzido pela comunidade mantido por usuários Starlight:

<CardGrid>
	<LinkCard
		href="https://www.webpro.nl/scraps/versioned-docs-with-starlight-and-vercel"
		title="Documentação versionada com Starlight e Vercel"
		description="Um guia para implementar versões separadas da documentação para cada versão principal de um projeto"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-heading-links"
		title="Adicione links em cabeçalhos Starlight"
		description="Um guia sobre como usar um plugin rehype para criar links para seções específicas de sua documentação"
	/>
	<LinkCard
		href="https://blog.otterlord.dev/posts/starlight-sponsors/"
		title="Adicione patrocinadores para seu site Starlight"
		description="Um guia sobre implementar um componente de patrocinadores personalizado na barra lateral de sua documentação"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-og-images"
		title="Adicione imagens Open Graph a Starlight"
		description="Um guia para gerar imagens sociais e as metatags correspondentes para as suas páginas"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-third-party-icon-sets"
		title="Use ícones de terceiros em Starlight"
		description="Um guia sobre como usar unplugin-icons para expandir a seleção de ícones disponíveis para Starlight"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-custom-html-head"
		title="Edite o elemento HTML head de páginas Starlight"
		description="Aprenda sobre como adicionar conteúdo como fontes, scripts e web analytics"
	/>
	<LinkCard
		href="https://dev.to/mrrobot/publishing-documentation-with-astro-starlight-691"
		title="Publicando documentação com Astro Starlight"
		description="Começando com a documentação Starlight"
	/>
	<LinkCard
		href="https://events-3bg.pages.dev/jotter/starlight/guide/"
		title="Habilite Transições de Visualização"
		description="Tenha aquela aparência e experiência de uma SPA com o suporte a transições de visualização da Mochila de Truques"
	/>
</CardGrid>

## Conteúdo em Vídeo

Descubra vídeos e canais com conteúdo Starlight, incluindo _lives_ e conteúdo educacional.

import YouTubeGrid from '~/components/youtube-grid.astro';

### Astro Videos

<YouTubeGrid
	videos={[
		{
			href: 'https://www.youtube.com/watch?v=5u0Ds7wzUeI',
			title: 'Starlight por Astro',
			description: 'Assista ao vídeo oficial do lançamento Starlight',
		},
		{
			href: 'https://www.youtube.com/shorts/zjOWezSzd18',
			title: '🌟 SUB 1 MINUTE RUN',
			description:
				'Assista Ben lançar um novo site Starlight em menos de um minuto!',
		},
	]}
/>

### Vídeos da Comunidade e Streams

<YouTubeGrid
	videos={[
		{
			href: 'https://www.youtube.com/watch?v=sF6UcV3moZg',
			title: 'Construindo documentação com Starlight e Astro',
			description:
				'Assista Chris e Alex mergulhando no código do Starlight com CodingCat.dev',
		},
		{
			href: 'https://www.youtube.com/watch?v=sWkkHbwDeQc',
			title: 'Astro Starlight',
			description: 'Introdução ao Starlight em menos de um minuto.',
		},
		{
			href: 'https://www.youtube.com/watch?v=-Ki-1E5gNCk',
			title:
				'Modelo de Documentação Astro Starlight (construa documentações personalizadas!)',
			description:
				'Tenha um novo site Starlight em funcionamento em cerca de 5 minutos',
		},
	]}
/>


================================================
FILE: docs/src/content/docs/pt-br/resources/plugins.mdx
================================================
---
title: Plugins e Integrações
description: Descubra ferramentas da comunidade e integrações que estendem Starlight!
sidebar:
  order: 1
---

:::tip[Adicione o seu!]
Você construiu um plugin ou uma ferramenta para Starlight?
Abra um PR adicionando um link para esta página!
:::

## Plugins

[Plugins](/pt-br/reference/plugins/) podem personalizar a configuração Starlight, a interface do usuário e o comportamento, enquanto também são fáceis de compartilhar e de reutilizar.
Estenda o seu site com os plugins oficiais suportados pelo time Starlight e plugins da comunidade mantidos por usuários Starlight.

### Plugins oficiais

<CardGrid>
	<LinkCard
		href="/pt-br/guides/site-search/#algolia-docsearch"
		title="Algolia DocSearch"
		description="Substitua Pagefind, o provedor de busca padrão, com Algolia DocSearch."
	/>
</CardGrid>

### Plugins da comunidade

<CardGrid>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-links-validator"
		title="starlight-links-validator"
		description="Verifique links quebrados em suas páginas Starlight."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-typedoc"
		title="starlight-typedoc"
		description="Gere páginas Starlight a partir de TypeScript utilizando TypeDoc."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-blog"
		title="starlight-blog"
		description="Adicione um blog ao seu site de documentação."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-openapi"
		title="starlight-openapi"
		description="Crie páginas de documentação a partir de especificações OpenAPI/Swagger."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-obsidian"
		title="starlight-obsidian"
		description="Publique vaults Obsidian em seu site Starlight."
	/>
	<LinkCard
		href="https://astro-ghostcms.xyz/intro/starlight/install/"
		title="starlight-ghostcms"
		description="Adicione suas postagens do blog GhostCMS ao lado de suas páginas Starlight."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-image-zoom"
		title="starlight-image-zoom"
		description="Adicione recursos de zoom as imagens da sua documentação."
	/>
	<LinkCard
		href="https://github.com/lorenzolewis/starlight-utils"
		title="starlight-utils"
		description="Estenda Starlight com uma coleção de utilitários comuns."
	/>
	<LinkCard
		href="https://github.com/trueberryless/starlight-view-modes"
		title="starlight-view-modes"
		description="Adicione diferentes recursos de modo de exibição ao seu site de documentação."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-versions"
		title="starlight-versions"
		description="Versione suas páginas de documentação Starlight."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-theme-rapide"
		title="starlight-theme-rapide"
		description="Tema Starlight inspirado pelo tema Visual Studio Code Vitesse."
	/>
</CardGrid>

## Ferramentas da comunidade e integrações

import { CardGrid, LinkCard } from '@astrojs/starlight/components';

Essas ferramentas da comunidade e integrações podem ser usadas para adicionar funcionalidades para o seu site Starlight.

<CardGrid>
	<LinkCard
		href="https://www.feelback.dev/blog/new-astro-starlight-integration/"
		title="FeelBack"
		description="Adicione um sistema de feedback de usuário para as páginas da sua documentação."
	/>
	<LinkCard
		href="https://github.com/val-town/notion-to-astro"
		title="notion-to-astro"
		description="Converta exportações do Notion para documentação Asto Starlight"
	/>
	<LinkCard
		href="https://github.com/mattjennings/astro-live-code"
		title="astro-live-code"
		description="Apresente seus blocos de código MDX como componentes interativos"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-i18n"
		title="starlight-i18n"
		description="Extensão para Visual Studio Code para ajudar a traduzir páginas Starlight."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-package-managers"
		title="starlight-package-managers"
		description="Exiba rapidamente comandos relacionados ao npm para vários gerenciadores de pacotes."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-showcases"
		title="starlight-showcases"
		description="Conjunto de componentes Starlight para criar páginas de exibição."
	/>
</CardGrid>


================================================
FILE: docs/src/content/docs/pt-br/resources/showcase.mdx
================================================
---
title: Vitrine Starlight
description: Descubra sites construídos com Starlight!
sidebar:
  label: Vitrine de Sites
---

:::tip[Adicione o seu!]
Você construiu um site com Starlight?
[Abra um PR](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md#showcase) adicionando um link para esta página!
:::

## Sites

import ShowcaseSites from '~/components/showcase-sites.astro';

Starlight já está sendo usado em produção. Esses são alguns sites que estão pela web:

<ShowcaseSites />

Veja todos os [repositórios de projetos públicos usando Starlight no GitHub](https://github.com/withastro/starlight/network/dependents).


================================================
FILE: docs/src/content/docs/pt-pt/404.md
================================================
---
title: Não encontrado
template: splash
editUrl: false
lastUpdated: false
hero:
  title: '404'
  tagline: <strong>Houston, temos um problema.</strong> Não conseguimos encontrar esta página.<br>Verifique se o URL está correto ou tente utilizar a barra de pesquisa.
  actions:
    - text: Ir para o início
      icon: right-arrow
      link: /pt-pt/
      variant: primary
---


================================================
FILE: docs/src/content/docs/pt-pt/environmental-impact.md
================================================
---
title: Documentação ecológica
description: Aprenda como o Starlight te pode ajudar a construir sites de documentação mais ecológicos e reduzir a pegada de carbono.
---

As estimativas para o impacto climático da indústria web variam entre [2%][sf] e [4% das emissões globais de carbono][bbc], aproximadamente o equivalente às emissões da indústria aeronáutica.
Há vários fatores complexos no cálculo do impacto ecológico de um website, mas este guia inclui algumas dicas para reduzir a pegada ambiental do seu site de documentação.

A boa noticía é que, escolher o Starlight já é um bom começo!
De acordo com o "Website Carbon Calculator", este site é [mais limpo do que 99% das páginas web testadas][sl-carbon], produzindo 0.01g de CO₂ por cada visita à página.

## Peso da página

Quanto mais dados uma página web transfere mais recursos energéticos são necessários.
De acordo com [dados do HTTP Archive][http], em Abril de 2023, uma página web mediana necessitava que o utilizador baixasse mais de 2,000 KB.

O Starlight constrói páginas que são o mais leve possível.
Por exemplo, na primeira visita, um utilizador vai descarregar menos do que 50 KB de dados comprimidos, ou seja, apenas 2.5% da mediana indicada pelo HTTP Archive.
Com uma boa estratégia de _cache_, as navegações subsequentes podem descarregar tão pouco quanto 10 KB.

### Imagens

Enquanto o Starlight providencia uma boa base, as imagens que você adicionar à sua documentação podem aumentar o peso da sua página rapidamente.
O Starlight usa o [suporte a assets otimizados][assets] do Astro para otimizar imagens locais nos seus arquivos Markdown e MDX.

### Componentes de UI

Os componentes construídos com frameworks de UI como React ou Vue podem facilmente adicionar grandes quantidades de JavaScript a uma página.
Porque o Starlight é construído com o Astro, e graças às [Ilhas Astro][islands], esses componentes carregam, **por padrão, zero código JavaScript no lado do cliente**.

### _Cache_

A _Cache_ é usada para controlar por quanto tempo um navegador armazena e reutiliza os dados já descarregados.
Uma boa estratégia de _caching_ garante que um utilizador receba o conteúdo novo o mais cedo possível assim que ele muda, mas também evita descarregar inutil e repetidamente o mesmo conteúdo sem que ele mude.

A forma mais comum de configurar a _cache_ é com o [header HTTP `Cache-Control`][cache].
Ao utilizar o Starlight, você pode definir um grande tempo de cache para todo o conteúdo do diretório `/_astro/`.
Este diretório contém CSS, JavaScript e outros artefactos em _bundle_ que podem ser seguramente _cached_ para sempre, reduzindo assim downloads desnecessários:

```
Cache-Control: public, max-age=604800, immutable
```

A forma de configurar a _cache_ depende do seu alojamento web. Por exemplo, o Vercel aplica por você esta estratégia de _cache_ sem necessidade de configuração adicional, já a definição de [cabeçalhos customizados para Netlify][ntl-headers] necessita que adicione um arquivo `public/_headers` ao seu projeto:

```
/_astro/*
  Cache-Control: public
  Cache-Control: max-age=604800
  Cache-Control: immutable
```

[cache]: https://csswizardry.com/2019/03/cache-control-for-civilians/
[ntl-headers]: https://docs.netlify.com/routing/headers/

## Consumo de energia

A forma com que uma página web é construída pode ter impacto na energia necessária para executá-la no dispositivo de um utilizador.
Por utilizar JavaScript ao mínimo, o Starlight reduz a quantidade de energia de processamento que o celular, tablet ou computador de um utilizador precisa para carregar e renderizar páginas.

Tenha atenção ao adicionar funcionalidades como scripts de rastreamento de _Analytics_ ou conteúdo cheio de JavaScript como embeds de vídeo já que estes podem aumentar o consumo de energia da página.
Se você precisa de _Analytics_, considere escolher uma opção leve como [Cabin][cabin], [Fathom][fathom] ou [Plausible][plausible].
Embeds como vídeos do YouTube e Vimeo podem ser melhorados se [carregar o vídeo mediante a interação do usuário][lazy-video].
Pacotes como o [`astro-embed`][embed] podem ajudá-lo com alguns dos serviços comuns.

:::tip[Sabia que?]
Fazer parse e compilação de JavaScript é uma das tarefas mais caras que os navegadores tem que fazer.
Comparado com a renderização de uma imagem JPEG de mesmo tamanho, [o JavaScript pode levar mais do que 30 vezes o tempo para processar][cost-of-js].
:::

[cabin]: https://withcabin.com/
[fathom]: https://usefathom.com/
[plausible]: https://plausible.io/
[lazy-video]: https://web.dev/iframe-lazy-loading/
[embed]: https://www.npmjs.com/package/astro-embed
[cost-of-js]: https://medium.com/dev-channel/the-cost-of-javascript-84009f51e99e

## Alojamento

O lugar onde uma página web é alojada pode ter um grande impacto no quão amigável ao ambiente o seu site de documentação é.
Os centros de dados e de servidores podem ter um grande impacto ecológico, incluindo alto consumo de eletricidade e uso intensivo de água.

Escolher um alojamento que utiliza energia renovável significará menos emissões de carbono para o seu site. A [Green Web Directory][gwb] é uma ferramenta que poderá ajudá-lo a encontrar empresas de alojamento.

[gwb]: https://www.thegreenwebfoundation.org/directory/

## Comparações

Está curioso para comparar com os outros frameworks de documentação?
Estes testes realizados com o [Website Carbon Calculator][wcc] comparam páginas semelhantes construídas com diferentes ferramentas.

| Framework                   | CO₂ per page visit | Rating |
| --------------------------- | ------------------ | :----: |
| [Starlight][sl-carbon]      | 0.01g              |   A+   |
| [Read the Docs][rtd-carbon] | 0.05g              |   A+   |
| [Sphinx][sx-carbon]         | 0.06g              |   A+   |
| [VitePress][vp-carbon]      | 0.07g              |   A+   |
| [Docus][dc-carbon]          | 0.09g              |   A+   |
| [docsify][dy-carbon]        | 0.10g              |   A    |
| [Nextra][nx-carbon]         | 0.11g              |   A    |
| [MkDocs][mk-carbon]         | 0.19g              |   B    |
| [Docusaurus][ds-carbon]     | 0.21g              |   B    |
| [GitBook][gb-carbon]        | 0.43g              |   C    |
| [Mintlify][mt-carbon]       | 1.22g              |   F    |

<small>Dados recolhidos a 22 de Julho de 2024. Clique num dos links para ver os valores atualizados.</small>

[sl-carbon]: https://www.websitecarbon.com/website/starlight-astro-build-getting-started/
[vp-carbon]: https://www.websitecarbon.com/website/vitepress-dev-guide-what-is-vitepress/
[dc-carbon]: https://www.websitecarbon.com/website/docus-dev-introduction-getting-started/
[sx-carbon]: https://www.websitecarbon.com/website/sphinx-doc-org-en-master-usage-quickstart-html/
[mk-carbon]: https://www.websitecarbon.com/website/mkdocs-org-getting-started/
[nx-carbon]: https://www.websitecarbon.com/website/nextra-site-docs-docs-theme-start/
[dy-carbon]: https://www.websitecarbon.com/website/docsify-js-org/
[ds-carbon]: https://www.websitecarbon.com/website/docusaurus-io-docs/
[rtd-carbon]: https://www.websitecarbon.com/website/docs-readthedocs-io-en-stable-index-html/
[gb-carbon]: https://www.websitecarbon.com/website/docs-gitbook-com/
[mt-carbon]: https://www.websitecarbon.com/website/mintlify-com-docs-quickstart/

## Mais recursos

### Ferramentas

- [Website Carbon Calculator][wcc]
- [GreenFrame](https://greenframe.io/)
- [Ecograder](https://ecograder.com/)
- [WebPageTest Carbon Control](https://www.webpagetest.org/carbon-control/)
- [Ecoping](https://ecoping.earth/)

### Artigos e palestras

- [“Building a greener web”](https://youtu.be/EfPoOt7T5lg), palestra por Michelle Barker
- [“Sustainable Web Development Strategies Within An Organization”](https://www.smashingmagazine.com/2022/10/sustainable-web-development-strategies-organization/), artigo por Michelle Barker
- [“A sustainable web for everyone”](https://2021.stateofthebrowser.com/speakers/tom-greenwood/), palestra por Tom Greenwood
- [“How Web Content Can Affect Power Usage”](https://webkit.org/blog/8970/how-web-content-can-affect-power-usage/), artigo por Benjamin Poulain e Simon Fraser

[sf]: https://www.sciencefocus.com/science/what-is-the-carbon-footprint-of-the-internet/
[bbc]: https://www.bbc.com/future/article/20200305-why-your-internet-habits-are-not-as-clean-as-you-think
[http]: https://httparchive.org/reports/state-of-the-web
[assets]: https://docs.astro.build/en/guides/images/
[islands]: https://docs.astro.build/pt-pt/concepts/islands/
[wcc]: https://www.websitecarbon.com/


================================================
FILE: docs/src/content/docs/pt-pt/getting-started.mdx
================================================
---
title: Introdução
description: Aprenda como começar a construir o seu próximo site de documentação com Starlight pelo Astro.
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

O Starlight é um tema de documentação cheio de funcionalidades construído em cima do framework [Astro](https://astro.build).
Este guia irá ajudá-lo a começar um novo projeto.
Consulte as [instruções de instalação manual](/pt-pt/manual-setup/) para adicionar o Starlight a um projeto Astro já existente.

## Início Rápido

### Crie um novo projeto

Crie um novo projeto Astro + Starlight executando o seguinte comando no seu terminal:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight
```

</TabItem>
</Tabs>

Isto irá criar um novo [diretório de projeto](/pt-pt/guides/project-structure/) com todos os arquivos e configurações necessárias para o seu novo site.

:::tip[Veja-o em ação]
Experimente o Starlight directamente no seu navegador:
[abrir o template no StackBlitz](https://stackblitz.com/github/withastro/starlight/tree/main/examples/basics).
:::

### Inicie o servidor de desenvolvimento

Quando estiver a trabalhar localmente, o [servidor de desenvolvimento do Astro](https://docs.astro.build/pt/reference/cli-reference/#astro-dev) permitirá visualizar seu trabalho e atualizar automaticamente o seu navegador após fazer alterações.

Dentro do diretório do seu projeto, execute o seguinte comando para iniciar o servidor de desenvolvimento:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm run dev
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dev
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dev
```

</TabItem>
</Tabs>

Será exibida uma mensagem no seu terminal com o URL para a visualização local.
Abra esse URL para começar a navegar no seu site.

### Crie conteúdo

O Starlight está pronto para você adicionar novos conteúdos, ou trazer os seus arquivos existentes!

Adicione páginas ao seu site criando ficheiros _Markdown_ no directório `src/content/docs/`.

Saiba mais acerca de _routing_ baseado em ficheiros e suporte para ficheiros MDX e Markdoc no guia [“Páginas”](/pt-pt/guides/pages/).

### Próximos passos

- **Configurar:** Descubra opções comuns em ["Customização do Starlight"](/pt-pt/guides/customization/).
- **Navegar:** Configure a barra lateral com o guia [“Barra lateral de navegação”](/pt-pt/guides/sidebar/).
- **Componentes:** Conheça os cartões, separadores e outros componentes integrados no guia [“Componentes”](/pt-pt/components/using-components/).
- **Deploy:** Publique o seu projeto com a ajuda do guia [“Deploy do seu site Astro”](https://docs.astro.build/pt-br/guides/deploy/) na documentação do Astro.

## Atualizar o Starlight

:::tip
Como o Starlight é um software em beta é normal que ocorram atualizações e melhorias frequentes.
Certifique-se que atualiza o Starlight constantemente!
:::

O Starlight é uma integração do Astro. Pode atualizá-lo, como outros pacotes Astro, executando no seu terminal o seguinte comando:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npx @astrojs/upgrade
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dlx @astrojs/upgrade
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dlx @astrojs/upgrade
```

</TabItem>
</Tabs>

Consulte o [histórico de mudanças do Starlight](https://github.com/withastro/starlight/blob/main/packages/starlight/CHANGELOG.md) para ver a lista completa das alterações feitas em cada versão.

## Solucionar Problemas no Starlight

Utilize as páginas de referência [configuração do projeto](/pt-pt/reference/configuration/) e [configuração do frontmatter para cada página](/pt-pt/reference/frontmatter/) para garantir que seu site Starlight está configurado e a funcionar corretamente.
Confira os guias na barra lateral para ajudá-lo a adicionar conteúdo e a personalizar o seu site Starlight.

Se não encontrar a sua resposta nesta documentação, visite por favor a [documentação do Astro](https://docs.astro.build/pt-br/) para consultar uma documentação mais completa sobre o Astro.
A sua dúvida pode ser respondida se entender como é que o Astro funciona no geral e por debaixo do tema Starlight.

Pode ainda procurar por [problemas conhecidos do Starlight no GitHub](https://github.com/withastro/starlight/issues), e obter ajuda no [Discord do Astro](https://astro.build/chat/) com a nossa ativa e amigável comunidade! Envie perguntas no nosso fórum `#support` com a tag "starlight", ou visite o canal dedicado `#starlight` para discutir o desenvolvimento atual e mais!


================================================
FILE: docs/src/content/docs/pt-pt/index.mdx
================================================
---
title: Starlight 🌟 Construa sites de documentação com Astro
head:
  - tag: title
    content: Starlight 🌟 Construa sites de documentação com Astro
description: Starlight ajuda-te a construir websites de documentação belos e rápidos com Astro.
template: splash
editUrl: false
lastUpdated: false
banner:
  content: |
    Atualização para o Astro 5?
    <a href="https://github.com/withastro/starlight/releases/tag/%40astrojs/starlight%400.30.0">
      Aprenda como fazer
    </a>
hero:
  title: Faça a sua documentação brilhar com Starlight
  tagline: Tudo o que precisa para construir um site de documentação brilhante. Rápido, acessível e fácil de usar.
  image:
    file: ~/assets/hero-star.webp
  actions:
    - text: Começar
      icon: right-arrow
      link: /pt-pt/getting-started/
    - text: Veja no GitHub
      icon: external
      variant: minimal
      link: https://github.com/withastro/starlight
---

import { CardGrid, Card } from '@astrojs/starlight/components';
import AboutAstro from '~/components/about-astro.astro';
import TestimonialGrid from '~/components/testimonial-grid.astro';
import Testimonial from '~/components/testimonial.astro';

<CardGrid stagger>
	<Card title="Documentação de iluminar os olhos" icon="open-book">
		Inclui: Navegação do site, pesquisa, internacionalização, SEO, tipografia
		fácil de ler, _highlighting_ de código, modo escuro e mais.
	</Card>
	<Card title="Possibilitado pelo Astro" icon="rocket">
		Aproveite todo o poder e performance do Astro. Estenda o Starlight com suas
		integrações e bibliotecas favoritas do Astro.
	</Card>
	<Card title="Markdown, Markdoc e MDX" icon="document">
		Utilize a sua linguagem de marcação favorita. O Starlight inclui validação
		com _frontmatter_ e segurança integrada de tipos com TypeScript.
	</Card>
	<Card title="Traga seus componentes de UI" icon="puzzle">
		O Starlight é uma solução completa de documentação agnóstica a frameworks.
		Estenda-o com React, Vue, Svelte, Solid e outros.
	</Card>
</CardGrid>

<TestimonialGrid title="O que dizem acerca de nós">
  <Testimonial
    name="Rachel"
    handle="rachelnabors"
    cite="https://twitter.com/astrodotbuild/status/1724934718745915558"
  >
	  A equipa do Astro EVOLUIU a forma como a documentação pode ser feita e podemos ter tudo pronto a instalar com o seu o projecto Starlight.
	</Testimonial>
  <Testimonial
    name="Flavio"
    handle="flaviocopes"
    cite="https://twitter.com/flaviocopes/status/1738237658717905108"
  >
	  O _kit_ oficial de iniciação Starlight é de facto uma ferramenta incrível para construir um website de documentação
	</Testimonial>
  <Testimonial
    name="Tomek"
    handle="sulco"
    cite="https://twitter.com/sulco/status/1735610348730802342"
  >
    O Starlight é o nosso modelo exemplar de uma grande experiência de DX: a rapidez, conveniência,
		e atenção ao detalhe são inspiradoras. Ele trata da tecnologia e do aspecto, para que se possa
		focar no seu conteúdo 👏

    	A equipa StackBlitz simplesmente adora-o!

  </Testimonial>
  <Testimonial
    name="Roberto"
    handle="RmeetsH"
    cite="https://twitter.com/RmeetsH/status/1735783992018760090"
  >
    O Startlight tem sido uma completa mudança para mim, permitindo-me focar na criação de conteúdos.

    	O seu design intituitivo não só agiliza o meu fluxo de trabalho mas também reduz o tempo de envolvimento para developers open-source.

  </Testimonial>
  <Testimonial
    name="Joel"
    handle="jhooks"
    cite="https://twitter.com/jhooks/status/1727405160547418405"
  >
		Dediquei mais algum tempo com o Starlight para a documentação do meu "Course Builder" e tem sido fantástico até agora.
		Muitos pormenores interessantes e permite-me focar em escrever com _Markdown_ em vez de perder tempo no site.
  </Testimonial>
  <Testimonial
    name="Rick"
    handle="rick_viscomi"
    cite="https://twitter.com/rick_viscomi/status/1665867447910510593"
  >
		Comecei a mexer com o Starlight. Tenho de dizer que estou bastante impressionado com a performance
		pronta-a-instalar!

    💯💯💯💯

  </Testimonial>
  <Testimonial
    name="Nicolas"
    handle="beaussan"
    cite="https://twitter.com/beaussan/status/1735625189583466893"
  >
		O Starlight é a melhor forma de começar com a documentação, entre o poder
		e a rapidez do Astro, e as ferramentas do Starlight, é uma combinação feita no céu.

    	Tem sido a minha escolha de eleição há algum tempo, e continuo a adorá-lo!

  </Testimonial>
  <Testimonial
    name="Sylwia"
    handle="SylwiaVargas"
    cite="https://x.com/SylwiaVargas/status/1726556825741578286"
  >
		Utilizei o Starlight no meu último trabalho e adorei-o! Componentes fantásticos,
		design intuitivo, e uma comunidade super responsiva (sempre que alguém precisava de algo,
		eles lançavam-no mais cedo ou mostravam uma alternativa). Uma experiência muito agradável.
  </Testimonial>
  <Testimonial
    name="Lou Cyx"
    handle="loucyx"
    cite="https://elk.zone/m.webtoo.ls/@loucyx@mastodon.social/111587380021362284"
  >
	  A documentação do meu site mono-repositório parece melhor do que nunca graças ao Starlight. É extremamente fácil de utilizar sem perder nenhum do poder do Astro.
		Obrigado por trabalharem nele!
	</Testimonial>
  <Testimonial
    name="BowTiedWebReaper"
    handle="BowTiedWebReapr"
    cite="https://twitter.com/BowTiedWebReapr/status/1735633399501697517"
  >
    O Starlight é a minha ferramenta de seleção para documentação. Ele tornou a inclusão de documentação no meu site Astro super fácil sem necessidade
		de um sub-domínio ou de utilizar outra ferramenta.
  </Testimonial>
  <Testimonial
    name="Jeff"
    handle="J_Everhart383"
    cite="https://twitter.com/J_Everhart383/status/1691900590048292908"
  >
	  Tenho estado a reconstruir a documentação da plataforma WPEngine Atlas Platform. Confiem em mim quando digo que o Starlight tem tudo o que precisam
		para criar uma plataforma de documentação A+ 🙌
	</Testimonial>
  <Testimonial
    name="Chloe"
    handle="solelychloe"
    cite="https://twitter.com/solelychloe/status/1695115277602628082"
  >
	  Experimente o Starlight!

    Eu utilizo-o em alguns dos meus sites e é fantástico.

  </Testimonial>
</TestimonialGrid>

<AboutAstro title="Trazido por">
Astro é o framework web tudo-em-um projetado para velocidade.
Traga o seu conteúdo de qualquer lugar e faça deploy em qualquer lugar, tudo fornecido pelos seus componentes de UI e bibliotecas favoritas.

[Aprenda acerca do Astro](https://astro.build/)

</AboutAstro>


================================================
FILE: docs/src/content/docs/pt-pt/resources/community-content.mdx
================================================
---
title: Conteúdo da Comunidade
description: Descubra guias produzidos pela comunidade, artigos e vídeos para ajudar a aprender e construir com o Starlight!
---

:::tip[Inclua o seu!]
Já produziu conteúdo sobre Starlight?
Então abra um PR e adicione o seu link nesta página!
:::

import { CardGrid, LinkCard } from '@astrojs/starlight/components';

## Artigos e Avaliações

Aqui está uma coleção de posts e artigos para aprender mais sobre Starlight e sobre as experiências de outras pessoas:

<CardGrid>
	<LinkCard
		href="https://devm.io/open-source/starlight-astro"
		title="Geração de Site Estático com Starlight"
		description="'Nenhuma ideia é tão grande ou pequena ao projetar componentes' — uma entrevista com Chris Swithinbank, Líder Starlight"
	/>
	<LinkCard
		href="https://frontendatscale.com/blog/hybrid-frontend-architecture/"
		title="Arquitetura Frontend Híbrida com Astro e Starlight"
		description="Maxi Ferreira e Ben Holmes constroem um site de documentação com Starlight, TinaCMS, e um Playground de API interativo com autenticação."
	/>
	<LinkCard
		href="https://www.olets.dev/posts/comparing-docs-site-builders-vuepress-vs-starlight/"
		title="Comparando construtores de site de documentação: VuePress vs Starlight"
		description="Como estes dois frameworks se comparam?"
	/>
</CardGrid>

## Receitas e Guias

Receitas são tipicamente guias passo a passo, curtos e focados, que levam o leitor a completar um exemplo funcional de uma tarefa específica.
As receitas são também uma ótima maneira de adicionar novas funcionalidades ou comportamentos para seu projeto Starlight bastando seguir simples instruções passo a passo!
Outros guias podem explicar conceitos relacionados a determinada área de conteúdo, como por exemplo usar imagens ou trabalhar com MDX.

Explore o conteúdo produzido pela comunidade e mantido pelos utilizadores Starlight:

<CardGrid>
	<LinkCard
		href="https://www.webpro.nl/scraps/versioned-docs-with-starlight-and-vercel"
		title="Documentação versionada com Starlight e Vercel"
		description="Um guia para implementar versões separadas da documentação para cada versão principal de um projeto"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-heading-links"
		title="Adicione links em cabeçalhos Starlight"
		description="Um guia sobre como usar um plugin rehype para criar links para seções específicas da sua documentação"
	/>
	<LinkCard
		href="https://blog.otterlord.dev/posts/starlight-sponsors/"
		title="Adicione patrocinadores para seu site Starlight"
		description="Um guia sobre implementar um componente de patrocinadores personalizado na barra lateral da sua documentação"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-og-images"
		title="Adicione imagens Open Graph a Starlight"
		description="Um guia para gerar imagens sociais e as metatags correspondentes para as suas páginas"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-third-party-icon-sets"
		title="Use ícones de terceiros em Starlight"
		description="Um guia sobre como usar unplugin-icons para expandir a seleção de ícones disponíveis para Starlight"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-custom-html-head"
		title="Edite o elemento HTML head de páginas Starlight"
		description="Aprenda sobre como adicionar conteúdo como fontes, scripts e web analytics"
	/>
	<LinkCard
		href="https://dev.to/mrrobot/publishing-documentation-with-astro-starlight-691"
		title="Publicando documentação com Astro Starlight"
		description="Começando com a documentação Starlight"
	/>
	<LinkCard
		href="https://events-3bg.pages.dev/jotter/starlight/guide/"
		title="Ativar Transições de Vistas"
		description="Obtenha o aspecto de SPA com o suporte às transições de vistas do Bag of Tricks’"
	/>
	<LinkCard
		href="https://jamcomments.com/posts/structured-data-with-starlight"
		title="Acrescentar Dados Estructurados a páginas do Starlight"
		description="Aprenda a construir dados dinâmicos estructurados JSON-LD para as suas páginas de documentação."
	/>
	<LinkCard
		href="https://starlight-examples.netlify.app/"
		title="Exemplos do Starlight"
		description="Uma coleção de exemplos deStackBlitz embebidos que demonstram formas práticas de fazer coisas em sites de documentação do Starlight."
	/>
</CardGrid>

## Conteúdo de Vídeo

Descubra os vídeos e canais com conteúdo Starlight, incluíndo transmissões ao vivo e conteúdo educacional.

import YouTubeGrid from '~/components/youtube-grid.astro';

### Videos oficiais do Astro

<YouTubeGrid
	videos={[
		{
			href: 'https://www.youtube.com/watch?v=5u0Ds7wzUeI',
			title: 'Starlight por Astro',
			description: 'Veja o vídeo oficial do lançamento Starlight',
		},
		{
			href: 'https://www.youtube.com/shorts/zjOWezSzd18',
			title: '🌟 SUB 1 MINUTE RUN',
			description:
				'Veja o Ben lançar um novo site Starlight em menos de um minuto!',
		},
	]}
/>

### Vídeos e Transmissões da Comunidade

<YouTubeGrid
	videos={[
		{
			href: 'https://www.youtube.com/watch?v=sF6UcV3moZg',
			title: 'Construir documentação com o Starlight e Astro',
			description:
				"Veja o Chris e Alex mergulhar no Starlight em 'Code with CodingCat.dev'",
		},
		{
			href: 'https://www.youtube.com/watch?v=sWkkHbwDeQc',
			title: 'Astro Starlight',
			description: 'Introdução ao Starlight em menos de um minuto.',
		},
		{
			href: 'https://www.youtube.com/watch?v=-Ki-1E5gNCk',
			title:
				'Modelo de Documentação Astro Starlight (construa documentações personalizadas!)',
			description:
				'Tenha um novo site Starlight a funcionar em cerca de 5 minutos',
		},
		{
			href: 'https://www.youtube.com/watch?v=12o7WxjAxjM',
			title:
				'Inclua a documentação Starlight num projecto Next.js através de proxies',
			description:
				'Configurar o Starlight como uma sub-directoria dentro de um site Next.js',
		},
		{
			href: 'https://www.youtube.com/watch?v=5pq80drDrNs',
			title:
				"Eu recreei a documentação do Shadcn's em 30 minutoes com esta ferramenta fantástica",
			description:
				'Neste video eu abordo o que torna o Starlight tão porreiro e porque razão deve experimentá-lo no seu próximo projecto.',
		},
		{
			href: 'https://www.youtube.com/watch?v=Q1E4Gkt63ko',
			title: 'Astro Starlight and emoji-blast with Chris Swithinbank',
			description:
				"Wherein Chris, the creator of Astro's Starlight framework-on-a-framework, walks me through setting it up for a new emoji-blast website. 🌟 🎇",
		},
	]}
/>


================================================
FILE: docs/src/content/docs/pt-pt/resources/plugins.mdx
================================================
---
title: Plugins e Integrações
description: Descubra ferramentas da comunidade e integrações que estendem o Starlight!
sidebar:
  order: 1
---

:::tip[Inclua o seu!]
Já construiu um plugin ou uma ferramenta para o Starlight?
Então abra um PR e adicione o seu link nesta página!
:::

## Plugins

Os [plugins](/pt-pt/reference/plugins/) podem personalizar ou estender a configuração do Starlight, a interface do utilizador e o comportamento, sendo também fáceis de compartilhar e de reutilizar.
Estenda o seu site com os plugins oficiais suportados pela equipa Starlight e com plugins da comunidade mantidos por outros utilizadores Starlight.

### Plugins oficiais

<CardGrid>
	<LinkCard
		href="/pt-pt/guides/site-search/#algolia-docsearch"
		title="Algolia DocSearch"
		description="Substitua o fornecedor de pesquisa Pagefind pelo Algolia DocSearch."
	/>
</CardGrid>

### Plugins da comunidade

<CardGrid>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-links-validator"
		title="starlight-links-validator"
		description="Verifique links incorretos nas suas páginas do Starlight."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-typedoc"
		title="starlight-typedoc"
		description="Crie páginas Starlight a partir de TypeScript utilizando o TypeDoc."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-blog"
		title="starlight-blog"
		description="Adicione um blog ao seu site de documentação."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-openapi"
		title="starlight-openapi"
		description="Crie páginas de documentação a partir de especificações OpenAPI/Swagger."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-obsidian"
		title="starlight-obsidian"
		description="Publique cofres de Obsidian no seu site Starlight."
	/>
	<LinkCard
		href="https://astro-ghostcms.xyz/intro/starlight/install/"
		title="starlight-ghostcms"
		description="Adicione os artigos do seu blog GhostCMS ao lado das páginas Starlight."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-image-zoom"
		title="starlight-image-zoom"
		description="Adicione funções de zoom à sua documentação do Starlight."
	/>
	<LinkCard
		href="https://github.com/lorenzolewis/starlight-utils"
		title="starlight-utils"
		description="Estenda o Starlight com uma coleção de utilitários comuns."
	/>
	<LinkCard
		href="https://github.com/trueberryless/starlight-view-modes"
		title="starlight-view-modes"
		description="Adicione a capacidade de mostrar diferentes formas de visualização no seu website de documentação."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-versions"
		title="starlight-versions"
		description="Acrescente a versão às páginas da sua documentação Starlight."
	/>
	<LinkCard
		href="https://inox-tools.fryuni.dev/star-warp"
		title="star-warp"
		description="Acelere a pesquisa de resultados na sua documentação."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-heading-badges"
		title="starlight-heading-badges"
		description="Adicione distintivos aos cabeçalhos de Markdown e MDX."
	/>
	<LinkCard
		href="https://github.com/Fevol/starlight-site-graph"
		title="starlight-site-graph"
		description="Adicione um mapa interativo do site à barra lateral das suas páginas."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-sidebar-topics"
		title="starlight-sidebar-topics"
		description="Divida a sua documentação em secções diferentes cada uma com a sua barra lateral."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-sidebar-topics-dropdown"
		title="starlight-sidebar-topics-dropdown"
		description="Divida as suas páginas de documentação em várias sub-páginas e alterne entre elas através de um menu na barra lateral."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-cooler-credit"
		title="starlight-cooler-credit"
		description="Adicione os créditos do Starlight ou Astro no fundo da tabela de conteúdos."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-contributor-list"
		title="starlight-contributor-list"
		description="Apresente uma lista de todos os contribuidores do seu projeto."
	/>
</CardGrid>

### Temas da comunidade

Um Tema é um plugin do Starlight que muda visualmente a aparência do site através da sobreposição de componentes, CSS personalizados, ou outras
novas funcionalidades.

<CardGrid>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-theme-rapide"
		title="starlight-theme-rapide"
		description="Tema do Starlight inspirado no tema Vitesse do Visual Studio Code."
	/>
	<LinkCard
		href="https://github.com/Fevol/starlight-theme-obsidian"
		title="starlight-theme-obsidian"
		description="Tema do Starlight inspirado em sites com o tema Obsidian Publish."
	/>
	<LinkCard
		href="https://github.com/TheOtterlord/catppuccin-starlight"
		title="catppuccin-starlight"
		description="Tema em tons de pastel suave para o Starlight"
	/>
</CardGrid>

## Ferramentas e integrações da comunidade

import { CardGrid, LinkCard } from '@astrojs/starlight/components';

Estas ferramentas e integrações da comunidade podem ser usadas para adicionar funcionalidades ao seu site Starlight.

<CardGrid>
	<LinkCard
		href="https://www.feelback.dev/blog/new-astro-starlight-integration/"
		title="FeelBack"
		description="Adicione um sistema de feedback de utilizador às páginas da documentação."
	/>
	<LinkCard
		href="https://github.com/val-town/notion-to-astro"
		title="notion-to-astro"
		description="Converta exportações do Notion para documentos do Starlight"
	/>
	<LinkCard
		href="https://github.com/mattjennings/astro-live-code"
		title="astro-live-code"
		description="Apresente blocos de código MDX como componentes interativos"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-i18n"
		title="starlight-i18n"
		description="Extensão para o Visual Studio Code que ajuda a traduzir páginas do Starlight."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-package-managers"
		title="starlight-package-managers"
		description="Mostra de forma rápida comandos npm relacionados para vários gestores de packages."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-showcases"
		title="starlight-showcases"
		description="Conjunto de componentes do Starlight para construir páginas de demonstração."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/generator-starlight-plugin"
		title="@hideoo/starlight-plugin"
		description="A generator to quickly scaffold Starlight plugins."
	/>
</CardGrid>


================================================
FILE: docs/src/content/docs/pt-pt/resources/showcase.mdx
================================================
---
title: Montra Starlight
description: Descubra sites construídos com Starlight!
sidebar:
  label: Montra de Sites
---

:::tip[Inclua o seu!]
Já construiu um site com o Starlight?
Então abra um PR e adicione o seu link nesta página!
:::

## Sites

import ShowcaseSites from '~/components/showcase-sites.astro';

O Starlight já está a ser usado em muitos sites em produção. Estes são alguns desses sites já espalhados pela web:

<ShowcaseSites />

Pesquise todos os [repositórios de projetos públicos que usam o Starlight no GitHub](https://github.com/withastro/starlight/network/dependents).


================================================
FILE: docs/src/content/docs/reference/configuration.mdx
================================================
---
title: Configuration Reference
description: An overview of all the configuration options Starlight supports.
---

## Configure the `starlight` integration

Starlight is an integration built on top the [Astro](https://astro.build) web framework. You can configure your project inside the `astro.config.mjs` configuration file:

```js
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'My delightful docs site',
		}),
	],
});
```

You can pass the following options to the `starlight` integration.

### `title` (required)

**type:** `string | Record<string, string>`

Set the title for your website. Will be used in metadata and in the browser tab title.

The value can be a string, or for multilingual sites, an object with values for each different locale.
When using the object form, the keys must be BCP-47 tags (e.g. `en`, `ar`, or `zh-CN`):

```ts
starlight({
	title: {
		en: 'My delightful docs site',
		de: 'Meine bezaubernde Dokumentationsseite',
	},
});
```

### `description`

**type:** `string`

Set the description for your website. Used in metadata shared with search engines in the `<meta name="description">` tag if `description` is not set in a page’s frontmatter.

### `logo`

**type:** [`LogoConfig`](#logoconfig)

Set a logo image to show in the navigation bar alongside or instead of the site title. You can either set a single `src` property or set separate image sources for `light` and `dark`.

```js
starlight({
	logo: {
		src: './src/assets/my-logo.svg',
	},
});
```

#### `LogoConfig`

```ts
type LogoConfig = { alt?: string; replacesTitle?: boolean } & (
	| { src: string }
	| { light: string; dark: string }
);
```

### `tableOfContents`

**type:** `false | { minHeadingLevel?: number; maxHeadingLevel?: number }`  
**default:** `{ minHeadingLevel: 2, maxHeadingLevel: 3 }`

Configure the table of contents shown on the right of each page. By default, `<h2>` and `<h3>` headings will be included in this table of contents.

### `editLink`

**type:** `{ baseUrl: string }`

Enable “Edit this page” links by setting the base URL these should use. The final link will be `editLink.baseUrl` + the current page path. For example, to enable editing pages in the `withastro/starlight` repo on GitHub:

```js
starlight({
	editLink: {
		baseUrl: 'https://github.com/withastro/starlight/edit/main/',
	},
});
```

With this config, a `/introduction` page would have an edit link pointing to `https://github.com/withastro/starlight/edit/main/src/content/docs/introduction.md`.

### `sidebar`

**type:** [`SidebarItem[]`](#sidebaritem)

Configure your site’s sidebar navigation items.

A sidebar is an array of links and groups of links.
With the exception of items using `slug`, each item must have a `label` and one of the following properties:

- `link` — a single link to a specific URL, e.g. `'/home'` or `'https://example.com'`.

- `slug` — a reference to an internal page, e.g. `'guides/getting-started'`.

- `items` — an array containing more sidebar links and subgroups.

- `autogenerate` — an object specifying a directory of your docs to automatically generate a group of links from.

Internal links can also be specified as a string instead of an object with a `slug` property.

```js
starlight({
	sidebar: [
		// A single link item labelled “Home”.
		{ label: 'Home', link: '/' },
		// A group labelled “Start Here” containing four links.
		{
			label: 'Start Here',
			items: [
				// Using `slug` for internal links.
				{ slug: 'intro' },
				{ slug: 'installation' },
				// Or using the shorthand for internal links.
				'tutorial',
				'next-steps',
			],
		},
		// A group linking to all pages in the reference directory.
		{
			label: 'Reference',
			autogenerate: { directory: 'reference' },
		},
	],
});
```

#### Sorting

Autogenerated sidebar groups are sorted by filename alphabetically.
For example, a page generated from `astro.md` would appear above the page for `starlight.md`.

#### Collapsing groups

Groups of links are expanded by default. You can change this behavior by setting a group’s `collapsed` property to `true`.

Autogenerated subgroups respect the `collapsed` property of their parent group by default. Set the `autogenerate.collapsed` property to override this.

```js {5,13}
sidebar: [
  // A collapsed group of links.
  {
    label: 'Collapsed Links',
    collapsed: true,
    items: ['intro', 'next-steps'],
  },
  // An expanded group containing collapsed autogenerated subgroups.
  {
    label: 'Reference',
    autogenerate: {
      directory: 'reference',
      collapsed: true,
    },
  },
],
```

#### Translating labels

If your site is multilingual, each item’s `label` is considered to be in the default locale. You can set a `translations` property to provide labels for your other supported languages:

```js {5,9,14}
sidebar: [
  // An example sidebar with labels translated to Brazilian Portuguese.
  {
    label: 'Start Here',
    translations: { 'pt-BR': 'Comece Aqui' },
    items: [
      {
        label: 'Getting Started',
        translations: { 'pt-BR': 'Introdução' },
        link: '/getting-started',
      },
      {
        label: 'Project Structure',
        translations: { 'pt-BR': 'Estrutura de Projetos' },
        link: '/structure',
      },
    ],
  },
],
```

#### `SidebarItem`

```ts
type SidebarItem =
	| string
	| ({
			translations?: Record<string, string>;
			badge?: string | BadgeConfig;
	  } & (
			| {
					// Link
					link: string;
					label: string;
					attrs?: Record<string, string | number | boolean | undefined>;
			  }
			| {
					// Internal link
					slug: string;
					label?: string;
					attrs?: Record<string, string | number | boolean | undefined>;
			  }
			| {
					// Group of links
					label: string;
					items: SidebarItem[];
					collapsed?: boolean;
			  }
			| {
					// Autogenerated link group
					label: string;
					autogenerate: {
						directory: string;
						collapsed?: boolean;
						attrs?: Record<string, string | number | boolean | undefined>;
					};
					collapsed?: boolean;
			  }
	  ));
```

#### `BadgeConfig`

```ts
interface BadgeConfig {
	text: string;
	variant?: 'note' | 'tip' | 'caution' | 'danger' | 'success' | 'default';
	class?: string;
}
```

### `locales`

**type:** <code>\{ \[dir: string\]: [LocaleConfig](#localeconfig) \}</code>

[Configure internationalization (i18n)](/guides/i18n/) for your site by setting which `locales` are supported.

Each entry should use the directory where that language’s files are saved as the key.

```js
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'My Site',
			// Set English as the default language for this site.
			defaultLocale: 'en',
			locales: {
				// English docs in `src/content/docs/en/`
				en: {
					label: 'English',
				},
				// Simplified Chinese docs in `src/content/docs/zh-cn/`
				'zh-cn': {
					label: '简体中文',
					lang: 'zh-CN',
				},
				// Arabic docs in `src/content/docs/ar/`
				ar: {
					label: 'العربية',
					dir: 'rtl',
				},
			},
		}),
	],
});
```

#### `LocaleConfig`

```ts
interface LocaleConfig {
	label: string;
	lang?: string;
	dir?: 'ltr' | 'rtl';
}
```

You can set the following options for each locale:

##### `label` (required)

**type:** `string`

The label for this language to show to users, for example in the language switcher. Most often you will want this to be the language’s name as a user of that language would expect to read it, e.g. `"English"`, `"العربية"`, or `"简体中文"`.

##### `lang`

**type:** `string`

The BCP-47 tag for this language, e.g. `"en"`, `"ar"`, or `"zh-CN"`. If not set, the language’s directory name will be used by default. Language tags with regional subtags (e.g. `"pt-BR"` or `"en-US"`) will use built-in UI translations for their base language if no region-specific translations are found.

##### `dir`

**type:** `'ltr' | 'rtl'`

The writing direction of this language; `"ltr"` for left-to-right (the default) or `"rtl"` for right-to-left.

#### Root locale

You can serve the default language without a `/lang/` directory by setting a `root` locale:

```js {3-6}
starlight({
	locales: {
		root: {
			label: 'English',
			lang: 'en',
		},
		fr: {
			label: 'Français',
		},
	},
});
```

For example, this allows you to serve `/getting-started/` as an English route and use `/fr/getting-started/` as the equivalent French page.

### `defaultLocale`

**type:** `string`

Set the language which is the default for this site.
The value should match one of the keys of your [`locales`](#locales) object.
(If your default language is your [root locale](#root-locale), you can skip this.)

The default locale will be used to provide fallback content where translations are missing.

### `social`

**type:** <code>{`Array<{ label: string; icon: `}[StarlightIcon](/reference/icons/){`; href: string }>`}</code>

Optional details about the social media accounts for this site.
Each entry will be displayed as an icon link in the site header.

```js
starlight({
	social: [
		{ icon: 'codeberg', label: 'Codeberg', href: 'https://codeberg.org/knut' },
		{ icon: 'discord', label: 'Discord', href: 'https://astro.build/chat' },
		{ icon: 'github', label: 'GitHub', href: 'https://github.com/withastro' },
		{ icon: 'gitlab', label: 'GitLab', href: 'https://gitlab.com/delucis' },
		{ icon: 'mastodon', label: 'Mastodon', href: 'https://m.webtoo.ls/@astro' },
	],
}),
```

### `customCss`

**type:** `string[]`

Provide CSS files to customize the look and feel of your Starlight site.

Supports local CSS files relative to the root of your project, e.g. `'./src/custom.css'`, and CSS you installed as an npm module, e.g. `'@fontsource/roboto'`.

```js
starlight({
	customCss: ['./src/custom-styles.css', '@fontsource/roboto'],
});
```

### `markdown`

**type:** `{ headingLinks?: boolean; processedDirs?: string[] }`  
**default:** `{ headingLinks: true, processedDirs: [] }`

Configure Starlight’s Markdown processing.

#### `headingLinks`

**type:** `boolean`  
**default:** `true`

Controls whether or not headings are rendered with a clickable anchor link.

```js
starlight({
	markdown: {
		// Disable Starlight’s clickable heading anchor links.
		headingLinks: false,
	},
}),
```

#### `processedDirs`

**type:** `string[]`  
**default:** `[]`

Define additional directories where files should be processed by Starlight’s Markdown pipeline.
By default, only Markdown and MDX content loaded using Starlight's [`docsLoader()`](/reference/configuration/#docsloader) is processed.
Supports local directories relative to the root of your project, e.g. `'./src/data/comments/'`.

Starlight’s processing includes support for [clickable heading anchor links](#headinglinks), [asides Markdown directive syntax](/guides/authoring-content/#asides), and RTL support for code blocks.
This option can be useful if you are rendering content from a custom content collection in a [custom page](/guides/pages/#custom-pages) using the `<StarlightPage>` component and expect Starlight's Markdown processing to be applied to that content as well.

```js
starlight({
	markdown: {
		// Process Markdown files from the `reviews` content collection located in the
		// `src/data/reviews/` directory.
		processedDirs: ['./src/data/reviews/'],
	},
}),
```

### `expressiveCode`

**type:** `StarlightExpressiveCodeOptions | boolean`  
**default:** `true`

Starlight uses [Expressive Code](https://expressive-code.com) to render code blocks and add support for highlighting parts of code examples, adding filenames to code blocks, and more.
See the [“Code blocks” guide](/guides/authoring-content/#code-blocks) to learn how to use Expressive Code syntax in your Markdown and MDX content.

You can use any of the standard [Expressive Code configuration options](https://expressive-code.com/reference/configuration/) as well as some Starlight-specific properties, by setting them in Starlight’s `expressiveCode` option.
For example, set Expressive Code’s `styleOverrides` option to override the default CSS. This enables customizations like giving your code blocks rounded corners:

```js ins={2-4}
starlight({
	expressiveCode: {
		styleOverrides: { borderRadius: '0.5rem' },
	},
});
```

If you want to disable Expressive Code, set `expressiveCode: false` in your Starlight config:

```js ins={2}
starlight({
	expressiveCode: false,
});
```

In addition to the standard Expressive Code options, you can also set the following Starlight-specific properties in your `expressiveCode` config to further customize theme behavior for your code blocks :

#### `themes`

**type:** `Array<string | ThemeObject | ExpressiveCodeTheme>`  
**default:** `['starlight-dark', 'starlight-light']`

Set the themes used to style code blocks.
See the [Expressive Code `themes` documentation](https://expressive-code.com/guides/themes/) for details of the supported theme formats.

Starlight uses the dark and light variants of Sarah Drasner’s [Night Owl theme](https://github.com/sdras/night-owl-vscode-theme) by default.

If you provide at least one dark and one light theme, Starlight will automatically keep the active code block theme in sync with the current site theme.
Configure this behavior with the [`useStarlightDarkModeSwitch`](#usestarlightdarkmodeswitch) option.

#### `useStarlightDarkModeSwitch`

**type:** `boolean`  
**default:** `true`

When `true`, code blocks automatically switch between light and dark themes when the site theme changes.
When `false`, you must manually add CSS to handle switching between multiple themes.

:::note
When setting `themes`, you must provide at least one dark and one light theme for the Starlight dark mode switch to work.
:::

#### `useStarlightUiThemeColors`

**type:** `boolean`  
**default:** `true` if `themes` is not set, otherwise `false`

When `true`, Starlight's CSS variables are used for the colors of code block UI elements (backgrounds, buttons, shadows etc.), matching the [site color theme](/guides/css-and-tailwind/#theming).
When `false`, the colors provided by the active syntax highlighting theme are used for these elements.

:::note
When using custom themes and setting this to `true`, you must provide at least one dark and one light theme to ensure proper color contrast.
:::

### `pagefind`

**type:** <code>boolean | <a href="#pagefindoptions">PagefindOptions</a></code>  
**default:** `true`

Configure Starlight’s default site search provider [Pagefind](https://pagefind.app/).

Set to `false` to disable indexing your site with Pagefind.
This will also hide the default search UI if in use.

Pagefind cannot be enabled when the [`prerender`](#prerender) option is set to `false`.

Set `pagefind` to an object to configure the Pagefind search client:

- See [“Customize Pagefind's result ranking”](https://pagefind.app/docs/ranking/) in the Pagefind documentation for more details about using the `pagefind.ranking` option to control how search result ranking is calculated
- See [“Searching multiple sites”](https://pagefind.app/docs/multisite/) in the Pagefind documentation for more details about using the `pagefind.mergeIndex` option to control how to search across multiple sites

#### `PagefindOptions`

```ts
interface PagefindOptions {
	ranking?: {
		pageLength?: number;
		termFrequency?: number;
		termSaturation?: number;
		termSimilarity?: number;
	};
	indexWeight?: number;
	mergeIndex?: Array<{
		bundlePath: string;
		indexWeight?: number;
		basePath?: string;
		baseUrl?: string;
		mergeFilter?: Record<string, string | string[]>;
		language?: string;
		ranking?: {
			pageLength?: number;
			termFrequency?: number;
			termSaturation?: number;
			termSimilarity?: number;
		};
	}>;
}
```

### `prerender`

**type:** `boolean`  
**default:** `true`

Define whether Starlight pages should be pre-rendered to static HTML or on-demand rendered by an [SSR adapter](https://docs.astro.build/en/guides/on-demand-rendering/).

Starlight pages are pre-rendered by default.
If you are using an SSR adapter and want to render Starlight pages on demand, set `prerender: false`.

### `head`

**type:** [`HeadConfig[]`](#headconfig)

Add custom tags to the `<head>` of your Starlight site.
Can be useful for adding analytics and other third-party scripts and resources.

```js
starlight({
	head: [
		// Example: add Fathom analytics script tag.
		{
			tag: 'script',
			attrs: {
				src: 'https://cdn.usefathom.com/script.js',
				'data-site': 'MY-FATHOM-ID',
				defer: true,
			},
		},
	],
});
```

Entries in `head` are converted directly to HTML elements and do not pass through Astro’s [script](https://docs.astro.build/en/guides/client-side-scripts/#script-processing) or [style](https://docs.astro.build/en/guides/styling/#styling-in-astro) processing.
If you need to import local assets like scripts, styles, or images, [override the Head component](/guides/overriding-components/#reuse-a-built-in-component).

#### `HeadConfig`

```ts
interface HeadConfig {
	tag: string;
	attrs?: Record<string, string | boolean | undefined>;
	content?: string;
}
```

### `lastUpdated`

**type:** `boolean`  
**default:** `false`

Control whether the footer shows when the page was last updated.

By default, this feature relies on your repository’s Git history and may not be accurate on some deployment platforms performing [shallow clones](https://git-scm.com/docs/git-clone#Documentation/git-clone.txt---depthltdepthgt). A page can override this setting or the Git-based date using the [`lastUpdated` frontmatter field](/reference/frontmatter/#lastupdated).

### `pagination`

**type:** `boolean`  
**default:** `true`

Define if the footer should include previous and next page links.

A page can override this setting or the link text and/or URL using the [`prev`](/reference/frontmatter/#prev) and [`next`](/reference/frontmatter/#next) frontmatter fields.

### `favicon`

**type:** `string`  
**default:** `'/favicon.svg'`

Set the path of the default favicon for your website which should be located in the `public/` directory and be a valid (`.ico`, `.gif`, `.jpg`, `.png`, or `.svg`) icon file.

```js
starlight({
  favicon: '/images/favicon.svg',
}),
```

If you need to set additional variants or fallback favicons, you can add tags using the [`head` option](#head):

```js
starlight({
	favicon: '/images/favicon.svg',
	head: [
		// Add ICO favicon fallback for Safari.
		{
			tag: 'link',
			attrs: {
				rel: 'icon',
				href: '/images/favicon.ico',
				sizes: '32x32',
			},
		},
	],
});
```

### `titleDelimiter`

**type:** `string`  
**default:** `'|'`

Sets the delimiter between page title and site title in the page’s `<title>` tag, which is displayed on browser tabs.

By default, every page has a `<title>` of `Page Title | Site Title`.
For example, this page is titled “Configuration Reference” and this site is titled “Starlight”, so the `<title>` for this page is “Configuration Reference | Starlight”.

### `disable404Route`

**type:** `boolean`  
**default:** `false`

Disables injecting Starlight's default [404 page](https://docs.astro.build/en/basics/astro-pages/#custom-404-error-page). To use a custom `src/pages/404.astro` route in your project, set this option to `true`.

### `routeMiddleware`

**type:** `string | string[]`

Provide paths to route middleware that can modify how Starlight processes your data.
These file paths must not conflict with [Astro’s middleware](https://docs.astro.build/en/guides/middleware/).

See the [Route Data guide](/guides/route-data/#customizing-route-data) for details about how to create route middleware.

### `components`

**type:** `Record<string, string>`

Provide the paths to components to override Starlight’s default implementations.

```js
starlight({
	components: {
		SocialLinks: './src/components/MySocialLinks.astro',
	},
});
```

See the [Overrides Reference](/reference/overrides/) for details of all the components that you can override.

### `plugins`

**type:** [`StarlightPlugin[]`](/reference/plugins/#quick-api-reference)

Extend Starlight with custom plugins.
Plugins apply changes to your project to modify or add to Starlight's features.

Visit the [plugins showcase](/resources/plugins/#plugins) to see a list of available plugins.

```js
starlight({
	plugins: [starlightPlugin()],
});
```

See the [Plugins Reference](/reference/plugins/) for details about creating your own plugins.

### `credits`

**type:** `boolean`  
**default:** `false`

Enable displaying a “Built with Starlight” link in your site’s footer.

```js
starlight({
	credits: true,
});
```

## Configure content collections

Starlight uses Astro [content collections](https://docs.astro.build/en/guides/content-collections/) to load your content.
Starlight’s content loaders and schemas help configure collections as required.

```js
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';

export const collections = {
	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
	// Optional: the i18n collection is used to translate UI in multilingual sites
	i18n: defineCollection({ loader: i18nLoader(), schema: i18nSchema() }),
};
```

### Loaders

Starlight exports the following [Astro loaders](https://docs.astro.build/en/reference/content-loader-reference/) from the `@astrojs/starlight/loaders` module to simplify configuring content collections.

#### `docsLoader()`

The `docsLoader()` loads local Markdown, MDX, and Markdoc files from the `src/content/docs/` directory.
File names starting with an underscore (`_`) are ignored.

##### Import

```js
import { docsLoader } from '@astrojs/starlight/loaders';
```

##### Options

###### `generateId()`

**type:** `({ entry: string; base: URL; data: Record<string, unknown> }) => string`

By default, pages generated using `docsLoader()` process your file names using a sluggifier, which removes special characters and lowercases the file name.
If you want to override this default, provide your own custom `generateId()` function.

For example, this can be useful to preserve special characters that would be removed.
By default, `Example.File.md` would be served at `/examplefile`.
If you wanted to serve it at `/Example.File`, you could do so by defining a custom `generateId()` function:

```js
docsLoader({
	// Remove the `.md` or `.mdx` extension, but otherwise don’t process filenames.
	generateId: ({ entry }) => entry.split('.').slice(0, -1).join('.'),
}),
```

See [`generateId()` in the Astro docs](https://docs.astro.build/en/reference/content-loader-reference/#generateid) for more details.

#### `i18nLoader()`

The `i18nLoader()` loads local JSON and YAML files from the `src/content/i18n/` directory.
File names starting with an underscore (`_`) are ignored.

##### Import

```js
import { i18nLoader } from '@astrojs/starlight/loaders';
```

##### Options

There are currently no options to configure `i18nLoader()`.

### Schemas

Starlight provides the following [content collection schemas](https://docs.astro.build/en/guides/content-collections/#defining-the-collection-schema) from the `@astrojs/starlight/schema` module.
These schemas must be used for the `docs` and `i18n` collections Starlight depends on.

#### `docsSchema()`

The `docsSchema()` parses frontmatter for all your content in the `docs` collection.

##### Import

```js
import { docsSchema } from '@astrojs/starlight/schema';
```

##### Options

###### `extend`

**type:** Zod schema or function that returns a Zod schema  
**default:** `z.object({})`

Extend Starlight’s frontmatter schema with additional fields.
See [“Customize frontmatter schema”](/reference/frontmatter/#customize-frontmatter-schema) for more details about using the `extend` option.

#### `i18nSchema()`

The `i18nSchema()` parses all data files in the `i18n` collection.

##### Import

```js
import { i18nSchema } from '@astrojs/starlight/schema';
```

##### Options

###### `extend`

**type:** Zod object  
**default:** `z.object({})`

Extend Starlight’s i18n schema with additional fields.
See [“Extend translation schema”](/guides/i18n/#extend-translation-schema) for more details about using the `extend` option.


================================================
FILE: docs/src/content/docs/reference/frontmatter.md
================================================
---
title: Frontmatter Reference
description: An overview of the default frontmatter fields Starlight supports.
---

You can customize individual Markdown and MDX pages in Starlight by setting values in their frontmatter. For example, a regular page might set `title` and `description` fields:

```md {3-4}
---
# src/content/docs/example.md
title: About this project
description: Learn more about the project I’m working on.
---

Welcome to the about page!
```

## Frontmatter fields

### `title` (required)

**type:** `string`

You must provide a title for every page. This will be displayed at the top of the page, in browser tabs, and in page metadata.

### `description`

**type:** `string`

The page description is used for page metadata and will be picked up by search engines and in social media previews.

### `slug`

**type**: `string`

Override the slug of the page. See [“Defining custom IDs”](https://docs.astro.build/en/guides/content-collections/#defining-custom-ids) in the Astro docs for more details.

### `editUrl`

**type:** `string | boolean`

Overrides the [global `editLink` config](/reference/configuration/#editlink). Set to `false` to disable the “Edit page” link for a specific page or provide an alternative URL where the content of this page is editable.

### `head`

**type:** [`HeadConfig[]`](/reference/configuration/#headconfig)

You can add additional tags to your page’s `<head>` using the `head` frontmatter field. This means you can add custom styles, metadata or other tags to a single page. Similar to the [global `head` option](/reference/configuration/#head).

```md
---
# src/content/docs/example.md
title: About us
head:
  # Use a custom <title> tag
  - tag: title
    content: Custom about title
---
```

### `tableOfContents`

**type:** `false | { minHeadingLevel?: number; maxHeadingLevel?: number; }`

Overrides the [global `tableOfContents` config](/reference/configuration/#tableofcontents).
Customize the heading levels to be included or set to `false` to hide the table of contents on this page.

```md
---
# src/content/docs/example.md
title: Page with only H2s in the table of contents
tableOfContents:
  minHeadingLevel: 2
  maxHeadingLevel: 2
---
```

```md
---
# src/content/docs/example.md
title: Page with no table of contents
tableOfContents: false
---
```

### `template`

**type:** `'doc' | 'splash'`  
**default:** `'doc'`

Set the layout template for this page.
Pages use the `'doc'` layout by default.
Set to `'splash'` to use a wider layout without any sidebars designed for landing pages.

### `hero`

**type:** [`HeroConfig`](#heroconfig)

Add a hero component to the top of this page. Works well with `template: splash`.

For example, this config shows some common options, including loading an image from your repository.

```md
---
# src/content/docs/example.md
title: My Home Page
template: splash
hero:
  title: 'My Project: Stellar Stuff Sooner'
  tagline: Take your stuff to the moon and back in the blink of an eye.
  image:
    alt: A glittering, brightly colored logo
    file: ~/assets/logo.png
  actions:
    - text: Tell me more
      link: /getting-started/
      icon: right-arrow
    - text: View on GitHub
      link: https://github.com/astronaut/my-project
      icon: external
      variant: minimal
      attrs:
        rel: me
---
```

You can display different versions of the hero image in light and dark modes.

```md
---
# src/content/docs/example.md
hero:
  image:
    alt: A glittering, brightly colored logo
    dark: ~/assets/logo-dark.png
    light: ~/assets/logo-light.png
---
```

#### `HeroConfig`

```ts
interface HeroConfig {
  title?: string;
  tagline?: string;
  image?:
    | {
        // Relative path to an image in your repository.
        file: string;
        // Alt text to make the image accessible to assistive technology
        alt?: string;
      }
    | {
        // Relative path to an image in your repository to be used for dark mode.
        dark: string;
        // Relative path to an image in your repository to be used for light mode.
        light: string;
        // Alt text to make the image accessible to assistive technology
        alt?: string;
      }
    | {
        // Raw HTML to use in the image slot.
        // Could be a custom `<img>` tag or inline `<svg>`.
        html: string;
      };
  actions?: Array<{
    text: string;
    link: string;
    variant?: 'primary' | 'secondary' | 'minimal';
    icon?: string;
    attrs?: Record<string, string | number | boolean>;
  }>;
}
```

### `banner`

**type:** `{ content: string }`

Displays an announcement banner at the top of this page.

The `content` value can include HTML for links or other content.
For example, this page displays a banner including a link to `example.com`.

```md
---
# src/content/docs/example.md
title: Page with a banner
banner:
  content: |
    We just launched something cool!
    <a href="https://example.com">Check it out</a>
---
```

### `lastUpdated`

**type:** `Date | boolean`

Overrides the [global `lastUpdated` option](/reference/configuration/#lastupdated). If a date is specified, it must be a valid [YAML timestamp](https://yaml.org/type/timestamp.html) and will override the date stored in Git history for this page.

```md
---
# src/content/docs/example.md
title: Page with a custom last update date
lastUpdated: 2022-08-09
---
```

### `prev`

**type:** `boolean | string | { link?: string; label?: string }`

Overrides the [global `pagination` option](/reference/configuration/#pagination). If a string is specified, the generated link text will be replaced and if an object is specified, both the link and the text will be overridden.

```md
---
# src/content/docs/example.md
# Hide the previous page link
prev: false
---
```

```md
---
# src/content/docs/example.md
# Override the previous page link text
prev: Continue the tutorial
---
```

```md
---
# src/content/docs/example.md
# Override both the previous page link and text
prev:
  link: /unrelated-page/
  label: Check out this other page
---
```

### `next`

**type:** `boolean | string | { link?: string; label?: string }`

Same as [`prev`](#prev) but for the next page link.

```md
---
# src/content/docs/example.md
# Hide the next page link
next: false
---
```

### `pagefind`

**type:** `boolean`  
**default:** `true`

Set whether this page should be included in the [Pagefind](https://pagefind.app/) search index. Set to `false` to exclude a page from search results:

```md
---
# src/content/docs/example.md
# Hide this page from the search index
pagefind: false
---
```

### `draft`

**type:** `boolean`  
**default:** `false`

Set whether this page should be considered a draft and not be included in [production builds](https://docs.astro.build/en/reference/cli-reference/#astro-build). Set to `true` to mark a page as a draft and make it only visible during development.

```md
---
# src/content/docs/example.md
# Exclude this page from production builds
draft: true
---
```

Because draft pages are not included in build output, you cannot add draft pages directly to your site sidebar config using [slugs](/guides/sidebar/#internal-links).
Draft pages in directories used for [autogenerated sidebar groups](/guides/sidebar/#autogenerated-groups) are automatically excluded in production builds.

### `sidebar`

**type:** [`SidebarConfig`](#sidebarconfig)

Control how this page is displayed in the [sidebar](/reference/configuration/#sidebar), when using an autogenerated link group.

#### `SidebarConfig`

```ts
interface SidebarConfig {
  label?: string;
  order?: number;
  hidden?: boolean;
  badge?: string | BadgeConfig;
  attrs?: Record<string, string | number | boolean | undefined>;
}
```

#### `label`

**type:** `string`  
**default:** the page [`title`](#title-required)

Set the label for this page in the sidebar when displayed in an autogenerated group of links.

```md
---
# src/content/docs/example.md
title: About this project
sidebar:
  label: About
---
```

#### `order`

**type:** `number`

Control the order of this page when sorting an autogenerated group of links.
Lower numbers are displayed higher up in the link group.

```md
---
# src/content/docs/example.md
title: Page to display first
sidebar:
  order: 1
---
```

#### `hidden`

**type:** `boolean`  
**default:** `false`

Prevents this page from being included in an autogenerated sidebar group.

```md
---
# src/content/docs/example.md
title: Page to hide from autogenerated sidebar
sidebar:
  hidden: true
---
```

#### `badge`

**type:** <code>string | <a href="/reference/configuration/#badgeconfig">BadgeConfig</a></code>

Add a badge to the page in the sidebar when displayed in an autogenerated group of links.
When using a string, the badge will be displayed with a default accent color.
Optionally, pass a [`BadgeConfig` object](/reference/configuration/#badgeconfig) with `text`, `variant`, and `class` fields to customize the badge.

```md
---
# src/content/docs/example.md
title: Page with a badge
sidebar:
  # Uses the default variant matching your site’s accent color
  badge: New
---
```

```md
---
# src/content/docs/example.md
title: Page with a badge
sidebar:
  badge:
    text: Experimental
    variant: caution
---
```

#### `attrs`

**type:** `Record<string, string | number | boolean | undefined>`

HTML attributes to add to the page link in the sidebar when displayed in an autogenerated group of links.
If [`autogenerate.attrs`](/guides/sidebar/#custom-html-attributes-for-autogenerated-links) is set on the autogenerated group this page belongs to, frontmatter attributes will be merged with the group attributes.

```md
---
# src/content/docs/example.md
title: Page opening in a new tab
sidebar:
  # Opens the page in a new tab
  attrs:
    target: _blank
---
```

## Customize frontmatter schema

The frontmatter schema for Starlight’s `docs` content collection is configured in `src/content.config.ts` using the `docsSchema()` helper:

```ts {4,7}
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
  docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
};
```

Learn more about content collection schemas in [“Defining a collection schema”](https://docs.astro.build/en/guides/content-collections/#defining-the-collection-schema) in the Astro docs.

`docsSchema()` takes the following options:

### `extend`

**type:** Zod schema or function that returns a Zod schema  
**default:** `z.object({})`

Extend Starlight’s schema with additional fields by setting `extend` in the `docsSchema()` options.
The value should be a [Zod schema](https://docs.astro.build/en/guides/content-collections/#defining-datatypes-with-zod).

In the following example, we provide a stricter type for `description` to make it required and add a new optional `category` field:

```ts {11-16}
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { z } from 'astro/zod';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
  docs: defineCollection({
    loader: docsLoader(),
    schema: docsSchema({
      extend: z.object({
        // Make a built-in field required instead of optional.
        description: z.string(),
        // Add a new field to the schema.
        category: z.enum(['tutorial', 'guide', 'reference']).optional(),
      }),
    }),
  }),
};
```

To take advantage of the [Astro `image()` helper](https://docs.astro.build/en/guides/images/#images-in-content-collections), use a function that returns your schema extension:

```ts {11-16}
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { z } from 'astro/zod';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
  docs: defineCollection({
    loader: docsLoader(),
    schema: docsSchema({
      extend: ({ image }) => {
        return z.object({
          // Add a field that must resolve to a local image.
          cover: image(),
        });
      },
    }),
  }),
};
```


================================================
FILE: docs/src/content/docs/reference/icons.mdx
================================================
---
title: Icons Reference
description: An overview of all the icons available in Starlight.
---

Starlight provides a set of built-in icons that you can display in your content using the `<Icon>` component.

## Use icons

Icons can be displayed using the [`<Icon>`](/components/icons/) component.
They are also often used in other components, such as [cards](/components/cards/) or settings like [hero actions](/reference/frontmatter/#hero).

## `StarlightIcon` type

Use the `StarlightIcon` TypeScript type to reference the names of [Starlight’s built-in icons](#all-icons).

```ts {2} /icon: (StarlightIcon)/
// src/icon.ts
import type { StarlightIcon } from '@astrojs/starlight/types';

function getIconLabel(icon: StarlightIcon) {
	// …
}
```

## All icons

A list of all available icons is shown below with their associated names. Click an icon to copy its name to your clipboard.

import IconsList from '~/components/icons-list.astro';

<IconsList labels={{ copied: 'Copied!' }} />


================================================
FILE: docs/src/content/docs/reference/overrides.md
================================================
---
title: Overrides Reference
description: An overview of the components and component props supported by Starlight overrides.
tableOfContents:
  maxHeadingLevel: 4
---

You can override Starlight’s built-in components by providing paths to replacement components in Starlight’s [`components`](/reference/configuration/#components) configuration option.
This page lists all components available to override and links to their default implementations on GitHub.

Learn more in the [Guide to Overriding Components](/guides/overriding-components/).

## Components

### Head

These components are rendered inside each page’s `<head>` element.
They should only include [elements permitted inside `<head>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head#see_also).

#### `Head`

**Default component:** [`Head.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Head.astro)

Component rendered inside each page’s `<head>`.

Override this component as a last resort.
Prefer the [`head` config option](/reference/configuration/#head), the [`head` frontmatter field](/reference/frontmatter/#head), or a [route data middleware](/guides/route-data/#customizing-route-data) to customize the route data rendered by the default component if possible.

#### `ThemeProvider`

**Default component:** [`ThemeProvider.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/ThemeProvider.astro)

Component rendered inside `<head>` that sets up dark/light theme support.
The default implementation includes an inline script and a `<template>` used by the script in [`<ThemeSelect />`](#themeselect).

---

### Accessibility

#### `SkipLink`

**Default component:** [`SkipLink.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/SkipLink.astro)

Component rendered as the first element inside `<body>` which links to the main page content for accessibility.
The default implementation is hidden until a user focuses it by tabbing with their keyboard.

---

### Layout

These components are responsible for laying out Starlight’s components and managing views across different breakpoints.
Overriding these comes with significant complexity.
When possible, prefer overriding a lower-level component.

#### `PageFrame`

**Default component:** [`PageFrame.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/PageFrame.astro)  
**Named slots:** `header`, `sidebar`

Layout component wrapped around most of the page content.
The default implementation sets up the header–sidebar–main layout and includes `header` and `sidebar` named slots along with a default slot for the main content.
It also renders [`<MobileMenuToggle />`](#mobilemenutoggle) to support toggling the sidebar navigation on small (mobile) viewports.

#### `MobileMenuToggle`

**Default component:** [`MobileMenuToggle.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MobileMenuToggle.astro)

Component rendered inside [`<PageFrame>`](#pageframe) that is responsible for toggling the sidebar navigation on small (mobile) viewports.

#### `TwoColumnContent`

**Default component:** [`TwoColumnContent.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/TwoColumnContent.astro)  
**Named slot:** `right-sidebar`

Layout component wrapped around the main content column and right sidebar (table of contents).
The default implementation handles the switch between a single-column, small-viewport layout and a two-column, larger-viewport layout.

---

### Header

These components render Starlight’s top navigation bar.

#### `Header`

**Default component:** [`Header.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Header.astro)

Header component displayed at the top of every page.
The default implementation displays [`<SiteTitle />`](#sitetitle), [`<Search />`](#search), [`<SocialIcons />`](#socialicons), [`<ThemeSelect />`](#themeselect), and [`<LanguageSelect />`](#languageselect).

#### `SiteTitle`

**Default component:** [`SiteTitle.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/SiteTitle.astro)

Component rendered at the start of the site header to render the site title.
The default implementation includes logic for rendering logos defined in Starlight config.

#### `Search`

**Default component:** [`Search.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Search.astro)

Component used to render Starlight’s search UI.
The default implementation includes the button in the header and the code for displaying a search modal when it is clicked and loading [Pagefind’s UI](https://pagefind.app/).

When [`pagefind`](/reference/configuration/#pagefind) is disabled, the default search component will not be rendered.
However, if you override `Search`, your custom component will always be rendered even if the `pagefind` configuration option is `false`.
This allows you to add UI for alternative search providers when disabling Pagefind.

#### `SocialIcons`

**Default component:** [`SocialIcons.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/SocialIcons.astro)

Component rendered in the site header including social icon links.
The default implementation uses the [`social`](/reference/configuration/#social) option in Starlight config to render icons and links.

#### `ThemeSelect`

**Default component:** [`ThemeSelect.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/ThemeSelect.astro)

Component rendered in the site header that allows users to select their preferred color scheme.

#### `LanguageSelect`

**Default component:** [`LanguageSelect.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/LanguageSelect.astro)

Component rendered in the site header that allows users to switch to a different language.

---

### Global Sidebar

Starlight’s global sidebar includes the main site navigation.
On narrow viewports this is hidden behind a drop-down menu.

#### `Sidebar`

**Default component:** [`Sidebar.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Sidebar.astro)

Component rendered before page content that contains global navigation.
The default implementation displays as a sidebar on wide enough viewports and inside a drop-down menu on small (mobile) viewports.
It also renders [`<MobileMenuFooter />`](#mobilemenufooter) to show additional items inside the mobile menu.

#### `MobileMenuFooter`

**Default component:** [`MobileMenuFooter.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MobileMenuFooter.astro)

Component rendered at the bottom of the mobile drop-down menu.
The default implementation renders [`<ThemeSelect />`](#themeselect) and [`<LanguageSelect />`](#languageselect).

---

### Page Sidebar

Starlight’s page sidebar is responsible for displaying a table of contents outlining the current page’s subheadings.
On narrow viewports this collapse into a sticky, drop-down menu.

#### `PageSidebar`

**Default component:** [`PageSidebar.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/PageSidebar.astro)

Component rendered before the main page’s content to display a table of contents.
The default implementation renders [`<TableOfContents />`](#tableofcontents) and [`<MobileTableOfContents />`](#mobiletableofcontents).

#### `TableOfContents`

**Default component:** [`TableOfContents.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/TableOfContents.astro)

Component that renders the current page’s table of contents on wider viewports.

#### `MobileTableOfContents`

**Default component:** [`MobileTableOfContents.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MobileTableOfContents.astro)

Component that renders the current page’s table of contents on small (mobile) viewports.

---

### Content

These components are rendered in the main column of page content.

#### `Banner`

**Default component:** [`Banner.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Banner.astro)

Banner component rendered at the top of each page.
The default implementation uses the page’s [`banner`](/reference/frontmatter/#banner) frontmatter value to decide whether or not to render.

#### `ContentPanel`

**Default component:** [`ContentPanel.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/ContentPanel.astro)

Layout component used to wrap sections of the main content column.

#### `PageTitle`

**Default component:** [`PageTitle.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/PageTitle.astro)

Component containing the `<h1>` element for the current page.

Implementations should ensure they set `id="_top"` on the `<h1>` element as in the default implementation.

#### `DraftContentNotice`

**Default component:** [`DraftContentNotice.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/DraftContentNotice.astro)

Notice displayed to users during development when the current page is marked as a draft.

#### `FallbackContentNotice`

**Default component:** [`FallbackContentNotice.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/FallbackContentNotice.astro)

Notice displayed to users on pages where a translation for the current language is not available.
Only used on multilingual sites.

#### `Hero`

**Default component:** [`Hero.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Hero.astro)

Component rendered at the top of the page when [`hero`](/reference/frontmatter/#hero) is set in frontmatter.
The default implementation shows a large title, tagline, and call-to-action links alongside an optional image.

#### `MarkdownContent`

**Default component:** [`MarkdownContent.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MarkdownContent.astro)

Component rendered around each page’s main content.
The default implementation sets up basic styles to apply to Markdown content.

The Markdown content styles are also exposed in `@astrojs/starlight/style/markdown.css` and scoped to the `.sl-markdown-content` CSS class.

---

### Footer

These components are rendered at the bottom of the main column of page content.

#### `Footer`

**Default component:** [`Footer.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Footer.astro)

Footer component displayed at the bottom of each page.
The default implementation displays [`<LastUpdated />`](#lastupdated), [`<Pagination />`](#pagination), and [`<EditLink />`](#editlink).

#### `LastUpdated`

**Default component:** [`LastUpdated.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/LastUpdated.astro)

Component rendered in the page footer to display the last-updated date.

#### `EditLink`

**Default component:** [`EditLink.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/EditLink.astro)

Component rendered in the page footer to display a link to where the page can be edited.

#### `Pagination`

**Default component:** [`Pagination.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Pagination.astro)

Component rendered in the page footer to display navigation arrows between previous/next pages.


================================================
FILE: docs/src/content/docs/reference/plugins.md
================================================
---
title: Plugins Reference
description: An overview of the Starlight plugin API.
tableOfContents:
  maxHeadingLevel: 4
---

Starlight plugins can customize Starlight configuration, UI, and behavior, while also being easy to share and reuse.
This reference page documents the API that plugins have access to.

Learn more about using a Starlight plugin in the [Configuration Reference](/reference/configuration/#plugins) or visit the [plugins showcase](/resources/plugins/#plugins) to see a list of available plugins.

## Quick API Reference

A Starlight plugin has the following shape.
See below for details of the different properties and hook parameters.

<!-- prettier-ignore-start -->
```ts
interface StarlightPlugin {
  name: string;
  hooks: {
    'i18n:setup'?: (options: {
      injectTranslations: (
        translations: Record<string, Record<string, string>>
      ) => void;
    }) => void | Promise<void>;
    'config:setup': (options: {
      config: StarlightUserConfig;
      updateConfig: (newConfig: StarlightUserConfig) => void;
      addIntegration: (integration: AstroIntegration) => void;
      addRouteMiddleware: (config: { entrypoint: string; order?: 'pre' | 'post' | 'default' }) => void;
      astroConfig: AstroConfig;
      command: 'dev' | 'build' | 'preview';
      isRestart: boolean;
      logger: AstroIntegrationLogger;
      useTranslations: (lang: string) => I18nT;
      absolutePathToLang: (path: string) => string;
    }) => void | Promise<void>;
  };
}
```
<!-- prettier-ignore-end -->

## `name`

**type:** `string`

A plugin must provide a unique name that describes it. The name is used when [logging messages](#logger) related to this plugin and may be used by other plugins to detect the presence of this plugin.

## `hooks`

Hooks are functions which Starlight calls to run plugin code at specific times.

To get the type of a hook's arguments, use the `HookParameters` utility type and pass in the hook name.
In the following example, the `options` parameter is typed to match the arguments passed to the `config:setup` hook:

```ts
import type { HookParameters } from '@astrojs/starlight/types';

function configSetup(options: HookParameters['config:setup']) {
  options.useTranslations('en');
}
```

### `i18n:setup`

Plugin internationalization setup function called when Starlight is initialized.
The `i18n:setup` hook can be used to inject translation strings so a plugin can support different locales.
These translations will be available via [`useTranslations()`](#usetranslations) in the `config:setup` hook and in UI components via [`Astro.locals.t()`](/guides/i18n/#using-ui-translations).

The `i18n:setup` hook is called with the following options:

#### `injectTranslations`

**type:** `(translations: Record<string, Record<string, string>>) => void`

A callback function to add or update translation strings used in Starlight’s [localization APIs](/guides/i18n/#using-ui-translations).

In the following example, a plugin injects translations for a custom UI string named `myPlugin.doThing` for the `en` and `fr` locales:

```ts {6-13} /(injectTranslations)[^(]/
// plugin.ts
export default {
  name: 'plugin-with-translations',
  hooks: {
    'i18n:setup'({ injectTranslations }) {
      injectTranslations({
        en: {
          'myPlugin.doThing': 'Do the thing',
        },
        fr: {
          'myPlugin.doThing': 'Faire le truc',
        },
      });
    },
  },
};
```

To use the injected translations in your plugin UI, follow the [“Using UI translations” guide](/guides/i18n/#using-ui-translations).
If you need to use UI strings in the context of the [`config:setup`](#configsetup) hook of your plugin, you can use the [`useTranslations()`](#usetranslations) callback.

Types for a plugin’s injected translation strings are generated automatically in a user’s project, but are not yet available when working in your plugin’s codebase.
To type the `locals.t` object in the context of your plugin, declare the following global namespaces in a TypeScript declaration file:

```ts
// env.d.ts
declare namespace App {
  type StarlightLocals = import('@astrojs/starlight').StarlightLocals;
  // Define the `locals.t` object in the context of a plugin.
  interface Locals extends StarlightLocals {}
}

declare namespace StarlightApp {
  // Define the additional plugin translations in the `I18n` interface.
  interface I18n {
    'myPlugin.doThing': string;
  }
}
```

You can also infer the types for the `StarlightApp.I18n` interface from a source file if you have an object containing your translations.

For example, given the following source file:

```ts title="ui-strings.ts"
export const UIStrings = {
  en: { 'myPlugin.doThing': 'Do the thing' },
  fr: { 'myPlugin.doThing': 'Faire le truc' },
};
```

The following declaration would infer types from the English keys in the source file:

```ts title="env.d.ts"
declare namespace StarlightApp {
  type UIStrings = typeof import('./ui-strings').UIStrings.en;
  interface I18n extends UIStrings {}
}
```

### `config:setup`

Plugin configuration setup function called when Starlight is initialized (during the [`astro:config:setup`](https://docs.astro.build/en/reference/integrations-reference/#astroconfigsetup) integration hook).
The `config:setup` hook can be used to update the Starlight configuration or add Astro integrations.

This hook is called with the following options:

#### `config`

**type:** `StarlightUserConfig`

A read-only copy of the user-supplied [Starlight configuration](/reference/configuration/).
This configuration may have been updated by other plugins configured before the current one.

#### `updateConfig`

**type:** `(newConfig: StarlightUserConfig) => void`

A callback function to update the user-supplied [Starlight configuration](/reference/configuration/).
Provide the root-level configuration keys you want to override.
To update nested configuration values, you must provide the entire nested object.

To extend an existing config option without overriding it, spread the existing value into your new value.
In the following example, a new [`social`](/reference/configuration/#social) media account is added to the existing configuration by spreading `config.social` into the new `social` array:

```ts {6-15}
// plugin.ts
export default {
  name: 'add-twitter-plugin',
  hooks: {
    'config:setup'({ config, updateConfig }) {
      updateConfig({
        social: [
          ...config.social,
          {
            icon: 'twitter',
            label: 'Twitter',
            href: 'https://twitter.com/astrodotbuild',
          },
        ],
      });
    },
  },
};
```

#### `addIntegration`

**type:** `(integration: AstroIntegration) => void`

A callback function to add an [Astro integration](https://docs.astro.build/en/reference/integrations-reference/) required by the plugin.

In the following example, the plugin first checks if [Astro’s React integration](https://docs.astro.build/en/guides/integrations-guide/react/) is configured and, if it isn’t, uses `addIntegration()` to add it:

```ts {14} "addIntegration,"
// plugin.ts
import react from '@astrojs/react';

export default {
  name: 'plugin-using-react',
  hooks: {
    'config:setup'({ addIntegration, astroConfig }) {
      const isReactLoaded = astroConfig.integrations.find(
        ({ name }) => name === '@astrojs/react'
      );

      // Only add the React integration if it's not already loaded.
      if (!isReactLoaded) {
        addIntegration(react());
      }
    },
  },
};
```

#### `addRouteMiddleware`

**type:** `(config: { entrypoint: string; order?: 'pre' | 'post' | 'default' }) => void`

A callback function to add a [route middleware handler](/guides/route-data/) to the site.

The `entrypoint` property must be a module specifier for your plugin’s middleware file that exports an `onRequest` handler.

In the following example, a plugin published as `@example/starlight-plugin` adds a route middleware using an npm module specifier:

```js {6-9}
// plugin.ts
export default {
  name: '@example/starlight-plugin',
  hooks: {
    'config:setup'({ addRouteMiddleware }) {
      addRouteMiddleware({
        entrypoint: '@example/starlight-plugin/route-middleware',
      });
    },
  },
};
```

##### Controlling execution order

By default, plugin middleware runs in the order the plugins are added.

Use the optional `order` property if you need more control over when your middleware runs.
Set `order: "pre"` to run before a user’s middleware.
Set `order: "post"` to run after all other middleware.

If two plugins add middleware with the same `order` value, the plugin added first will run first.

#### `astroConfig`

**type:** `AstroConfig`

A read-only copy of the user-supplied [Astro configuration](https://docs.astro.build/en/reference/configuration-reference/).

#### `command`

**type:** `'dev' | 'build' | 'preview'`

The command used to run Starlight:

- `dev` - Project is executed with `astro dev`
- `build` - Project is executed with `astro build`
- `preview` - Project is executed with `astro preview`

#### `isRestart`

**type:** `boolean`

`false` when the dev server starts, `true` when a reload is triggered.
Common reasons for a restart include a user editing their `astro.config.mjs` while the dev server is running.

#### `logger`

**type:** `AstroIntegrationLogger`

An instance of the [Astro integration logger](https://docs.astro.build/en/reference/integrations-reference/#astrointegrationlogger) that you can use to write logs.
All logged messages will be prefixed with the plugin name.

```ts {6}
// plugin.ts
export default {
  name: 'long-process-plugin',
  hooks: {
    'config:setup'({ logger }) {
      logger.info('Starting long process…');
      // Some long process…
    },
  },
};
```

The example above will log a message that includes the provided info message:

```shell
[long-process-plugin] Starting long process…
```

#### `useTranslations`

**type:** `(lang: string) => I18nT`

Call `useTranslations()` with a BCP-47 language tag to generate a utility function that provides access to UI strings for that language.
`useTranslations()` returns an equivalent of the `Astro.locals.t()` API that is available in Astro components.
To learn more about the available APIs, see the [“Using UI translations”](/guides/i18n/#using-ui-translations) guide.

```ts {6}
// plugin.ts
export default {
  name: 'plugin-use-translations',
  hooks: {
    'config:setup'({ useTranslations, logger }) {
      const t = useTranslations('zh-CN');
      logger.info(t('builtWithStarlight.label'));
    },
  },
};
```

The example above will log a message that includes a built-in UI string for the Simplified Chinese language:

```shell
[plugin-use-translations] 基于 Starlight 构建
```

#### `absolutePathToLang`

**type:** `(path: string) => string`

Call `absolutePathToLang()` with an absolute file path to get the language for that file.

This can be particularly useful when adding [remark or rehype plugins](https://docs.astro.build/en/guides/markdown-content/#markdown-plugins) to process Markdown or MDX files.
The [virtual file format](https://github.com/vfile/vfile) used by these plugins includes the [absolute path](https://github.com/vfile/vfile#filepath) of the file being processed, which can be used with `absolutePathToLang()` to determine the language of the file.
The returned language can be used with the [`useTranslations()`](#usetranslations) helper to get UI strings for that language.

For example, given the following Starlight configuration:

```js
starlight({
  title: 'My Docs',
  defaultLocale: 'en',
  locales: {
    // English docs in `src/content/docs/en/`
    en: { label: 'English' },
    // French docs in `src/content/docs/fr/`
    fr: { label: 'Français', lang: 'fr' },
  },
});
```

A plugin can determine the language of a file using its absolute path:

```ts {6-8} /fr/
// plugin.ts
export default {
  name: 'plugin-use-translations',
  hooks: {
    'config:setup'({ absolutePathToLang, useTranslations, logger }) {
      const lang = absolutePathToLang(
        '/absolute/path/to/project/src/content/docs/fr/index.mdx'
      );
      const t = useTranslations(lang);
      logger.info(t('aside.tip'));
    },
  },
};
```

The example above will log a message that includes a built-in UI string for the French language:

```shell
[plugin-use-translations] Astuce
```


================================================
FILE: docs/src/content/docs/reference/route-data.mdx
================================================
---
title: Route Data Reference
description: The full reference documentation for Starlight’s route data object.
---

Starlight’s route data object contains information about the current page.
Learn more about how Starlight’s data model works in the [“Route Data” guide](/guides/route-data/).

In Astro components, access route data from `Astro.locals.starlightRoute`:

```astro {4}
---
// src/components/Custom.astro

const { hasSidebar } = Astro.locals.starlightRoute;
---
```

In [route middleware](/guides/route-data/#customizing-route-data), access route data from the context object passed to your middleware function:

```ts {5}
// src/routeData.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

export const onRequest = defineRouteMiddleware((context) => {
	const { hasSidebar } = context.locals.starlightRoute;
});
```

## `starlightRoute`

The `starlightRoute` object has the following properties:

### `dir`

**Type:** `'ltr' | 'rtl'`

Page writing direction.

### `lang`

**Type:** `string`

BCP-47 language tag for this page’s locale, e.g. `en`, `zh-CN`, or `pt-BR`.

### `locale`

**Type:** `string | undefined`

The base path at which a language is served. `undefined` for root locale slugs.

### `siteTitle`

**Type:** `string`

The site title for this page’s locale.

### `siteTitleHref`

**Type:** `string`

The value for the site title’s `href` attribute, linking back to the homepage, e.g. `/`.
For multilingual sites this will include the current locale, e.g. `/en/` or `/zh-cn/`.

### `id`

**Type:** `string`

The slug for this page.

### `isFallback`

**Type:** `boolean | undefined`

`true` if this page is untranslated in the current language and using fallback content from the default locale.
Only used in multilingual sites.

### `entryMeta`

**Type:** `{ dir: 'ltr' | 'rtl'; lang: string }`

Locale metadata for the page content. Can be different from top-level locale values when a page is using fallback content.

### `entry`

The Astro content collection entry for the current page.
Includes frontmatter values for the current page at `entry.data`.

```ts
entry: {
	data: {
		title: string;
		description: string | undefined;
		// etc.
	}
}
```

Learn more about the shape of this object in [Astro’s Collection Entry Type](https://docs.astro.build/en/reference/modules/astro-content/#collectionentry) reference.

### `sidebar`

**Type:** `SidebarEntry[]`

Site navigation sidebar entries for this page.

### `hasSidebar`

**Type:** `boolean`

Whether or not the sidebar should be displayed on this page.

### `pagination`

**Type:** `{ prev?: Link; next?: Link }`

Links to the previous and next page in the sidebar if enabled.

### `toc`

**Type:** `{ minHeadingLevel: number; maxHeadingLevel: number; items: TocItem[] } | undefined`

Table of contents for this page if enabled.

### `headings`

**Type:** `{ depth: number; slug: string; text: string }[]`

Array of all Markdown headings extracted from the current page.
Use [`toc`](#toc) instead if you want to build a table of contents component that respects Starlight’s configuration options.

### `lastUpdated`

**Type:** `Date | undefined`

JavaScript `Date` object representing when this page was last updated if enabled.

### `editUrl`

**Type:** `URL | undefined`

`URL` object for the address where this page can be edited if enabled.

### `head`

**type:** [`HeadConfig[]`](/reference/configuration/#headconfig)

Array of all tags to include in the `<head>` of the current page.
Includes important tags such as `<title>` and `<meta charset="utf-8">`.

## Utilities

### `defineRouteMiddleware()`

Use the `defineRouteMiddleware()` utility to help type your route middleware module:

```ts "defineRouteMiddleware"
// src/routeData.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

export const onRequest = defineRouteMiddleware((context) => {
	// ...
});
```

### `StarlightRouteData` type

If you are writing code that needs to work with Starlight’s route data, you can import the `StarlightRouteData` type to match the shape of `Astro.locals.starlightRoute`.

In the following example, a `usePageTitleInTOC()` function updates route data to use the current page’s title as the label for the first item in the table of contents, replacing the default “Overview” label.
The `StarlightRouteData` type allows you to check whether the route data changes are valid.

```ts "StarlightRouteData"
// src/route-utils.ts
import type { StarlightRouteData } from '@astrojs/starlight/route-data';

export function usePageTitleInTOC(starlightRoute: StarlightRouteData) {
	const overviewLink = starlightRoute.toc?.items[0];
	if (overviewLink) {
		overviewLink.text = starlightRoute.entry.data.title;
	}
}
```

This function can then be called from a route middleware:

```ts {3,6}
// src/route-middleware.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';
import { usePageTitleInTOC } from './route-utils';

export const onRequest = defineRouteMiddleware((context) => {
	usePageTitleInTOC(context.locals.starlightRoute);
});
```


================================================
FILE: docs/src/content/docs/resources/community-content.mdx
================================================
---
title: Community Content
description: Discover community-produced guides, articles and videos to help you learn and build with Starlight!
---

:::tip[Add your own!]
Have you produced content about Starlight?
Open a PR adding a link to this page!
:::

import { CardGrid, LinkCard } from '@astrojs/starlight/components';

## Articles and Reviews

Here is a collection of posts and articles to learn more about Starlight and other people's experiences:

<CardGrid>
	<LinkCard
		href="https://devm.io/open-source/starlight-astro"
		title="Static Site Generation with Starlight"
		description="“No idea is too big or too small when designing components” — an interview with Chris Swithinbank, Starlight Lead"
	/>
	<LinkCard
		href="https://frontendatscale.com/blog/hybrid-frontend-architecture/"
		title="Hybrid Frontend Architecture with Astro and Starlight"
		description="Maxi Ferreira and Ben Holmes build a docs site with Starlight, TinaCMS, and an interactive API Playground with authentication."
	/>
	<LinkCard
		href="https://www.olets.dev/posts/comparing-docs-site-builders-vuepress-vs-starlight/"
		title="Comparing docs site builders: VuePress vs Starlight"
		description="How do these two frameworks measure up?"
	/>
	<LinkCard
		href="https://astro.build/case-studies/wp-engine/"
		title="Case Study: Slashing Development Costs"
		description="How WP Engine Lowered Development Costs by Over 50% with Astro’s Starlight."
	/>
	<LinkCard
		href="https://maciekpalmowski.dev/blog/building-a-documentation-site-using-astro-starlight/"
		title="Building a documentation site using Astro Starlight"
		description="Maciek Palmowski describes how Patchstack migrated their documentation to Starlight"
	/>
	<LinkCard
		href="https://blog.cloudflare.com/open-source-all-the-way-down-upgrading-our-developer-documentation/"
		title="Open source all the way down"
		description="How Cloudflare used Starlight to upgrade their developer documentation."
	/>
	<LinkCard
		href="https://starlight-changelog.netlify.app/"
		title="Starlight Changelog"
		description="View all releases of the @astrojs/starlight package on a single beautiful page."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/contributing-to-starlight"
		title="Contributing to Starlight"
		description="My personal experience and suggestions for contributing to open-source projects like Starlight."
	/>
</CardGrid>

## Recipes and Guides

Recipes are typically short, focused how-to guides that walk a reader through completing a working example of a specific task. Recipes are a great way to add new features or behavior to your Starlight project by following step-by-step instructions! Other guides might explain concepts related to an area of content, such as using images or working with MDX.

Explore community-produced content maintained by Starlight users:

<CardGrid>
	<LinkCard
		href="https://www.webpro.nl/scraps/versioned-docs-with-starlight-and-vercel"
		title="Versioned documentation with Starlight & Vercel"
		description="A guide to implementing separate versions of documentation for each major version of a project."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-heading-links"
		title="Add links to Starlight headings"
		description="A guide to using a rehype plugin to share links to specific sections of your documentation."
	/>
	<LinkCard
		href="https://blog.otterlord.dev/posts/starlight-sponsors/"
		title="Add sponsors to your Starlight site"
		description="A guide to implement a custom sponsors component in your documentation sidebar."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-og-images"
		title="Add Open Graph images to Starlight"
		description="A guide to generating social images and the corresponding meta tags for your pages."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-third-party-icon-sets"
		title="Use third-party icon sets in Starlight"
		description="A guide to using unplugin-icons to expand the selection of available icons for Starlight."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-custom-html-head"
		title="Edit the HTML head of Starlight pages"
		description="Learn how to add common head content such as web analytics, fonts, and scripts."
	/>
	<LinkCard
		href="https://dev.to/mrrobot/publishing-documentation-with-astro-starlight-691"
		title="Publishing Documentation with Astro Starlight"
		description="Getting started with Starlight documentation."
	/>
	<LinkCard
		href="https://events-3bg.pages.dev/jotter/starlight/"
		title="Enable View Transitions"
		description="Add support for view transitions, client-side routing, and SPA-like navigation to your Starlight documentation site."
	/>
	<LinkCard
		href="https://jamcomments.com/posts/structured-data-with-starlight"
		title="Adding Structured Data to Starlight Pages"
		description="Learn how to build dynamic JSON-LD structured data for your documentation pages."
	/>
	<LinkCard
		href="https://starlight-examples.netlify.app/"
		title="Starlight Examples"
		description="A collection of StackBlitz embeds demonstrating practical ways of doing stuff in Starlight documentation sites."
	/>
	<LinkCard
		href="https://hideoo.dev/notebooks/starlight-plugins-by-example"
		title="Starlight Plugins by Example"
		description="A collection of notes and examples about Starlight plugins and common patterns used to build them."
	/>
	<LinkCard
		href="https://blog.trueberryless.org/blog/starlight-progress-indicator/"
		title="Add a reading progress indicator"
		description="Find out how to add a horizontal reading progress bar to your Starlight site."
	/>
	<LinkCard
		href="https://blog.trueberryless.org/blog/starlight-sidebar-whitespace/"
		title="Apply custom styles to your Starlight sidebar"
		description="Using a little bit of CSS to adjust fonts, colours and more of the Starlight sidebar."
	/>
	<LinkCard
		href="https://blog.trueberryless.org/blog/starlight-dropdown-and-list-together/"
		title="Starlight Topics Dropdown on mobile, List on desktop"
		description="Combine two plugins to have the best of both on desktop and mobile devices."
	/>
	<LinkCard
		href="https://blog.trueberryless.org/blog/starlight-autogenerate-whole-sidebar/"
		title="Processing Starlight sidebars with middleware"
		description="Use route middleware to control sidebar ordering and group labels, inspired by Nuxt Content’s conventions."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-custom-social-links"
		title="Add social links with custom icons to Starlight"
		description="Learn how to use custom icons for social links in Starlight website header."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-paste-images-with-visual-studio-code"
		title="Paste images to Starlight pages with Visual Studio Code"
		description="Improve your Starlight documentation workflow by pasting images to your documentation pages using Visual Studio Code."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-add-diagrams-using-d2"
		title="Add diagrams to your Starlight documentation using D2"
		description="Learn how to use D2 to add diagrams to your Starlight documentation."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-og-images-cloudinary-astro-sdk"
		title="Generate Open Graph images for Starlight using the Cloudinary Astro SDK"
		description="Learn how to use the Cloudinary Astro SDK to generate Open Graph images for your Starlight documentation website."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-list-recent-github-releases"
		title="List recent GitHub releases in Starlight using the Astro Content Layer API"
		description="Learn how to use the Astro Content Layer API to list the recent GitHub releases in a Starlight project."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-sitewide-banner"
		title="Add a sitewide banner to Starlight"
		description="Learn how to create a sitewide banner using Starlight's built-in per-page banner feature."
	/>
	<LinkCard
		href="https://lirantal.com/blog/customizing-astro-starlight-sidebar-gated-content-auth"
		title="Customizing Astro Starlight Sidebar for Gated Content with Authentication"
		description="Secure your course material by using Clerk and SSR to dynamically hide or reveal Starlight sidebar chapters based on user login."
	/>
</CardGrid>

## Video Content

Discover videos and channels with Starlight content, including live streams and educational content.

import YouTubeGrid from '~/components/youtube-grid.astro';

### Official Videos

<YouTubeGrid
	videos={[
		{
			href: 'https://www.youtube.com/watch?v=5u0Ds7wzUeI',
			title: 'Starlight by Astro',
			description: 'Watch the official Starlight launch video',
		},
		{
			href: 'https://www.youtube.com/watch?v=j8K-ESJF814',
			title: 'One year of Starlight!',
			description:
				"Sarah talks about Astro's community-built documentation theme",
		},
	]}
/>

### Community Videos and Streams

<YouTubeGrid
	videos={[
		{
			href: 'https://www.youtube.com/shorts/zjOWezSzd18',
			title: '🌟 SUB 1 MINUTE RUN',
			description: 'Watch Ben launch a new Starlight site in under a minute!',
		},
		{
			href: 'https://www.youtube.com/watch?v=sF6UcV3moZg',
			title: 'Building docs with Starlight and Astro',
			description:
				'Watch Chris and Alex dive into Starlight on Code with CodingCat.dev',
		},
		{
			href: 'https://www.youtube.com/watch?v=sWkkHbwDeQc',
			title: 'Astro Starlight',
			description: 'Introduction to Starlight in under a minute.',
		},
		{
			href: 'https://www.youtube.com/watch?v=-Ki-1E5gNCk',
			title: 'Astro Starlight Documentation Template (build custom app docs!)',
			description: 'Get a new Starlight site up and running in about 5 minutes',
		},
		{
			href: 'https://www.youtube.com/watch?v=12o7WxjAxjM',
			title: 'Include Starlight docs in a Next.js project with proxies',
			description:
				'Set up Starlight as a sub-directory project inside a Next.js website',
		},
		{
			href: 'https://www.youtube.com/watch?v=5pq80drDrNs',
			title: "I Recreated Shadcn's Docs In 30 Minutes With This Amazing Tool",
			description:
				'In this video I go over what makes Starlight so cool and why you may want to give it a try on your next project.',
		},
		{
			href: 'https://www.youtube.com/watch?v=Q1E4Gkt63ko',
			title: 'Astro Starlight and emoji-blast with Chris Swithinbank',
			description:
				"Wherein Chris, the creator of Astro's Starlight framework-on-a-framework, walks me through setting it up for a new emoji-blast website. 🌟 🎇",
		},
	]}
/>


================================================
FILE: docs/src/content/docs/resources/plugins.mdx
================================================
---
title: Plugins and Integrations
description: Discover community tools like plugins and integrations that extend Starlight!
sidebar:
  order: 1
---

:::tip[Add your own!]
Have you built a plugin or a tool for Starlight?
Open a PR adding a link to this page!
:::

## Plugins

[Plugins](/reference/plugins/) can customize Starlight configuration, UI, and behavior, while also being easy to share and reuse.
Extend your site with official plugins supported by the Starlight team and community plugins maintained by Starlight users.

### Official plugins

<CardGrid>
	<LinkCard
		href="/guides/site-search/#algolia-docsearch"
		title="Algolia DocSearch"
		description="Replace Pagefind, the default search provider, with Algolia DocSearch."
	/>
</CardGrid>

### Community plugins

<CardGrid>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-links-validator"
		title="starlight-links-validator"
		description="Check for broken links in your Starlight pages."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-typedoc"
		title="starlight-typedoc"
		description="Generate Starlight pages from TypeScript using TypeDoc."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-blog"
		title="starlight-blog"
		description="Add a blog to your documentation site."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-openapi"
		title="starlight-openapi"
		description="Create documentation pages from OpenAPI/Swagger specifications."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-obsidian"
		title="starlight-obsidian"
		description="Publish Obsidian vaults in your Starlight site."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-image-zoom"
		title="starlight-image-zoom"
		description="Add zoom capabilities to your documentation images."
	/>
	<LinkCard
		href="https://github.com/lorenzolewis/starlight-utils"
		title="starlight-utils"
		description="Extend Starlight with a collection of common utilities."
	/>
	<LinkCard
		href="https://github.com/trueberryless/starlight-view-modes"
		title="starlight-view-modes"
		description="Add different view mode capabilities to your documentation website."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-versions"
		title="starlight-versions"
		description="Version your Starlight documentation pages."
	/>
	<LinkCard
		href="https://inox-tools.fryuni.dev/star-warp"
		title="star-warp"
		description="Warp-drive through search results in your documentation."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-heading-badges"
		title="starlight-heading-badges"
		description="Add badges to your Markdown and MDX headings."
	/>
	<LinkCard
		href="https://github.com/Fevol/starlight-site-graph"
		title="starlight-site-graph"
		description="Add an interactive site graph inside your page’s sidebar."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-sidebar-topics"
		title="starlight-sidebar-topics"
		description="Split your documentation into different sections, each with its own sidebar."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-cooler-credit"
		title="starlight-cooler-credit"
		description="Add a nice credit to Starlight or Astro at the bottom of the table of contents."
	/>
	<LinkCard
		href="https://github.com/dragomano/starlight-giscus"
		title="starlight-giscus"
		description="Add Giscus comments to your docs site."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-videos"
		title="starlight-videos"
		description="Enhance your documentation with video guides and courses."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-kbd"
		title="starlight-kbd"
		description="Document keyboard shortcuts with ease."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-auto-sidebar"
		title="starlight-auto-sidebar"
		description="Tweak your autogenerated sidebar groups."
	/>
	<LinkCard
		href="https://github.com/delucis/starlight-llms-txt"
		title="starlight-llms-txt"
		description="Add llms.txt to your documentation site based on llmstxt.org."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-toc-overview-customizer"
		title="starlight-toc-overview-customizer"
		description="Tweak Starlight’s table of contents with customizable overview title."
	/>
	<LinkCard
		href="https://delucis.github.io/starlight-markdown-blocks/"
		title="starlight-markdown-blocks"
		description="Extend Starlight’s Markdown asides syntax with custom block types."
	/>
	<LinkCard
		href="https://github.com/WindMillCode/starlight-fullview-mode"
		title="starlight-fullview-mode"
		description="Collapse sidebars and expand content for a fullscreen experience."
	/>
	<LinkCard
		href="https://github.com/frostybee/starlight-scroll-to-top"
		title="starlight-scroll-to-top"
		description="Add a scroll-to-top button to your documentation site."
	/>
	<LinkCard
		href="https://github.com/frostybee/starlight-codeblock-fullscreen"
		title="starlight-codeblock-fullscreen"
		description="Add fullscreen toggle functionality to Expressive Code blocks in your documentation."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-auto-drafts"
		title="starlight-auto-drafts"
		description="Tweak draft pages default behavior and automatically remove sidebar links to draft pages in production mode."
	/>
	<LinkCard
		href="https://github.com/corsfix/starlight-contextual-menu"
		title="starlight-contextual-menu"
		description="Add a contextual menu to your Starlight documentation."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-changelogs"
		title="starlight-changelogs"
		description="Display changelogs alongside your project documentation."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-github-alerts"
		title="starlight-github-alerts"
		description="Render GitHub alerts as Starlight asides."
	/>
	<LinkCard
		href="https://github.com/dlcastillop/starlight-page-actions"
		title="starlight-page-actions"
		description="Adds page action buttons to your documentation."
	/>
	<LinkCard
		href="https://github.com/typesense/starlight-docsearch-typesense"
		title="starlight-docsearch-typesense"
		description="A Typesense-powered alternative to the official Algolia DocSearch plugin."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-sidebar-swipe/"
		title="starlight-sidebar-swipe"
		description="Make the left sidebar swipeable on mobile devices like Discord Mobile."
	/>
	<LinkCard
		href="https://github.com/Rettend/starlight-plugin-icons"
		title="starlight-plugin-icons"
		description="Add icons to Astro Starlight: sidebar, codeblocks, filetree."
	/>
	<LinkCard
		href="https://github.com/dlcastillop/starlight-ui-tweaks"
		title="starlight-ui-tweaks"
		description="Extends core UI components with custom navigation links, ads, marketing footers, and a cleaner theme toggle."
	/>
	<LinkCard
		href="https://frostybee.github.io/starlight-tags/"
		title="starlight-tags"
		description="Add tags to your Starlight documentation pages for content organization and discovery."
	/>
	<LinkCard
		href="https://github.com/dionysuzx/starlight-copy-button"
		title="starlight-copy-button"
		description="Copy full docs page Markdown with a polished button in the page title."
	/>
	<LinkCard
		href="https://frostybee.github.io/starlight-telescope/"
		title="starlight-telescope"
		description="Quickly navigate to any page in your Starlight docs with fuzzy search and keyboard-first navigation."
	/>
	<LinkCard
		href="https://frostybee.github.io/starlight-announcement/"
		title="starlight-announcement"
		description="Add enhanced announcement banners with dismissibility, variants, scheduling, and page targeting for your Starlight docs."
	/>
</CardGrid>

## Community tools and integrations

import { CardGrid, LinkCard } from '@astrojs/starlight/components';

These community tools and integrations can be used to add features to your Starlight site.

<CardGrid>
	<LinkCard
		href="https://www.feelback.dev/blog/new-astro-starlight-integration/"
		title="FeelBack"
		description="Add a user feedback system to your docs pages."
	/>
	<LinkCard
		href="https://github.com/val-town/notion-to-astro"
		title="notion-to-astro"
		description="Convert Notion exports to Astro Starlight docs"
	/>
	<LinkCard
		href="https://github.com/mattjennings/astro-live-code"
		title="astro-live-code"
		description="Render your MDX code blocks as interactive components"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-i18n"
		title="starlight-i18n"
		description="Visual Studio Code extension to help translate Starlight pages."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-package-managers"
		title="starlight-package-managers"
		description="Quickly display npm related commands for multiple package managers."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-showcases"
		title="starlight-showcases"
		description="Set of Starlight components to author showcase pages."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/generator-starlight-plugin"
		title="@hideoo/starlight-plugin"
		description="A generator to quickly scaffold Starlight plugins."
	/>
	<LinkCard
		href="https://github.com/Linkerin/starlight-to-pdf"
		title="starlight-to-pdf"
		description="A CLI tool to convert Starlight websites into PDF files."
	/>
	<LinkCard
		href="https://github.com/joesaby/astro-plantuml"
		title="astro-plantuml"
		description="Render PlantUML content in Markdown code blocks."
	/>
	<LinkCard
		href="https://github.com/joesaby/astro-mermaid"
		title="astro-mermaid"
		description="Client-side render Mermaid content in Markdown code blocks."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/astro-d2"
		title="astro-d2"
		description="Transform D2 Markdown code blocks into diagrams."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-links"
		title="starlight-links"
		description="Visual Studio Code extension providing IntelliSense for Starlight Markdown and MDX content links."
	/>
	<LinkCard
		href="https://docs.contentisland.net/templates/starlight/"
		title="contentisland-cli"
		description="Connect and sync your Starlight project to Content Island Headless CMS to edit and manage your documentation."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-sidebar-topics-dropdown"
		title="starlight-sidebar-topics-dropdown"
		description="Split your docs page into multiple subpages and switch between them with a dropdown menu in the sidebar."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-save-file-component"
		title="starlight-save-file-component"
		description="Quickly display a link to some download asset on your Starlight site."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-contributor-list"
		title="starlight-contributor-list"
		description="Display a list of all contributors to your project."
	/>
</CardGrid>


================================================
FILE: docs/src/content/docs/resources/showcase.mdx
================================================
---
title: Starlight Showcase
description: Discover sites built with Starlight!
sidebar:
  label: Site Showcase
---

:::tip[Add your own!]
Have you built a Starlight site?
[Open a PR](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md#showcase) adding a link to this page!
:::

## Sites

import ShowcaseSites from '~/components/showcase-sites.astro';

Starlight is already being used in production. These are some of the sites around the web:

<ShowcaseSites />

See all the [public project repos using Starlight on GitHub](https://github.com/withastro/starlight/network/dependents).


================================================
FILE: docs/src/content/docs/resources/themes.mdx
================================================
---
title: Themes
description: Style your docs with a community theme for Starlight
tableOfContents: false
sidebar:
  order: 2
head:
  - tag: style
    content: |
      body { --sl-content-width: 66.75rem; }
---

import ThemeGrid from '~/components/theme-grid.astro';

A theme is a Starlight plugin that changes the visual appearance of a site with [custom CSS](/guides/css-and-tailwind/), [component overrides](/guides/overriding-components/), or other new features.

## Community Themes

Install a theme built by the community to quickly customize the look and feel of your site.

Preview a list of all themes below or try them out interactively on the [Starlight Themes demo site](https://starlight-themes.netlify.app/).

<ThemeGrid
	labels={{
		/** Accessible label for the theme toggle. */
		legend: 'Preview',
		/** Accessible label for the dark color scheme variant. */
		dark: 'Dark',
		/** Accessible label for the light color scheme variant. */
		light: 'Light',
	}}
	themes={[
		{
			title: 'Starlight Rapide',
			description:
				'Starlight theme inspired by the Visual Studio Code Vitesse theme.',
			href: 'https://starlight-theme-rapide.vercel.app/',
			previews: { light: 'rapide-light.png', dark: 'rapide-dark.png' },
		},
		{
			title: 'Starlight Obsidian',
			description:
				'Starlight theme inspired by the style of Obsidian Publish sites.',
			href: 'https://fevol.github.io/starlight-theme-obsidian/',
			previews: { light: 'obsidian-light.png', dark: 'obsidian-dark.png' },
		},
		{
			title: 'Catppuccin for Starlight',
			description: 'Soothing pastel theme for Starlight.',
			href: 'https://starlight.catppuccin.com/',
			previews: { light: 'catppuccin-light.png', dark: 'catppuccin-dark.png' },
		},
		{
			title: 'Ion',
			description: 'A sleek, modern theme for Starlight.',
			href: 'https://louisescher.github.io/starlight-ion-theme/',
			previews: { light: 'ion-light.png', dark: 'ion-dark.png' },
		},
		{
			title: 'Starlight Black',
			description: 'Starlight theme inspired by shadcn docs.',
			href: 'https://starlight-theme-black.vercel.app/',
			previews: { light: 'black-light.png', dark: 'black-dark.png' },
		},
		{
			title: 'Starlight Flexoki',
			description:
				'A warm and friendly theme based on the Flexoki color palette.',
			href: 'https://delucis.github.io/starlight-theme-flexoki/',
			previews: { light: 'flexoki-light.png', dark: 'flexoki-dark.png' },
		},
		{
			title: 'Starlight Nova',
			description: 'A modern and beautiful theme for Starlight.',
			href: 'https://starlight-theme-nova.pages.dev/',
			previews: { light: 'nova-light.png', dark: 'nova-dark.png' },
		},
		{
			title: 'Starlight Next.js',
			description: 'Starlight theme inspired by the Next.js docs.',
			href: 'https://starlight-theme-next.trueberryless.org/',
			previews: { light: 'nextjs-light.png', dark: 'nextjs-dark.png' },
		},
		{
			title: 'Starlight Galaxy',
			description:
				'An Astro Starlight theme tailored for publishing documentation and educational content.',
			href: 'https://frostybee.github.io/starlight-theme-galaxy/',
			previews: { light: 'galaxy-light.png', dark: 'galaxy-dark.png' },
		},
		{
			title: 'Starlight Page',
			description:
				'An intuitive, modern Starlight theme with smooth, float-in animations.',
			href: 'https://pelagornis-page.netlify.app/',
			previews: { light: 'page-light.png', dark: 'page-dark.png' },
		},
		{
			title: 'Starlight Gruvbox',
			description: 'Retro groove theme for Starlight',
			href: 'https://starlight-theme-gruvbox.otterlord.dev/',
			previews: { light: 'gruvbox-light.png', dark: 'gruvbox-dark.png' },
		},
		{
			title: 'Starlight Six',
			description:
				'Clean and modern Astro.js Starlight theme by Six Technology ',
			href: 'https://six-tech.github.io/Six.StarlightTheme/',
			previews: { light: 'six-light.png', dark: 'six-dark.png' },
		},
		{
			title: 'Starlight Vintage',
			description:
				'Starlight theme heavily inspired by the timeless design of the legacy Astro documentation.',
			href: 'https://starlight-theme-vintage.netlify.app/',
			previews: { light: 'vintage-light.png', dark: 'vintage-dark.png' },
		},
		{
			title: 'Starlight Rosé Pine',
			description: 'Soho vibes for Starlight.',
			href: 'https://starlight-theme-rose-pine.trueberryless.org/',
			previews: { light: 'rose-pine-light.png', dark: 'rose-pine-dark.png' },
		},
	]}
/>

:::tip[Add your own!]
Have you built a Starlight theme?
[Open a PR](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md#themes) adding your theme to this page!
:::


================================================
FILE: docs/src/content/docs/ru/404.md
================================================
---
title: Не найдено
template: splash
editUrl: false
lastUpdated: false
hero:
  title: '404'
  tagline: <strong>Хьюстон, у нас проблемы.</strong> Мы не смогли найти эту страницу.<br>Проверьте URL или попробуйте использовать поиск.
  actions:
    - text: На главную
      icon: right-arrow
      link: /ru/
      variant: primary
---


================================================
FILE: docs/src/content/docs/ru/components/asides.mdx
================================================
---
title: Вставки
description: Узнайте, как использовать вставки в Starlight для отображения второстепенной информации рядом с основным содержимым страницы.
---

import { Aside } from '@astrojs/starlight/components';

Для отображения второстепенной информации рядом с основным содержимым страницы используйте компонент `<Aside>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<Aside slot="preview">
    Включите несущественную, дополнительную информацию в `<Aside>`.
</Aside>

</Preview>

## Импорт

```tsx
import { Aside } from '@astrojs/starlight/components';
```

## Использование

Отображайте вставки (также известные как «наставления» или «призывы») с помощью компонента `<Aside>`.

`<Aside>` может иметь дополнительный атрибут [`type`](#type), который управляет цветом, значком и заголовком по умолчанию.

<Preview>

````mdx
import { Aside } from '@astrojs/starlight/components';

<Aside>Некоторый контент.</Aside>

<Aside type="caution">Некоторое предостережение.</Aside>

<Aside type="tip">

Другой контент также поддерживается.

```js
// Например, фрагмент кода.
```

</Aside>

<Aside type="danger">Никому не сообщайте свой пароль.</Aside>
````

<Fragment slot="markdoc">

````markdoc
{% aside %}
Некоторый контент.
{% /aside %}

{% aside type="caution" %}
Некоторое предостережение.
{% /aside %}

{% aside type="tip" %}
Другой контент также поддерживается.

```js
// Например, фрагмент кода.
```
{% /aside %}

{% aside type="danger" %}
Никому не сообщайте свой пароль.
{% /aside %}
````

</Fragment>

<Fragment slot="preview">

    <Aside>Некоторый контент.</Aside>

    <Aside type="caution">Некоторое предостережение.</Aside>

    <Aside type="tip">

    Другой контент также поддерживается.

    ```js
    // Например, фрагмент кода.
    ```

    </Aside>

    <Aside type="danger">Никому не сообщайте свой пароль.</Aside>

</Fragment>

</Preview>

Starlight также предоставляет собственный синтаксис для рендеринга в Markdown и MDX в качестве альтернативы компоненту `<Aside>`.
Подробную информацию о пользовательском синтаксисе см. в руководстве [Создание контента в Markdown](/ru/guides/authoring-content/#вставки).

### Использование пользовательских заголовков

Переопределяйте стандартные заголовки вставок, используя атрибут [`title`](#title).

<Preview>

```mdx 'title="Осторожно!"'
import { Aside } from '@astrojs/starlight/components';

<Aside type="caution" title="Осторожно!">
	Предупреждение *с* пользовательским заголовком.
</Aside>
```

<Fragment slot="markdoc">

```markdoc 'title="Осторожно!"'
{% aside type="caution" title="Осторожно!" %}
Предупреждение *с* пользовательским заголовком.
{% /aside %}
```

</Fragment>

<Aside slot="preview" type="caution" title="Осторожно!">
	Предупреждение *с* пользовательским заголовком.
</Aside>

</Preview>

### Использование пользовательских иконок

Переопределяйте стандартные иконки боковой панели, используя атрибут [`icon`](#icon) с именем одной из [встроенных иконок Starlight](/ru/reference/icons/#все-иконки).

<Preview>

```mdx 'icon="starlight"'
import { Aside } from '@astrojs/starlight/components';

<Aside type="tip" icon="starlight">
	Подсказка *с* пользовательской иконкой.
</Aside>
```

<Fragment slot="markdoc">

```markdoc 'icon="starlight"'
{% aside type="tip" icon="starlight" %}
Подсказка *с* пользовательской иконкой.
{% /aside %}
```

</Fragment>

<Aside slot="preview" type="tip" icon="starlight">
	Подсказка *с* пользовательской иконкой.
</Aside>

</Preview>

## Параметры `<Aside>`

**Реализация:** [`Aside.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Aside.astro)

Компонент `<Aside>` принимает следующие параметры:

### `type`

**тип:** `'note' | 'tip' | 'caution' | 'danger'`  
**по умолчанию:** `'note'`

Тип вставки для отображения:

- `note` (по умолчанию), вставка синего цвета, с информационной иконкой.
- `tip`, вставка фиолетового цвета, с иконкой ракеты.
- `caution`, вставка жёлтого цвета, с треугольной предупреждающей иконкой.
- `danger`, вставка красного цвета, с восьмиугольнаой предупреждающей иконкой.

### `title`

**тип:** `string`

Заголовок вставки для отображения.
Если `title` не установлен, будет использоваться заголовок по умолчанию для текущего `type` вставки.

### `icon`

**тип:** [`StarlightIcon`](/ru/reference/icons/#тип-starlighticon)

Вставка может включать атрибут `icon`, содержащий имя одной из [встроенных иконок Starlight](/ru/reference/icons/#все-иконки).


================================================
FILE: docs/src/content/docs/ru/components/badges.mdx
================================================
---
title: Значки
description: Узнайте, как использовать значки в Starlight для отображения дополнительной информации.
---

import { Badge } from '@astrojs/starlight/components';

Для отображения небольших фрагментов информации, таких как статус или категория, используйте компонент `<Badge>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<Badge slot="preview" text="Новинка" />

</Preview>

## Импорт

```tsx
import { Badge } from '@astrojs/starlight/components';
```

## Использование

Отображайте значки с помощью компонента `<Badge>`, с передачей желаемого содержимого через атрибут [`text`](#text).

По умолчанию значок будет использовать акцентный цвет темы вашего сайта.
Чтобы использовать встроенный цвет значка, установите для атрибута [`variant`](#variant) одно из поддерживаемых значений.

<Preview>

```mdx
import { Badge } from '@astrojs/starlight/components';

- <Badge text="Примечание" variant="note" />
- <Badge text="Успешно" variant="success" />
- <Badge text="Совет" variant="tip" />
- <Badge text="Внимание" variant="caution" />
- <Badge text="Опасность" variant="danger" />
```

<Fragment slot="markdoc">

```markdoc
- {% badge text="Примечание" variant="note" /%}
- {% badge text="Успешно" variant="success" /%}
- {% badge text="Совет" variant="tip" /%}
- {% badge text="Внимание" variant="caution" /%}
- {% badge text="Опасность" variant="danger" /%}
```

</Fragment>

<Fragment slot="preview">
	- <Badge text="Примечание" variant="note" />
	- <Badge text="Успешно" variant="success" />
	- <Badge text="Совет" variant="tip" />
	- <Badge text="Внимание" variant="caution" />
	- <Badge text="Опасность" variant="danger" />
</Fragment>

</Preview>

### Использование разных размеров

Используйте атрибут [`size`](#size) для управления размером текста значка.

<Preview>

```mdx /size="\w+"/
import { Badge } from '@astrojs/starlight/components';

- <Badge text="Новинки" size="small" />
- <Badge text="Новинки и улучшения" size="medium" />
- <Badge text="Новинки, улучшения и другое" size="large" />
```

<Fragment slot="markdoc">

```markdoc /size="\w+"/
- {% badge text="Новинки" size="small" /%}
- {% badge text="Новинки и улучшения" size="medium" /%}
- {% badge text="Новинки, улучшения и другое" size="large" /%}
```

</Fragment>

<Fragment slot="preview">
	- <Badge text="Новинки" size="small" />
	- <Badge text="Новинки и улучшения" size="medium" />
	- <Badge text="Новинки, улучшения и другое" size="large" />
</Fragment>

</Preview>

### Настройка значков

Настраивайте значки, используя другие атрибуты `<span>`, такие как `class` или `style`, с помощью пользовательского CSS.

<Preview>

```mdx "style={{ fontStyle: 'italic' }}"
import { Badge } from '@astrojs/starlight/components';

<Badge text="Свой текст" variant="success" style={{ fontStyle: 'italic' }} />
```

<Fragment slot="markdoc">

```markdoc 'style="font-style: italic;"'
{% badge text="Свой текст" variant="success" style="font-style: italic;" /%}
```

</Fragment>

<Badge
	slot="preview"
	text="Свой текст"
	variant="success"
	style={{ fontStyle: 'italic' }}
/>

</Preview>

## Параметры `<Badge>`

**Реализация:** [`Badge.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Badge.astro)

Компонент `<Badge>` принимает следующие параметры, а также любые [другие атрибуты `<span>`](https://developer.mozilla.org/ru/docs/Web/HTML/Global_attributes):

### `text`

**обязательный**  
**тип:** `string`

Текстовое содержимое для отображения в значке.

### `variant`

**тип:** `'note' | 'danger' | 'success' | 'caution' | 'tip' | 'default'`  
**по умолчанию:** `'default'`

Вариант цвета значка для использования: `note` (синий), `tip` (фиолетовый), `danger` (красный), `caution` (оранжевый), `success` (зелёный) или `default` (акцентный цвет темы).

### `size`

**тип:** `'small' | 'medium' | 'large'`

Определяет размер отображаемого значка.


================================================
FILE: docs/src/content/docs/ru/components/card-grids.mdx
================================================
---
title: Карточные сетки
description: Узнайте, как обернуть несколько карточек в сетку в Starlight.
sidebar:
  order: 4
---

import { Card, CardGrid, LinkCard } from '@astrojs/starlight/components';

Чтобы обернуть несколько компонентов [`<Card>`](/ru/components/cards/) или [`<LinkCard>`](/ru/components/link-cards/) в сетку, используйте компонент `<CardGrid>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<CardGrid slot="preview">
	<Card title="Звёзды" icon="star">
		Сириус, Вега, Бетельгейзе
	</Card>
	<Card title="Луны" icon="moon">
		Ио, Европа, Ганимед
	</Card>
</CardGrid>

</Preview>

## Импорт

```tsx
import { CardGrid } from '@astrojs/starlight/components';
```

## Использование

### Группировка карточек

Отображайте несколько компонентов [`<Card>`](/ru/components/cards/) рядом друг с другом при наличии свободного места, группируя их с помощью компонента `<CardGrid>`.

<Preview>

```mdx {3,10}
import { Card, CardGrid } from '@astrojs/starlight/components';

<CardGrid>
	<Card title="Зацените это" icon="open-book">
		Интересный контент, который вы хотите выделить.
	</Card>
	<Card title="Другая фича" icon="information">
		Дополнительная информация, которой вы хотите поделиться.
	</Card>
</CardGrid>
```

<Fragment slot="markdoc">

```markdoc {1,9}
{% cardgrid %}
{% card title="Зацените это" icon="open-book" %}
Интересный контент, который вы хотите выделить.
{% /card %}

{% card title="Другая фича" icon="information" %}
Дополнительная информация, которой вы хотите поделиться.
{% /card %}
{% /cardgrid %}
```

</Fragment>

<CardGrid slot="preview">
	<Card title="Зацените это" icon="open-book">
		Интересный контент, который вы хотите выделить.
	</Card>
	<Card title="Другая фича" icon="information">
		Дополнительная информация, которой вы хотите поделиться.
	</Card>
</CardGrid>

</Preview>

### Группировка карточек-ссылок

Отображайте несколько компонентов [`<LinkCard>`](/ru/components/link-cards/) рядом друг с другом при наличии свободного места, группируя их с помощью компонента `<CardGrid>`.

<Preview>

```mdx {3,6}
import { LinkCard, CardGrid } from '@astrojs/starlight/components';

<CardGrid>
	<LinkCard
		title="Создание контента в Markdown"
		href="/ru/guides/authoring-content/"
	/>
	<LinkCard title="Компоненты" href="/ru/components/using-components/" />
</CardGrid>
```

<Fragment slot="markdoc">

```markdoc {1,5}
{% cardgrid %}
{% linkcard title="Создание контента в Markdown" href="/ru/guides/authoring-content/" /%}

{% linkcard title="Компоненты" href="/ru/components/using-components/" /%}
{% /cardgrid %}
```

</Fragment>

<CardGrid slot="preview">
	<LinkCard
		title="Создание контента в Markdown"
		href="/ru/guides/authoring-content/"
	/>
	<LinkCard title="Компоненты" href="/ru/components/using-components/" />
</CardGrid>

</Preview>

### Смещение карточек

Сместите второй столбец сетки по вертикали, чтобы добавить визуальный интерес, добавив атрибут [`stagger`](#stagger) к компоненту `<CardGrid>`.

Этот атрибут полезен на главной странице для отображения ключевых особенностей вашего проекта.

<Preview>

```mdx "stagger"
import { Card, CardGrid } from '@astrojs/starlight/components';

<CardGrid stagger>
	<Card title="Зацените это" icon="open-book">
		Интересный контент, который вы хотите выделить.
	</Card>
	<Card title="Другая фича" icon="information">
		Дополнительная информация, которой вы хотите поделиться.
	</Card>
</CardGrid>
```

<Fragment slot="markdoc">

```markdoc "stagger=true"
{% cardgrid stagger=true %}
{% card title="Зацените это" icon="open-book" %}
Интересный контент, который вы хотите выделить.
{% /card %}

{% card title="Другая фича" icon="information" %}
Дополнительная информация, которой вы хотите поделиться.
{% /card %}
{% /cardgrid %}
```

</Fragment>

<CardGrid slot="preview" stagger>
	<Card title="Зацените это" icon="open-book">
		Интересный контент, который вы хотите выделить.
	</Card>
	<Card title="Другая фича" icon="information">
		Дополнительная информация, которой вы хотите поделиться.
	</Card>
</CardGrid>

</Preview>

## Параметры `<CardGrid>`

**Реализация:** [`CardGrid.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/CardGrid.astro)

Компонент `<CardGrid>` принимает следующие параметры:

### `stagger`

**тип:** `boolean`

Определяет, нужно ли перемешивать карты в сетке или нет.


================================================
FILE: docs/src/content/docs/ru/components/cards.mdx
================================================
---
title: Карточки
description: Узнайте, как использовать карточки в Starlight для отображения содержимого в прямоугольных блоках.
sidebar:
  order: 2
---

import { Card } from '@astrojs/starlight/components';

Для отображения контента в блоке со стилями Starlight используя компонент `<Card>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<Card slot="preview" title="Луны" icon="moon">
	Ио, Европа, Ганимед
</Card>

</Preview>

## Импорт

```tsx
import { Card } from '@astrojs/starlight/components';
```

## Использование

Отображайте карточки с помощью компонента `<Card>`, используя атрибут [`title`](#title) для добавления заголовка.

<Preview>

```mdx
import { Card } from '@astrojs/starlight/components';

<Card title="Зацените это">Интересный контент, который хочется выделить.</Card>
```

<Fragment slot="markdoc">

```markdoc
{% card title="Зацените это" %}
Интересный контент, который хочется выделить.
{% /card %}
```

</Fragment>

<Card slot="preview" title="Зацените это">
	Интересный контент, который хочется выделить.
</Card>

</Preview>

### Добавление иконок

Включите иконку в карточку, используя атрибут [`icon`](#icon), содержащий имя [одной из встроенных иконок Starlight](/ru/reference/icons/#все-иконки).

<Preview>

```mdx 'icon="star"'
import { Card } from '@astrojs/starlight/components';

<Card title="Звёзды" icon="star">
	Сириус, Вега, Бетельгейзе
</Card>
```

<Fragment slot="markdoc">

```markdoc 'icon="star"'
{% card title="Звёзды" icon="star" %}
Сириус, Вега, Бетельгейзе
{% /card %}
```

</Fragment>

<Card slot="preview" title="Звёзды" icon="star">
	Сириус, Вега, Бетельгейзе
</Card>

</Preview>

### Группировка карточек

Отображайте несколько карточек рядом друг с другом при наличии свободного места, группируя их с помощью компонента [`<CardGrid>`](/ru/components/card-grids/).
Пример смотрите в статье [Группировка карточек](/ru/components/card-grids/#группировка-карточек).

## Параметры `<Card>`

**Реализация:** [`Card.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Card.astro)

Компонент `<Card>` принимает следующие параметры:

### `title`

**обязательный**  
**тип:** `string`

Заголовок карточки для отображения.

### `icon`

**тип:** `string`

Карточка может содержать атрибут `icon`, содержащий имя [одной из встроенных иконок Starlight](/ru/reference/icons/#все-иконки).


================================================
FILE: docs/src/content/docs/ru/components/code.mdx
================================================
---
title: Код
description: Узнайте, как отображать код с подсветкой синтаксиса в Starlight без блоков кода Markdown.
---

import { Code } from '@astrojs/starlight/components';

Компонент `<Code>` отображает код с подсветкой синтаксиса.
Это полезно, когда использование [блоков кода Markdown](/ru/guides/authoring-content/#блоки-кода) невозможно, например, для отображения данных, поступающих из внешних источников, таких как файлы, базы данных или API.

import Preview from '~/components/component-preview.astro';

<Preview>

<Code
	slot="preview"
	code={`## Добро пожаловать

Привет из **космоса**!`}
lang="md"
title="example.md"
ins={3}
/>

</Preview>

## Импорт

```tsx
import { Code } from '@astrojs/starlight/components';
```

## Использование

Используйте компонент `<Code>` для отображения кода с подсветкой синтаксиса, например, при отображении кода, полученного из внешних источников.

См. главу [Компонент кода](https://expressive-code.com/key-features/code-component/) в документации Expressive Code для получения полной информации о параметрах, которые поддерживает `<Code>`.

<Preview>

```mdx
import { Code } from '@astrojs/starlight/components';

export const exampleCode = `console.log('Это может быть файл или CMS!');`;
export const fileName = 'example.js';
export const highlights = ['файл', 'CMS'];

<Code code={exampleCode} lang="js" title={fileName} mark={highlights} />
```

<Fragment slot="markdoc">

```markdoc
{% code
   code="console.log('Это может быть файл или CMS!');"
   lang="js"
   title="example.js"
   meta="'файл' 'CMS'" /%}
```

</Fragment>

export const exampleCode = `console.log('Это может быть файл или CMS!');`;
export const fileName = 'example.js';
export const highlights = ['файл', 'CMS'];

<Code
	slot="preview"
	code={exampleCode}
	lang="js"
	title={fileName}
	mark={highlights}
/>

</Preview>

### Отображение импортированного кода

Используйте [суффикс `?raw`](https://vite.dev/guide/assets#importing-asset-as-string) в MDX-файлах и компонентах Astro, чтобы импортировать любой файл кода в виде строки.
Затем можно передать эту импортированную строку компоненту `<Code>`, чтобы включить её на свою страницу.

<Preview>

```mdx "?raw"
# src/content/docs/example.mdx

import { Code } from '@astrojs/starlight/components';
import importedCode from '/tsconfig.json?raw';

<Code code={importedCode} lang="json" title="tsconfig.json" />
```

import importedCode from '../../../../../../examples/basics/tsconfig.json?raw';

<Code slot="preview" code={importedCode} lang="json" title="tsconfig.json" />

</Preview>

## Параметры `<Code>`

**Реализация:** [`Code.astro`](https://github.com/expressive-code/expressive-code/blob/main/packages/astro-expressive-code/components/Code.astro)

Компонент `<Code>` принимает все параметры, описанные в документации [Компонент кода](https://expressive-code.com/key-features/code-component/#available-props) Expressive Code.


================================================
FILE: docs/src/content/docs/ru/components/file-tree.mdx
================================================
---
title: Дерево файлов
description: Узнайте, как отобразить структуру каталога с помощью значков файлов и сворачиваемых подкаталогов в Starlight.
---

import { FileTree } from '@astrojs/starlight/components';

Для отображения структуры каталога с иконками файлов и сворачиваемыми подкаталогами используйте компонент `<FileTree>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<FileTree slot="preview">

- astro.config.mjs — **важный** файл
- package.json
- README.md
- src
  - components
    - **Header.astro**
  - …
- pages/

</FileTree>

</Preview>

## Импорт

```tsx
import { FileTree } from '@astrojs/starlight/components';
```

## Использование

Отображайте дерево файлов с иконками файлов и сворачиваемыми подкаталогами с помощью компонента `<FileTree>`.

Укажите структуру ваших файлов и каталогов с помощью [неупорядоченного списка Markdown](https://www.markdownguide.org/basic-syntax/#unordered-lists) внутри `<FileTree>`.
Создайте подкаталог с помощью вложенного списка или добавьте `/` в конец элемента списка, чтобы отобразить его как каталог без определённого содержимого.

<Preview>

```mdx
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- astro.config.mjs
- package.json
- src
  - components
    - Header.astro
    - Title.astro
  - pages/

</FileTree>
```

<Fragment slot="markdoc">

```markdoc
{% filetree %}
- astro.config.mjs
- package.json
- src
  - components
    - Header.astro
    - Title.astro
  - pages/
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- astro.config.mjs
- package.json
- src
  - components
    - Header.astro
    - Title.astro
  - pages/

</FileTree>

</Preview>

### Выделение элементов

Выделите файл или каталог, сделав его имя жирным, например: `**README.md**`.

<Preview>

```mdx {7}
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src
  - components
    - **Header.astro**
    - Title.astro

</FileTree>
```

<Fragment slot="markdoc">

```markdoc {4}
{% filetree %}
- src
  - components
    - **Header.astro**
    - Title.astro
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- src
  - components
    - **Header.astro**
    - Title.astro

</FileTree>

</Preview>

### Добавление комментариев

Добавьте комментарий к файлу или каталогу с помощью дополнительного текста после имени.
В комментариях поддерживается встроенное форматирование Markdown, такое как полужирное и курсивное начертание.

<Preview>

```mdx {7}
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src
  - components
    - Header.astro — **важный** файл
    - Title.astro

</FileTree>
```

<Fragment slot="markdoc">

```markdoc {4}
{% filetree %}
- src
  - components
    - Header.astro — **важный** файл
    - Title.astro
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- src
  - components
    - Header.astro — **важный** файл
    - Title.astro

</FileTree>

</Preview>

### Добавление заглушек

Добавьте заглушки файлов и каталогов, используя в качестве имени либо `...`, либо `_`.
Это может быть полезно для указания читателю, что папка должна содержать больше элементов, не указывая их все в явном виде.

<Preview>

```mdx {8}
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src
  - components
    - Header.astro
    - …

</FileTree>
```

<Fragment slot="markdoc">

```markdoc {5}
{% filetree %}
- src
  - components
    - Header.astro
    - …
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- src
  - components
    - Header.astro
    - …

</FileTree>

</Preview>

### Экранирование специальных символов

Экранируйте специальные символы, такие как нижнее подчёркивание или пробелы в именах файлов, заключая имя файла в обратные кавычки.

<Preview>

```mdx
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- `__init__.py`
- `Hello world.txt`
- **`READ ME FIRST.md`**

</FileTree>
```

<Fragment slot="markdoc">

```markdoc
{% filetree %}
- `__init__.py`
- `Hello world.txt`
- **`READ ME FIRST.md`**
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- `__init__.py`
- `Hello world.txt`
- **`READ ME FIRST.md`**

</FileTree>

</Preview>

## Параметры `<FileTree>`

**Реализация:** [`FileTree.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/FileTree.astro)

Компонент `<FileTree>` не принимает никаких параметров.


================================================
FILE: docs/src/content/docs/ru/components/icons.mdx
================================================
---
title: Иконки
description: Узнайте, как отображать иконки в Starlight.
---

import { Icon } from '@astrojs/starlight/components';

Для отображения иконок из [встроенного набора Starlight](/ru/reference/icons/#все-иконки) используйте компонент `<Icon>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<Icon
	slot="preview"
	name="open-book"
	color="var(--sl-color-text-accent)"
	size="4rem"
/>

</Preview>

## Импорт

```tsx
import { Icon } from '@astrojs/starlight/components';
```

## Использование

Отображайте иконки с помощью компонента `<Icon>`.
Иконка требует указания атрибута [`name`](#name) с именем [одной из встроенных иконок Starlight](/ru/reference/icons/#все-иконки) и по желанию может включать атрибут [`label`](#label), чтобы обеспечить контекст для программ чтения с экрана.

<Preview>

```mdx
import { Icon } from '@astrojs/starlight/components';

<Icon name="star" />
<Icon name="starlight" label="Логотип Starlight" />
```

<Fragment slot="markdoc">

```markdoc
{% icon name="star" /%}
{% icon name="starlight" label="Логотип Starlight" /%}
```

</Fragment>

<Fragment slot="preview">
	<Icon name="star" />
	<Icon name="starlight" label="Логотип Starlight" />
</Fragment>

</Preview>

### Настройка иконок

Атрибуты [`size`](#size) и [`color`](#color) можно использовать для настройки внешнего вида иконки с помощью единиц CSS и значений цвета.
Атрибут [`class`](#class) можно использовать для добавления пользовательских классов CSS к иконке.

<Preview>

```mdx
import { Icon } from '@astrojs/starlight/components';

<Icon name="star" color="goldenrod" size="2rem" />
<Icon name="rocket" color="var(--sl-color-text-accent)" />
```

<Fragment slot="markdoc">

```markdoc
{% icon name="star" color="goldenrod" size="2rem" /%}
{% icon name="rocket" color="var(--sl-color-text-accent)" /%}
```

</Fragment>

<Fragment slot="preview">
	<Icon name="star" color="goldenrod" size="2rem" />
	<Icon name="rocket" color="var(--sl-color-text-accent)" />
</Fragment>

</Preview>

## Параметры `<Icon>`

**Реализация:** [`Icon.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Icon.astro)

Компонент `<Icon>` принимает следующие параметры:

### `name`

**обязательный**  
**тип:** [`StarlightIcon`](/ru/reference/icons/#тип-starlighticon)

Имя отображаемой иконки, из набора [встроенных иконок Starlight](/ru/reference/icons/#все-иконки).

### `label`

**тип:** `string`

Необязательная метка, обеспечивающая контекст для вспомогательных технологий, таких как программы чтения с экрана.

Если `label` не задана, иконка будет полностью скрыта от вспомогательных технологий.
В этом случае убедитесь, что контекст понятен и без иконки.
Например, ссылка, содержащая только иконку, **обязательно** должна содержать атрибут `label`, чтобы быть доступной, но если ссылка содержит текст, а иконка является чисто декоративной, опустить `label` может быть вполне разумно.

### `size`

**тип:** `string`

Размер иконки, заданный с помощью единиц CSS. Например, `2rem`.

### `color`

**тип:** `string`

Цвет иконки с использованием значения цвета CSS. Например, `red`.

### `class`

**тип:** `string`

Пользовательские классы CSS для добавления к иконке.


================================================
FILE: docs/src/content/docs/ru/components/link-buttons.mdx
================================================
---
title: Кнопки-ссылки
description: Узнайте, как создавать кнопки-ссылки в Starlight для визуального выделения ссылок, призывающих к действию.
---

import { LinkButton } from '@astrojs/starlight/components';

Для отображения визуально различимых ссылок, призывающих к действию, используйте компонент `<LinkButton>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<LinkButton slot="preview" href="/ru/getting-started/">
	Прочитайте документацию
</LinkButton>

</Preview>

## Импорт

```tsx
import { LinkButton } from '@astrojs/starlight/components';
```

## Использование

Используйте компонент `<LinkButton>` для визуального выделения ссылок, призывающих к действию.
Кнопка-ссылка полезна для направления пользователей к наиболее релевантному или действующему контенту и часто используется на целевых страницах.

`<LinkButton>` требует обязательного заполнения атрибута [`href`](#href).
Кроме того, можно настроить внешний вид кнопки ссылки с помощью атрибута [`variant`](#variant), который может иметь одно из следующих значений: `primary` (по умолчанию), `secondary` или `minimal`.

<Preview>

```mdx
import { LinkButton } from '@astrojs/starlight/components';

<LinkButton href="/ru/getting-started/">Первые шаги</LinkButton>
<LinkButton href="/ru/reference/configuration/" variant="secondary">
	Справочник по конфигурации
</LinkButton>
```

<Fragment slot="markdoc">

```markdoc
{% linkbutton href="/ru/getting-started/" %}Первые шаги{% /linkbutton %}

{% linkbutton href="/ru/reference/configuration/" variant="secondary" %}
Справочник по конфигурации
{% /linkbutton %}
```

</Fragment>

<Fragment slot="preview">
	<LinkButton href="/ru/getting-started/">Первые шаги</LinkButton>
	<LinkButton href="/ru/reference/configuration/" variant="secondary">
		Справочник по конфигурации
	</LinkButton>
</Fragment>

</Preview>

### Добавление иконок

Включите иконку в кнопку-ссылку, используя атрибут [`icon`](#icon), содержащий имя [одной из встроенных иконок Starlight](/ru/reference/icons/#все-иконки).

Атрибут [`iconPlacement`](#iconplacement) можно использовать для размещения иконки перед текстом, задав ему значение `start` (по умолчанию `end`).

<Preview>

```mdx {6-7}
import { LinkButton } from '@astrojs/starlight/components';

<LinkButton
	href="https://docs.astro.build"
	variant="secondary"
	icon="external"
	iconPlacement="start"
>
	Похожие: Astro
</LinkButton>
```

<Fragment slot="markdoc">

```markdoc {4-5}
{% linkbutton
   href="https://docs.astro.build"
	 variant="secondary"
	 icon="external"
	 iconPlacement="start" %}
Похожие: Astro
{% /linkbutton %}
```

</Fragment>

<LinkButton
	slot="preview"
	href="https://docs.astro.build"
	variant="secondary"
	icon="external"
	iconPlacement="start"
>
	Похожие: Astro
</LinkButton>

</Preview>

## Параметры `<LinkButton>`

**Реализация:** [`LinkButton.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/LinkButton.astro)

Компонент `<LinkButton>` принимает следующие параметры, а также любые [другие атрибуты `<a>`](https://developer.mozilla.org/ru/docs/Web/HTML/Element/a):

### `href`

**обязательный**  
**тип:** `string`

URL-адрес, на который указывает кнопка-ссылка.

### `variant`

**тип:** `'primary' | 'secondary' | 'minimal'`  
**по умолчанию:** `'primary'`

Внешний вид кнопки-ссылки.
Установите значение `primary` для заметной ссылки с призывом к действию, использующей акцентный цвет темы, `secondary` — для менее заметной ссылки, или `minimal` — для ссылки с минимальным оформлением.

### `icon`

**тип:** `string`

Кнопка-ссылка может содержать атрибут `icon` с именем [одной из встроенных иконок Starlight](/ru/reference/icons/#все-иконки).

### `iconPlacement`

**тип:** `'start' | 'end'`  
**по умолчанию:** `'end'`

Определяет расположение значка по отношению к тексту кнопки-ссылки.


================================================
FILE: docs/src/content/docs/ru/components/link-cards.mdx
================================================
---
title: Карточки-ссылки
description: Узнайте, как отображать ссылки в виде карточек в Starlight.
sidebar:
  order: 3
---

import { LinkCard } from '@astrojs/starlight/components';

Для создания карточек-ссылок на разные страницы используйте компонент `<LinkCard>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<LinkCard
	slot="preview"
	title="Кастомизация Starlight"
	description="Узнайте, как сделать ваш сайт на Starlight уникальным с помощью пользовательских стилей, шрифтов и многого другого."
	href="/ru/guides/customization/"
/>

</Preview>

## Импорт

```tsx
import { LinkCard } from '@astrojs/starlight/components';
```

## Использование

Отображайте карточку-ссылку с помощью компонента `<LinkCard>`.
Каждый компонент `<LinkCard>` требует использования атрибутов [`title`](#title) и [`href`](#href).

<Preview>

```mdx
import { LinkCard } from '@astrojs/starlight/components';

<LinkCard
	title="Создание контента в Markdown"
	href="/ru/guides/authoring-content/"
/>
```

<Fragment slot="markdoc">

```markdoc
{% linkcard title="Создание контента в Markdown" href="/ru/guides/authoring-content/" /%}
```

</Fragment>

<LinkCard
	slot="preview"
	title="Создание контента в Markdown"
	href="/ru/guides/authoring-content/"
/>

</Preview>

### Добавление описания ссылки

Добавьте краткое описание к карточке-ссылке с помощью атрибута [`description`](#description).

<Preview>

```mdx {6}
import { LinkCard } from '@astrojs/starlight/components';

<LinkCard
	title="Интернационализация"
	href="/ru/guides/i18n/"
	description="Настройте Starlight для поддержки нескольких языков."
/>
```

<Fragment slot="markdoc">

```markdoc {4}
{% linkcard
   title="Интернационализация"
	 href="/ru/guides/i18n/"
	 description="Настройте Starlight для поддержки нескольких языков." /%}
```

</Fragment>

<LinkCard
	slot="preview"
	title="Интернационализация"
	href="/ru/guides/i18n/"
	description="Настройте Starlight для поддержки нескольких языков."
/>

</Preview>

### Группировка карточек-ссылок

Отображайте несколько карточек-ссылок рядом друг с другом при наличии свободного места, группируя их с помощью компонента [`<CardGrid>`](/ru/components/card-grids/).
См. пример в статье [Группировка карточек](/ru/components/card-grids/#группировка-карточек).

## Параметры `<LinkCard>`

**Реализация:** [`LinkCard.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/LinkCard.astro)

Компонент `<LinkCard>` принимает следующие параметры, а также все остальные атрибуты элементов [`<a>`](https://developer.mozilla.org/ru/docs/Web/HTML/Element/a):

### `title`

**обязательный**  
**тип:** `string`

Заголовок карточки-ссылки.

### `href`

**обязательный**  
**тип:** `string`

URL-адрес, на который нужно ссылаться при взаимодействии с карточкой.

### `description`

**тип:** `string`

Необязательное описание для отображения под заголовком.


================================================
FILE: docs/src/content/docs/ru/components/steps.mdx
================================================
---
title: Шаги
description: Узнайте, как стилизовать нумерованные списки задач для создания пошаговых руководств в Starlight.
---

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

Для стилизации нумерованного списка задач, при создании пошаговых руководств, используйте компонент `<Steps>`.

import Preview from '~/components/component-preview.astro';

<Preview>

<Steps slot="preview">

1. Создайте новый проект Starlight:

   <Tabs syncKey="pkg">

   <TabItem label="npm">

   ```sh
   npm create astro@latest -- --template starlight
   ```

   </TabItem>

   <TabItem label="pnpm">

   ```sh
   pnpm create astro --template starlight
   ```

   </TabItem>

   <TabItem label="Yarn">

   ```sh
   yarn create astro --template starlight
   ```

   </TabItem>

   </Tabs>

2. Напишите первую страницу документации.

</Steps>

</Preview>

## Импорт

```tsx
import { Steps } from '@astrojs/starlight/components';
```

## Использование

Используйте компонент `<Steps>` для стилизации нумерованных списков задач.
Это удобно для сложных пошаговых руководств, где каждый шаг должен быть чётко выделен.

Оберните `<Steps>` вокруг стандартного упорядоченного списка Markdown.
Внутри `<Steps>` применим весь обычный синтаксис Markdown.

<Preview>

````mdx
import { Steps } from '@astrojs/starlight/components';

<Steps>

1. Импортируйте компонент в свой MDX-файл:

   ```js
   import { Steps } from '@astrojs/starlight/components';
   ```

2. Оберните `<Steps>` вокруг элементов упорядоченного списка.

</Steps>
````

<Fragment slot="markdoc">

````markdoc
{% steps %}

1. Импортируйте компонент в свой MDX-файл:

   ```js
   import { Steps } from '@astrojs/starlight/components';
   ```

2. Оберните `<Steps>` вокруг элементов упорядоченного списка.

{% /steps %}
````

</Fragment>

<Steps slot="preview">

1. Импортируйте компонент в свой MDX-файл:

   ```js
   import { Steps } from '@astrojs/starlight/components';
   ```

2. Оберните `<Steps>` вокруг элементов упорядоченного списка.

</Steps>

</Preview>

## Параметры `<Steps>`

**Реализация:** [`Steps.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Steps.astro)

Компонент `<Steps>` не принимает никаких параметров.


================================================
FILE: docs/src/content/docs/ru/components/tabs.mdx
================================================
---
title: Вкладки
description: Узнайте, как создавать интерфейсы с вкладками в Starlight для группировки равнозначной информации.
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

Для создания интерфейса с вкладками используйте компоненты `<Tabs>` и `<TabItem>`.
Вкладки полезны для группировки эквивалентной информации, когда пользователю нужно увидеть только один из нескольких вариантов.

import Preview from '~/components/component-preview.astro';

<Preview>

<Tabs slot="preview">
	<TabItem label="Звёзды">Сириус, Вега, Бетельгейзе</TabItem>
	<TabItem label="Луны">Ио, Европа, Ганимед</TabItem>
</Tabs>

</Preview>

## Импорт

```tsx
import { Tabs, TabItem } from '@astrojs/starlight/components';
```

## Использование

Создавайте интерфейс с вкладками с помощью компонентов `<Tabs>` и `<TabItem>`.
Каждый компонент `<TabItem>` должен иметь атрибут [`label`](#label) для отображения пользователям.

<Preview>

```mdx
import { Tabs, TabItem } from '@astrojs/starlight/components';

<Tabs>
	<TabItem label="Звёзды">Сириус, Вега, Бетельгейзе</TabItem>
	<TabItem label="Луны">Ио, Европа, Ганимед</TabItem>
</Tabs>
```

<Fragment slot="markdoc">

```markdoc
{% tabs %}
{% tabitem label="Звёзды" %}
Сириус, Вега, Бетельгейзе
{% /tabitem %}

{% tabitem label="Луны" %}
Ио, Европа, Ганимед
{% /tabitem %}
{% /tabs %}
```

</Fragment>

<Tabs slot="preview">
	<TabItem label="Звёзды">Сириус, Вега, Бетельгейзе</TabItem>
	<TabItem label="Луны">Ио, Европа, Ганимед</TabItem>
</Tabs>

</Preview>

### Синхронизация вкладок

Обеспечьте синхронизацию нескольких групп вкладок, добавив атрибут [`syncKey`](#synckey).

Все `<Tabs>` с одинаковым значением `syncKey` будут отображать одну и ту же активную метку.
Это позволит вашему читателю выбрать один раз (например, операционную систему или менеджер пакетов), и видеть, что их выбор сохраняется при переходе по страницам.

Чтобы синхронизировать связанные вкладки, добавьте идентичное свойство `syncKey` к каждому компоненту `<Tabs>` и убедитесь, что все они используют одни и те же метки `<TabItem>`:

<Preview>

```mdx 'syncKey="constellations"'
import { Tabs, TabItem } from '@astrojs/starlight/components';

_Некоторые звёзды:_

<Tabs syncKey="constellations">
	<TabItem label="Орион">Беллатрикс, Ригель, Бетельгейзе</TabItem>
	<TabItem label="Близнецы">Поллукс, Кастор А, Кастор Б</TabItem>
</Tabs>

_Некоторые экзопланеты:_

<Tabs syncKey="constellations">
	<TabItem label="Орион">HD 34445 b, Gliese 179 b, Wasp-82 b</TabItem>
	<TabItem label="Близнецы">Поллукс b, HAT-P-24b, HD 50554 b</TabItem>
</Tabs>
```

<Fragment slot="markdoc">

```markdoc 'syncKey="constellations"'
_Некоторые звёзды:_

{% tabs syncKey="constellations" %}
{% tabitem label="Orion" %}
Беллатрикс, Ригель, Бетельгейзе
{% /tabitem %}

{% tabitem label="Gemini" %}
Pollux, Castor A, Castor B
{% /tabitem %}
{% /tabs %}

_Некоторые экзопланеты:_

{% tabs syncKey="constellations" %}
{% tabitem label="Orion" %}
HD 34445 b, Gliese 179 b, Wasp-82 b
{% /tabitem %}

{% tabitem label="Gemini" %}
Pollux b, HAT-P-24b, HD 50554 b
{% /tabitem %}
{% /tabs %}
```

</Fragment>

<Fragment slot="preview">

_Некоторые звёзды:_

<Tabs syncKey="constellations">
	<TabItem label="Орион">Беллатрикс, Ригель, Бетельгейзе</TabItem>
	<TabItem label="Близнецы">Поллукс, Кастор А, Кастор Б</TabItem>
</Tabs>

_Некоторые экзопланеты:_

<Tabs syncKey="constellations">
	<TabItem label="Орион">HD 34445 b, Gliese 179 b, Wasp-82 b</TabItem>
	<TabItem label="Близнецы">Поллукс b, HAT-P-24b, HD 50554 b</TabItem>
</Tabs>

</Fragment>

</Preview>

### Добавление иконок

Включите иконку в элемент вкладки, используя атрибут [`icon`](#icon), содержащий имя [одной из встроенных иконок Starlight](/ru/reference/icons/#все-иконки), чтобы отобразить иконку рядом с меткой.

<Preview>

```mdx /icon="\w+"/
import { Tabs, TabItem } from '@astrojs/starlight/components';

<Tabs>
	<TabItem label="Звёзды" icon="star">
		Сириус, Вега, Бетельгейзе
	</TabItem>
	<TabItem label="Луны" icon="moon">
		Ио, Европа, Ганимед
	</TabItem>
</Tabs>
```

<Fragment slot="markdoc">

```markdoc /icon="\w+"/
{% tabs %}
{% tabitem label="Звёзды" icon="star" %}
Сириус, Вега, Бетельгейзе
{% /tabitem %}

{% tabitem label="Луны" icon="moon" %}
Ио, Европа, Ганимед
{% /tabitem %}
{% /tabs %}
```

</Fragment>

<Tabs slot="preview">
	<TabItem label="Звёзды" icon="star">
		Сириус, Вега, Бетельгейзе
	</TabItem>
	<TabItem label="Луны" icon="moon">
		Ио, Европа, Ганимед
	</TabItem>
</Tabs>

</Preview>

## Параметры `<Tabs>`

**Реализация:** [`Tabs.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Tabs.astro)

Компонент `<Tabs>` объединяет несколько компонентов `<TabItem>` и принимает следующие параметры:

### `syncKey`

**тип:** `string`

Ключ, используемый для синхронизации нескольких групп вкладок на нескольких страницах.

## Параметры `<TabItem>`

**Реализация:** [`TabItem.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/TabItem.astro)

Набор вкладок состоит из элементов вкладок, каждый из которых имеет следующие параметры:

### `label`

**обязательный**  
**тип:** `string`

Элемент вкладки должен содержать атрибут `label`, содержащий текст, который будет отображаться на вкладке.

### `icon`

**тип:** `string`

Каждый элемент вкладки может включать атрибут `icon` с именем [одной из встроенных иконок Starlight](/ru/reference/icons/#все-иконки), для отображения иконки рядом с меткой.


================================================
FILE: docs/src/content/docs/ru/components/using-components.mdx
================================================
---
title: Использование компонентов
description: Использование компонентов в MDX и Markdoc с помощью Starlight.
sidebar:
  order: 1
---

Компоненты позволяют легко и последовательно переиспользовать часть пользовательского интерфейса или стиля.
Примерами могут служить карточки-ссылки или встраиваемые ролики YouTube.
Starlight поддерживает использование компонентов в файлах [MDX](https://mdxjs.com/) и [Markdoc](https://markdoc.dev/), а также предоставляет некоторые общие компоненты для применения.

[Узнайте больше о создании компонентов в документации Astro](https://docs.astro.build/ru/basics/astro-components/).

## Использование компонента в MDX

Вы можете использовать компонент, импортировав его в ваш файл MDX, а затем отобразив его как тег JSX.
Они выглядят как HTML-теги, но начинаются с заглавной буквы, соответствующей имени в вашем операторе `import`:

```mdx
---
# src/content/docs/example.mdx
title: Добро пожаловать в мою документацию
---

import { Icon } from '@astrojs/starlight/components';
import CustomCard from '../../components/CustomCard.astro';

<Icon name="open-book" />

<CustomCard>Компоненты могут содержать **вложенное содержимое**.</CustomCard>
```

Поскольку Starlight работает на базе Astro, вы можете использовать в своих файлах MDX любые компоненты, созданные на [поддерживаемом UI-фреймворке (React, Preact, Svelte, Vue, Solid и Alpine)](https://docs.astro.build/ru/guides/framework-components/).
Узнайте больше об [использовании компонентов в MDX](https://docs.astro.build/ru/guides/integrations-guide/mdx/#using-components-in-mdx) в документации Astro.

## Использование компонента в Markdoc

Добавьте поддержку создания контента в Markdoc, следуя нашему [руководству по настройке Markdoc](/ru/guides/authoring-content/#markdoc).

С помощью пресета Starlight Markdoc вы можете использовать встроенные компоненты Starlight с синтаксисом тегов `{% %}` в Markdoc.
В отличие от MDX, компоненты в Markdoc не нужно импортировать.
Следующий пример отображает [компонент карточки](/ru/components/cards/) Starlight в файле Markdoc:

```markdoc
---
# src/content/docs/example.mdoc
title: Добро пожаловать в мою документацию
---

{% card title="Звёзды" icon="star" %}
Сириус, Вега, Бетельгейзе
{% /card %}
```

Дополнительные сведения об использовании компонентов в файлах Markdoc см. в [документация по интеграции Astro Markdoc](https://docs.astro.build/ru/guides/integrations-guide/markdoc/#render-components).

## Встроенные компоненты

Starlight предоставляет встроенные компоненты для частых случаев, нужных в документации.
Эти компоненты доступны из пакета `@astrojs/starlight/components` в файлах MDX и из [пресета Starlight Markdoc](/ru/guides/authoring-content/#markdoc) в файлах Markdoc.

Список доступных компонентов и способы их использования см. на боковой панели.

## Совместимость со стилями Starlight

Starlight применяет стандартную стилистику к содержимому Markdown, например, добавляет поля между элементами.
Если эти стили конфликтуют с внешним видом вашего компонента, установите класс `not-content` для своего компонента, чтобы отключить их.

```astro 'class="not-content"'
---
// src/components/Example.astro
---

<div class="not-content">
	<p>Стилизация содержимого по умолчанию не влияет на Starlight.</p>
</div>
```

## Параметры компонента

Используйте тип [`ComponentProps`](https://docs.astro.build/ru/guides/typescript/#%D1%82%D0%B8%D0%BF-componentprops) из `astro/types` для ссылки на `Props`, принимаемые компонентом, даже если они не экспортируются самим компонентом.
Это может быть полезно при обёртке или расширении существующего компонента.

В следующем примере используется `ComponentProps` для получения типа параметров, принимаемых встроенным компонентом Starlight `Badge`:

```astro
---
// src/components/Example.astro
import type { ComponentProps } from 'astro/types';
import { Badge } from '@astrojs/starlight/components';

type BadgeProps = ComponentProps<typeof Badge>;
---
```


================================================
FILE: docs/src/content/docs/ru/environmental-impact.md
================================================
---
title: Экологичная документация
description: Узнайте, как Starlight может помочь вам создавать более экологичные сайты документации и сократить ваш углеродный след.
---

Оценки влияния интернет-индустрии на климат варьируются от [2%][sf] до [4% глобальных выбросов углерода][bbc], что близко к выбросам авиационной индустрии.
Расчет экологического воздействия веб-сайта включает в себя множество сложных факторов, но в данном руководстве перечислены несколько советов по снижению экологического следа вашего сайта с документацией.

Хорошая новость в том, что выбор Starlight — отличное начало.
Согласно Website Carbon Calculator, этот сайт [чище, чем 98% протестированных веб-страниц][sl-carbon], производя 0,01 г CO₂ за каждое посещение страницы.

## Вес страницы

Чем больше данных передает веб-страница, тем больше энергетических ресурсов она требует.
В апреле 2023 года, медианная веб-страница требовала от пользователя скачать более 2 000 КБ данных, согласно [данным из HTTP Archive][http].

Starlight создает страницы лёгкими, настолько, насколько это возможно.
Например, при первом посещении пользователь загрузит менее 50 КБ сжатых данных, что составляет всего 2,5% от медианного значения HTTP архива.
При хорошей стратегии кэширования последующие навигации могут загружать всего 10 КБ.

### Изображения

Хоть Starlight и предлагает лёгкие страницы по умолчанию, изображения, которые вы добавляете на страницы документации, могут быстро увеличивать вес вашей страницы.
Starlight использует [оптимизировацию ресурсов][assets] Astro для оптимизации локальных изображений в ваших файлах Markdown и MDX.

### UI-компоненты

Компоненты, на UI-фреймворках, как React или Vue, могут легко добавлять большие объемы JavaScript на страницу.
Поскольку Starlight основан на Astro, эти компоненты по умолчанию **не загружают клиентский JavaScript** благодаря [островкам Astro][islands].

### Кэширование

Кэширование управляет тем, как долго браузер хранит и повторно использует данные, которые он уже загрузил.
Хорошая стратегия кэширования гарантирует, что пользователь получает новое содержание как можно быстрее, когда оно меняется, но также избегает бесполезной повторной загрузки одного и того же содержания снова и снова, когда оно не изменилось.

Самым распространённым способом настройки кэширования является использование [HTTP-заголовка `Cache-Control`][cache].
При использовании Starlight вы можете установить длительное время кэширования для всего, что находится в каталоге `/_astro/`.
Этот каталог содержит CSS, JavaScript и другие ресурсы, которые можно безопасно кэшировать навсегда, что позволяет снизить избыточные загрузки:

```
Cache-Control: public, max-age=604800, immutable
```

Как настроить кэширование зависит от вашего веб-хоста. Например, Vercel автоматически применяет эту стратегию кэширования без необходимости настройки, в то же время вы можете установить [заголовки для Netlify][ntl-headers], добавив файл `public/_headers` в ваш проект:

```
/_astro/*
  Cache-Control: public
  Cache-Control: max-age=604800
  Cache-Control: immutable
```

[cache]: https://csswizardry.com/2019/03/cache-control-for-civilians/
[ntl-headers]: https://docs.netlify.com/routing/headers/

## Потребление энергии

То, как реализована веб-страница может влиять на потребление энергии при её запуске на устройстве пользователя.
За счет минимального использования JavaScript, Starlight снижает объем вычислительных ресурсов, необходимых телефону, планшету или компьютеру пользователя для загрузки и отображения страниц.

Будьте внимательны при добавлении функций, таких как скрипты отслеживания аналитики или контент, зависящий от JavaScript, например, встроенные видео, так как они могут увеличить энергопотребление страницы.
Если вам необходима аналитика, рассмотрите выбор легковесного варианта, такого как [Cabin][cabin], [Fathom][fathom] или [Plausible][plausible].
Встроенные видео, такие как YouTube и Vimeo, можно улучшить, ожидая [взаимодействие пользователя для загрузки видео][lazy-video].
Пакеты, такие как [`astro-embed`][embed], могут помочь с часто используемыми сервисами.

:::tip
Разбор и компиляция JavaScript являются одной из самых ресурсоемких задач, которые браузерам приходится выполнять.
По сравнению с отображением изображения JPEG того же размера, [обработка JavaScript может занять более чем в 30 раз больше времени][cost-of-js].
:::

[cabin]: https://withcabin.com/
[fathom]: https://usefathom.com/
[plausible]: https://plausible.io/
[lazy-video]: https://web.dev/iframe-lazy-loading/
[embed]: https://www.npmjs.com/package/astro-embed
[cost-of-js]: https://medium.com/dev-channel/the-cost-of-javascript-84009f51e99e

## Хостинг

Место, где размещена веб-страница, может иметь большое влияние на то, насколько экологичен ваш сайт с документацией.
Дата-центры и серверные фермы могут оказывать значительное экологическое воздействие, включая высокий энергопотребление и интенсивное использование воды.

Выбор хостинга, использующего возобновляемую энергию, снизит выбросы углерода для вашего сайта. [Справочник Green Web][gwb] — один из инструментов, который может помочь вам найти хостинговые компании, работающие с экологически чистой энергией.

[gwb]: https://www.thegreenwebfoundation.org/directory/

## Сравнения

Хотите сравнивить другие фреймворки для документации?
Эти тесты с использованием [Website Carbon Calculator][wcc] сравнивают аналогичные страницы, созданные с помощью разных инструментов.

| Фреймворк                   | CO₂ на каждое посещение стр. | Рейтинг |
| --------------------------- | ---------------------------- | :-----: |
| [Starlight][sl-carbon]      | 0.01g                        |   A+    |
| [Sphinx][sx-carbon]         | 0.01g                        |   A+    |
| [Read the Docs][rtd-carbon] | 0.03g                        |   A+    |
| [VitePress][vp-carbon]      | 0.04g                        |    A    |
| [docsify][dy-carbon]        | 0.05g                        |    A    |
| [mdBook][md-carbon]         | 0.05g                        |    A    |
| [Nextra][nx-carbon]         | 0.05g                        |    A    |
| [MkDocs][mk-carbon]         | 0.07g                        |    A    |
| [Fumadocs][fs-carbon]       | 0.07g                        |    A    |
| [Docusaurus][ds-carbon]     | 0.10g                        |    B    |
| [Docus][dc-carbon]          | 0.11g                        |    B    |
| [GitBook][gb-carbon]        | 0.42g                        |    F    |
| [Mintlify][mt-carbon]       | 0.48g                        |    F    |

<small>Данные собраны 7 августа 2025 года. Нажмите на ссылку для просмотра актуальной информации.</small>

[sl-carbon]: https://www.websitecarbon.com/website/starlight-astro-build-getting-started/
[vp-carbon]: https://www.websitecarbon.com/website/vitepress-dev-guide-what-is-vitepress/
[dc-carbon]: https://www.websitecarbon.com/website/docus-dev-en-getting-started-project-structure/
[sx-carbon]: https://www.websitecarbon.com/website/sphinx-doc-org-en-master-usage-quickstart-html/
[mk-carbon]: https://www.websitecarbon.com/website/mkdocs-org-getting-started/
[md-carbon]: https://www.websitecarbon.com/website/rust-lang-github-io-mdbook/
[nx-carbon]: https://www.websitecarbon.com/website/nextra-site-docs-docs-theme-start/
[fs-carbon]: https://www.websitecarbon.com/website/fumadocs-dev-docs-ui/
[dy-carbon]: https://www.websitecarbon.com/website/docsify-js-org/
[ds-carbon]: https://www.websitecarbon.com/website/docusaurus-io-docs/
[rtd-carbon]: https://www.websitecarbon.com/website/docs-readthedocs-io-en-stable-index-html/
[gb-carbon]: https://www.websitecarbon.com/website/gitbook-com-docs/
[mt-carbon]: https://www.websitecarbon.com/website/mintlify-com-docs-quickstart/

## Дополнительные ресурсы

### Инструменты

- [Website Carbon Calculator][wcc]
- [GreenFrame](https://greenframe.io/)
- [Ecograder](https://ecograder.com/)
- [WebPageTest Carbon Control](https://www.webpagetest.org/carbon-control/)
- [Ecoping](https://ecoping.earth/)

### Статьи и выступления

- [Построение более экологичного веба](https://youtu.be/EfPoOt7T5lg), выступление Мишель Баркер
- [Стратегии устойчивого веб-развития в организации](https://www.smashingmagazine.com/2022/10/sustainable-web-development-strategies-organization/), статья Мишель Баркер
- [Экологически устойчивый веб для каждого](https://2021.stateofthebrowser.com/speakers/tom-greenwood/), выступление Тома Гринвуда
- [Как веб-контент может влиять на энергопотребление](https://webkit.org/blog/8970/how-web-content-can-affect-power-usage/), статья Бенджамина Пулена и Саймона Фрейзера.

[sf]: https://www.sciencefocus.com/science/what-is-the-carbon-footprint-of-the-internet/
[bbc]: https://www.bbc.com/future/article/20200305-why-your-internet-habits-are-not-as-clean-as-you-think
[http]: https://httparchive.org/reports/state-of-the-web
[assets]: https://docs.astro.build/ru/guides/images/
[islands]: https://docs.astro.build/ru/concepts/islands/
[wcc]: https://www.websitecarbon.com/


================================================
FILE: docs/src/content/docs/ru/getting-started.mdx
================================================
---
title: Введение
description: Узнайте, как начать создание вашего следующего сайта с документацией с помощью Starlight от Astro.
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

Starlight — это полнофункциональная тема для документации, созданная на основе фреймворка [Astro](https://astro.build).
Это руководство поможет вам начать работу над новым проектом.
См. [инструкции по ручной настройке](/ru/manual-setup/), чтобы добавить Starlight в существующий проект Astro.

## Быстрый старт

### Создание нового проекта

Вы можете создать новый проект на базе Astro + Starlight, используя следующую команду:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight
```

</TabItem>
</Tabs>

Это создаст новую [директорию проекта](/ru/guides/project-structure/) со всеми необходимыми файлами и настройками для вашего сайта.

:::tip[Посмотрите это в действии]
Попробуйте Starlight в вашем браузере:
[откройте шаблон на StackBlitz](https://stackblitz.com/github/withastro/starlight/tree/main/examples/basics).
:::

### Запуск сервера разработки

При локальной работе [сервер разработки Astro](https://docs.astro.build/ru/reference/cli-reference/#astro-dev) позволяет предварительно просмотреть вашу работу и автоматически обновляет ваш браузер при внесении изменений.

Внутри каталога вашего проекта выполните следующую команду, чтобы запустить сервер разработки:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm run dev
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dev
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dev
```

</TabItem>
</Tabs>

На ваш терминал будет отправлено сообщение с URL-адресом вашего локального предварительного просмотра.
Откройте этот URL-адрес, чтобы начать просмотр вашего сайта.

### Добавление контента

Starlight готов к созданию нового контента или к интеграции уже существующих файлов!

Добавляйте новые страницы на свой сайт, создавая файлы Markdown в каталоге `src/content/docs/`.

Подробнее о файловой маршрутизации и поддержке файлов MDX и Markdoc читайте в руководстве [Страницы](/ru/guides/pages/).

### Следующие шаги

- **Настройка:** Узнайте об общих опциях в главе [Настройка Starlight](/ru/guides/customization/).
- **Навигация:** Настройте боковую панель с помощью руководства [Навигация по боковой панели](/ru/guides/sidebar/).
- **Компоненты:** Узнайте о встроенных карточках, вкладках и многом другом в руководстве [Компоненты](/ru/components/using-components/).
- **Расширение:** Изучите дополнения сообщества в наших каталогах [Плагины](/ru/resources/plugins/) и [Темы](/ru/resources/themes/).
- **Развёртывание:** Опубликуйте свою работу с помощью руководства [Развёртывание вашего сайта](https://docs.astro.build/ru/guides/deploy/) в документации Astro.

## Обновление Starlight

:::tip
Поскольку Starlight ещё в статусе beta, будут частые обновления и улучшения.
Не забывайте регулярно обновлять Starlight!
:::

Starlight является интеграцией Astro и обновляется так же, как любая интеграция @astrojs/\*:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npx @astrojs/upgrade
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dlx @astrojs/upgrade
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dlx @astrojs/upgrade
```

</TabItem>
</Tabs>

Вы можете увидеть полный список изменений, сделанных в каждом релизе, в [списке изменений Starlight](https://github.com/withastro/starlight/blob/main/packages/starlight/CHANGELOG.md).

## Устранение проблем со Starlight

Используйте справочные страницы [конфигурация проекта](/ru/reference/configuration/) и [конфигурация метаданных отдельной страницы](/ru/reference/frontmatter/), чтобы убедиться, что ваш сайт Starlight настроен и работает правильно.
См. руководства на боковой панели, чтобы получить помощь в добавлении контента и настройке вашего сайта Starlight.

Если вы не можете найти ответ в этой документации, пожалуйста, посетите [полную документацию Astro](https://docs.astro.build/ru/).
На ваш вопрос можно ответить, если вы поймете, как работает Astro в целом в рамках темы Starlight.

Вы также можете узнать про любые известные [проблемы Starlight на GitHub](https://github.com/withastro/starlight/issues) и получить помощь в
[Discord Astro](https://astro.build/chat/) от нашего активного, дружелюбного сообщества!
Задавайте вопросы на нашем форуме `#support` с тегом "starlight", или посетите наш специальный канал `#starlight`,
чтобы обсудить текущую разработку и многое другое!


================================================
FILE: docs/src/content/docs/ru/guides/authoring-content.mdx
================================================
---
title: Создание контента в Markdown
description: Обзор синтаксиса Markdown, который поддерживается в Starlight.
---

Starlight поддерживает весь синтаксис [Markdown](https://daringfireball.net/projects/markdown/) в файлах с расширением `.md`, а также синтаксис [YAML](https://dev.to/paulasantamaria/introduction-to-yaml-125f) для определения метаданных, таких как заголовок и описание.

Пожалуйста, обратитесь к [документации MDX](https://mdxjs.com/docs/what-is-mdx/#markdown) или [документации Markdoc](https://markdoc.dev/docs/syntax), если вы используете эти форматы файлов, поскольку поддержка и использование Markdown могут отличаться.

## Метаданные

Вы можете настроить отдельные страницы в Starlight, установив значения в их заглавной части.
Метаданные устанавливаются в верхней части ваших файлов между разделителями `---`:

```md title="src/content/docs/example.md"
---
title: Заголовок страницы
---

Содержимое страницы следует за вторым `---`.
```

Каждая страница должна включать хотя бы заголовок.
См. [справочник по метаданным](/ru/reference/frontmatter/) для получения информации обо всех доступных полях и о том, как добавлять настраиваемые поля.

## Встроенные стили

Текст может быть **жирным**, _курсивом_ или ~~зачёркнутым~~.

```md
Текст может быть **жирным**, _курсивом_ или ~~зачёркнутым~~.
```

Вы можете [ссылаться на другую страницу](/ru/getting-started/).

```md
Вы можете [ссылаться на другую страницу](/ru/getting-started/).
```

Вы можете выделить `код` обратными кавычками.

```md
Вы можете выделить `код` обратными кавычками.
```

## Изображения

Изображения в Starlight используют [встроенную оптимизацию ресурсов Astro](https://docs.astro.build/ru/guides/images/).

Markdown и MDX поддерживают синтаксис Markdown для отображения изображений, который включает альтернативный текст для экранных читателей и вспомогательных технологий.

![Иллюстрация планет и звёзд с надписью "astro"](https://raw.githubusercontent.com/withastro/docs/main/public/default-og-image.png)

```md
![Иллюстрация планет и звёзд с надписью "astro"](https://raw.githubusercontent.com/withastro/docs/main/public/default-og-image.png)
```

Относительные пути к изображениям также поддерживаются для изображений, хранящихся локально в вашем проекте.

```md
// src/content/docs/page-1.md

![Ракета в космосе](../../assets/images/rocket.svg)
```

## Заголовки

Вы можете структурировать контент, используя заголовки. Заголовки в Markdown обозначаются количеством символов `#` в начале строки.

### Как структурировать контент страницы

Starlight настроен так, чтобы автоматически использовать заголовок вашей страницы в качестве заголовка верхнего уровня и включать заголовок «Обзор» в начале оглавления каждой страницы. Мы рекомендуем начинать каждую страницу с обычного текстового содержания абзаца и использовать заголовки на странице от `<h2>` и ниже:

```md
---
title: Руководство по Markdown
description: Как использовать Markdown в Starlight
---

Эта страница описывает, как использовать Markdown в Starlight.

## Форматирование текста

## Заголовки
```

### Автоматические якорные ссылки для заголовков

Использование заголовков в Markdown автоматически создает якорные ссылки, позволяя вам ссылаться на определённые разделы вашей страницы:

```md
---
title: Моя страница с контентом
description: Как использовать встроенные в Starlight якорные ссылки.
---

## Введение

Я могу создать ссылку на [заключение](#заключение) ниже на этой же странице.

## Заключение

`https://my-site.com/page1/#введение` переходит непосредственно к моему Введению.
```

Заголовки уровня 2 (`<h2>`) и уровня 3 (`<h3>`) автоматически появятся в оглавлении страницы.

Узнайте больше о том, как Astro обрабатывает идентификаторы заголовков, в [документации Astro](https://docs.astro.build/ru/guides/markdown-content/#%D0%B8%D0%B4%D0%B5%D0%BD%D1%82%D0%B8%D1%84%D0%B8%D0%BA%D0%B0%D1%82%D0%BE%D1%80%D1%8B-%D0%B7%D0%B0%D0%B3%D0%BE%D0%BB%D0%BE%D0%B2%D0%BA%D0%BE%D0%B2)

## Вставки

Вставки полезны для отображения дополнительной информации рядом с основным контентом страницы.

Starlight предоставляет специальный синтаксис Markdown для отображения вставок. Вставки должны быть обернуты парой тройных двоеточий `:::` и могут иметь тип `note`, `tip`, `caution` или `danger`.

Вы можете указывать любые типы контента Markdown внутри вставок, но вставки лучше всего подходят для коротких и лаконичных блоков информации.

### Вставка «Заметка»

:::note
Starlight — это инструмент для создания сайтов с документацией, построенный с использованием [Astro](https://astro.build/ru/). Вы можете начать с этой команды:

```sh
npm create astro@latest -- --template starlight
```

:::

````md
:::note
Starlight — это инструмент для создания сайтов с документацией, построенный с использованием [Astro](https://astro.build/ru/). Вы можете начать с этой команды:

```sh
npm create astro@latest -- --template starlight
```

:::
````

### Настраиваемые заголовки вставок

Вы можете указать свой заголовок вставки в квадратных скобках после типа вставки, например, `:::tip[Небольшой совет]`.

:::tip[Небольшой совет]
Astro позволяет создавать быстрые сайты с помощью [архитектуры островков](https://docs.astro.build/ru/concepts/islands/)
:::

```md
:::tip[Небольшой совет]
Astro позволяет создавать быстрые сайты с помощью [архитектуры островков](https://docs.astro.build/ru/concepts/islands/)
:::
```

### Пользовательские иконки вставок

Вы можете указать пользовательскую иконку для вставки в фигурных скобках после типа панели или [пользовательского заголовка](#настраиваемые-заголовки-вставок), например, `:::tip{icon="heart"}` или `:::tip[Знаете ли вы?]{icon="heart"}` соответственно.
В качестве имени должна использоваться одна из [встроенных иконок Starlight](/ru/reference/icons/#все-иконки).

:::tip{icon="heart"}
Astro помогает создавать более быстрые веб-сайты с помощью [архитектуры островков](https://docs.astro.build/ru/concepts/islands/).
:::

```md
:::tip{icon="heart"}
Astro помогает создавать более быстрые веб-сайты с помощью [архитектуры островков](https://docs.astro.build/ru/concepts/islands/).
:::
```

### Другие типы вставок

Вставки с типами «caution» и «danger» полезны для привлечения внимания пользователя к деталям, которые могут сбивать с толку.
Если вы часто используете их, это может быть признаком того, что может быть нужно пересмотреть то, что вы документируете.

:::caution
Если вы не уверены, что хотите отличный сайт с документацией, подумайте дважды, прежде чем использовать [Starlight](/ru/).
:::

:::danger
Ваши пользователи могут быть более продуктивными и находить ваш продукт более простым в использовании благодаря полезным функциям Starlight.

- Чёткая навигация
- Цветовая тема, настраиваемая пользователем
- [Поддержка i18n](/ru/guides/i18n/)

:::

```md
:::caution
Если вы не уверены, что хотите отличный сайт с документацией, подумайте дважды, прежде чем использовать [Starlight](/ru/).
:::

:::danger
Ваши пользователи могут быть более продуктивными и находить ваш продукт более простым в использовании благодаря полезным функциям Starlight.

- Чёткая навигация
- Цветовая тема, настраиваемая пользователем
- [Поддержка i18n](/ru/guides/i18n/)

:::
```

## Цитаты

> Это цитата, которую обычно используют при цитировании другого человека или документа.
>
> Цитаты обозначаются символом `>` в начале каждой строки.

```md
> Это цитата, которую обычно используют при цитировании другого человека или документа.
>
> Цитаты обозначаются символом `>` в начале каждой строки.
```

## Блоки кода

Блок кода обозначается блоком с тремя обратными апострофами <code>```</code> в начале и в конце. Вы можете указать язык программирования после открывающих апострофов.

```js
// Javascript код с подсветкой синтаксиса.
var fun = function lang(l) {
	dateformat.i18n = require('./lang/' + l);
	return true;
};
```

````md
```js
// Javascript код с подсветкой синтаксиса.
var fun = function lang(l) {
	dateformat.i18n = require('./lang/' + l);
	return true;
};
```
````

### Возможности Expressive Code

Starlight использует [Expressive Code](https://expressive-code.com/) для расширения возможностей форматирования блоков кода.
Текстовые маркеры и плагины оконных рамок Expressive Code включены по умолчанию.
Рендеринг блоков кода можно настроить с помощью [параметра конфигурации `expressiveCode`](/ru/reference/configuration/#expressivecode) Starlight.

#### Текстовые маркеры

Вы можете выделить определённые строки или части блоков кода с помощью [текстовых маркеров Expressive Code](https://expressive-code.com/key-features/text-markers/) в первой строке вашего блока кода.
Используйте фигурные скобки (`{ }`), чтобы выделить целые строки, и кавычки, чтобы выделить строки текста.

Существует три стиля выделения: нейтральный для привлечения внимания к коду, зелёный для обозначения вставленного кода и красный для обозначения удалённого кода.
И текст, и целые строки можно пометить с помощью маркера по умолчанию или в сочетании с `ins=` и `del=` для получения желаемого выделения.

Expressive Code предоставляет несколько вариантов настройки внешнего вида примеров кода.
Многие из них можно комбинировать для получения наглядных примеров кода.
Ознакомьтесь с [документацией Expressive Code](https://expressive-code.com/key-features/text-markers/#configuration), чтобы узнать о расширенных возможностях. доступный.
Некоторые из наиболее распространённых примеров показаны ниже:

- [Пометка целых строк и диапазонов строк с помощью маркера `{ }`](https://expressive-code.com/key-features/text-markers/#marking-full-lines--line-ranges):

  ```js {2-3}
  function demo() {
  	// Эта строка (#2) и следующая выделены
  	return 'Это строка №3 этого фрагмента';
  }
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```js {2-3}
  function demo() {
  	// Эта строка (#2) и следующая выделены
  	return 'Это строка №3 этого фрагмента';
  }
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```js {% meta="{2-3}" %}
  function demo() {
    // Эта строка (#2) и следующая выделены
    return 'Это строка №3 этого фрагмента';
  }
  ```
  ````

  </TabItem>

  </Tabs>

- [Пометка выделенного текста с помощью маркера `" "` или регулярных выражений](https://expressive-code.com/key-features/text-markers/#marking-individual-text-inside-lines):

  ```js "Отдельные термины" /даже.*выражения/
  // Отдельные термины также могут быть выделены
  function demo() {
  	return 'Поддерживаются даже регулярные выражения';
  }
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```js "Отдельные термины" /даже.*выражения/
  // Отдельные термины также могут быть выделены
  function demo() {
  	return 'Поддерживаются даже регулярные выражения';
  }
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```js {% meta="'Отдельные термины' /даже.*выражения/" %}
  // Отдельные термины также могут быть выделены
  function demo() {
    return 'Поддерживаются даже регулярные выражения';
  }
  ```
  ````

  </TabItem>

  </Tabs>

- [Пометка текста или строк как вставленных или удалённых с помощью `ins` или `del`](https://expressive-code.com/key-features/text-markers/#selecting-inline-marker-types-mark-ins-del):

  ```js "return true;" ins="вставленные" del="удалённые"
  function demo() {
  	console.log('Это вставленные и удалённые типы маркеров');
  	// Оператор return использует тип маркера по умолчанию
  	return true;
  }
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```js "return true;" ins="вставленные" del="удалённые"
  function demo() {
  	console.log('Это вставленные и удалённые типы маркеров');
  	// Оператор return использует тип маркера по умолчанию
  	return true;
  }
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```js {% meta="'return true;' ins='вставленные' del='удалённые'" %}
  function demo() {
    console.log('Это вставленные и удалённые типы маркеров');
    // Оператор return использует тип маркера по умолчанию
    return true;
  }
  ```
  ````

  </TabItem>

  </Tabs>

- [Объединение подсветки синтаксиса с синтаксисом типа `diff`](https://expressive-code.com/key-features/text-markers/#combining-syntax-highlighting-with-diff-like-syntax):

  ```diff lang="js"
    function thisIsJavaScript() {
      // Весь этот блок выделяется как JavaScript,
      // и мы можем добавить к нему маркеры различий!
  -   console.log('Старый код, который нужно удалить')
  +   console.log('Новый и блестящий код!')
    }
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```diff lang="js"
    function thisIsJavaScript() {
      // Весь этот блок выделяется как JavaScript,
      // и мы можем добавить к нему маркеры различий!
  -   console.log('Устаревший код, который нужно удалить')
  +   console.log('Обновлённый и крутой код!')
    }
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```diff {% meta="lang='js'" %}
    function thisIsJavaScript() {
      // Весь этот блок выделяется как JavaScript,
      // и мы можем добавить к нему маркеры различий!
  -   console.log('Устаревший код, который нужно удалить')
  +   console.log('Обновлённый и крутой код!')
    }
  ```
  ````

  </TabItem>

  </Tabs>

#### Рамки и заголовки

Блоки кода могут отображаться внутри оконного фрейма.
Рамка, похожая на окно терминала, будет использоваться для языков сценариев оболочки (например, `bash` или `sh`).
Другие языки отображаются внутри рамки в стиле редактора кода, если они включают заголовок.

Необязательный заголовок блока кода может быть установлен либо с помощью атрибута `title="..."` после открывающих обратных кавычек блока кода и идентификатора языка, либо с помощью комментария к имени файла в первых строках кода.

- [Добавление вкладки имени файла с помощью комментария](https://expressive-code.com/key-features/frames/#code-editor-frames)

  ```js
  // my-test-file.js
  console.log('Привет, мир!');
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```js
  // my-test-file.js
  console.log('Привет, мир!');
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````md
  ```js
  // my-test-file.js
  console.log('Привет, мир!');
  ```
  ````

  </TabItem>

  </Tabs>

- [Добавление заголовка в окне терминала](https://expressive-code.com/key-features/frames/#terminal-frames)

  ```bash title="Установка зависимостей…"
  npm install
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```bash title="Установка зависимостей…"
  npm install
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```bash {% title="Установка зависимостей…" %}
  npm install
  ```
  ````

  </TabItem>

  </Tabs>

- [Отключение оконных рамок с помощью `frame="none"`](https://expressive-code.com/key-features/frames/#overriding-frame-types)

  ```bash frame="none"
  echo "Это не отображается как терминал, несмотря на использование языка bash"
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```bash frame="none"
  echo "Это не отображается как терминал, несмотря на использование языка bash"
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```bash {% frame="none" %}
  echo "Это не отображается как терминал, несмотря на использование языка bash"
  ```
  ````

  </TabItem>

  </Tabs>

## Спойлеры

Спойлеры (также известные как «раскрытия» или «аккордеоны») полезны для того, чтобы скрыть содержимое, которое не имеет непосредственного отношения к делу.
Пользователи могут нажать на краткое содержание, чтобы развернуть его и просмотреть полный текст.

Используйте стандартные элементы HTML [`<details>`](https://developer.mozilla.org/ru/docs/Web/HTML/Element/details) и [`<summary>`](https://developer.mozilla.org/ru/docs/Web/HTML/Element/summary) в вашем Markdown-контенте, чтобы создать виджет раскрытия информации.

Внутри элемента `<details>` можно использовать любой другой синтаксис Markdown.

<details>
<summary>Где и когда созвездие Андромеды видно лучше всего?</summary>

[Созвездие Андромеды](<https://ru.wikipedia.org/wiki/%D0%90%D0%BD%D0%B4%D1%80%D0%BE%D0%BC%D0%B5%D0%B4%D0%B0_(%D1%81%D0%BE%D0%B7%D0%B2%D0%B5%D0%B7%D0%B4%D0%B8%D0%B5)>) наиболее заметно на ночном небе в ноябре на широтах от `+90°` до `-40°`.

</details>

```md
<details>
<summary>Где и когда созвездие Андромеды видно лучше всего?</summary>

[Созвездие Андромеды](<https://ru.wikipedia.org/wiki/%D0%90%D0%BD%D0%B4%D1%80%D0%BE%D0%BC%D0%B5%D0%B4%D0%B0_(%D1%81%D0%BE%D0%B7%D0%B2%D0%B5%D0%B7%D0%B4%D0%B8%D0%B5)>) наиболее заметно на ночном небе в ноябре на широтах от `+90°` до `-40°`.

</details>
```

## Сноски

[Сноски](https://www.markdownguide.org/extended-syntax/#footnotes) полезны для добавления кратких ссылок или пояснений, не прерывая поток вашего контента. Они отображаются как нумерованные надстрочные ссылки, которые ведут к тексту сносок, собранному внизу страницы.

Определите сноску с помощью квадратных скобок с символом вставки (^) и нумерованной ссылкой:

```md
Здесь есть сноска[^1] с некоторым дополнительным текстом после неё.

[^1]: Моя ссылка.
```

## Другие возможности Markdown

Starlight поддерживает все синтаксические возможности Markdown, такие как списки и таблицы. Посмотрите [шпаргалку по Markdown от The Markdown Guide](https://www.markdownguide.org/cheat-sheet/) для изучения всех возможностей синтаксиса Markdown.

## Расширенная конфигурация Markdown и MDX

Starlight использует Markdown и рендерер MDX от Astro, основанный на `remark` и `rehype`. Вы можете добавить поддержку пользовательского синтаксиса и поведения, добавив `remarkPlugins` или `rehypePlugins` в свой файл конфигурации Astro. Дополнительную информацию см. в статье [Плагины Markdown](https://docs.astro.build/ru/guides/markdown-content/#%D0%BF%D0%BB%D0%B0%D0%B3%D0%B8%D0%BD%D1%8B-markdown) в документации Astro.

## Markdoc

Starlight поддерживает создание контента в Markdoc с помощью экспериментальной [интеграции с Astro](https://docs.astro.build/ru/guides/integrations-guide/markdoc/) и пресета Starlight Markdoc.

### Создание нового проекта с Markdoc

Начните новый проект Starlight с предварительно настроенным Markdoc с помощью команды `create astro`:

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight/markdoc
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight/markdoc
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight/markdoc
```

</TabItem>
</Tabs>

### Добавление Markdoc в существующий проект

Если у вас уже есть сайт Starlight и вы хотите добавить Markdoc, выполните следующие действия.

<Steps>

1.  Добавьте интеграцию Markdoc:

    <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npx astro add markdoc
    ```

    </TabItem>

    <TabItem label="pnpm">

    ```sh
    pnpm astro add markdoc
    ```

    </TabItem>

    <TabItem label="Yarn">

    ```sh
    yarn astro add markdoc
    ```

    </TabItem>

    </Tabs>

2.  Установите пресет Markdoc для Starlight:

    <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npm install @astrojs/starlight-markdoc
    ```

    </TabItem>

    <TabItem label="pnpm">

    ```sh
    pnpm add @astrojs/starlight-markdoc
    ```

    </TabItem>

    <TabItem label="Yarn">

    ```sh
    yarn add @astrojs/starlight-markdoc
    ```

    </TabItem>

    </Tabs>

3.  Создайте файл конфигурации Markdoc по адресу `markdoc.config.mjs` и используйте пресет Markdoc:

    ```js
    import { defineMarkdocConfig } from '@astrojs/markdoc/config';
    import starlightMarkdoc from '@astrojs/starlight-markdoc';

    export default defineMarkdocConfig({
    	extends: [starlightMarkdoc()],
    });
    ```

</Steps>

Чтобы узнать больше о синтаксисе и возможностях Markdoc, смотрите [документацию](https://markdoc.dev/docs/syntax) или [Руководство по интеграции Markdoc в Astro](https://docs.astro.build/ru/guides/integrations-guide/markdoc/).

### Настройка пресета Markdoc

Пресет `starlightMarkdoc()` принимает следующие параметры конфигурации:

#### `headingLinks`

**тип:** `boolean`  
**по умолчанию:** `true`

Определяет, будут ли заголовки отображаться с кликабельной ссылкой-якорем.
Эквивалентно опции [`markdown.headingLinks`](/ru/reference/configuration/#markdown), которая применяется к файлам Markdown и MDX.

```js "headingLinks: false"
export default defineMarkdocConfig({
	// Отключение поддержки ссылок-якорей для заголовков по умолчанию
	extends: [starlightMarkdoc({ headingLinks: false })],
});
```


================================================
FILE: docs/src/content/docs/ru/guides/css-and-tailwind.mdx
================================================
---
title: CSS и стилизация
description: Узнайте, как стилизовать ваш сайт Starlight с помощью CSS-файлов или интегрировать с Tailwind CSS.
---

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

Вы можете стилизовать ваш сайт Starlight с помощью CSS-файлов или использовать плагин Starlight Tailwind.

Для быстрого изменения стандартного стиля вашего сайта ознакомьтесь с [темами от сообщества](/ru/resources/themes/).

## Ваши CSS стили

Настройте стили, применяемые к вашему сайту Starlight, предоставив дополнительные CSS-файлы для изменения или расширения стандартных стилей Starlight.

<Steps>

1. Добавьте CSS-файл в ваш каталог `src/`.
   Например, вы можете установить большую ширину колонки по умолчанию и бóльший размер текста для заголовков страниц:

   ```css
   /* src/styles/custom.css */
   :root {
   	--sl-content-width: 50rem;
   	--sl-text-5xl: 3.5rem;
   }
   ```

2. Добавьте путь к вашему CSS-файлу в массив `customCss` Starlight в `astro.config.mjs`:

   ```js
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Документация с изменёнными CSS-стилями',
   			customCss: [
   				// Относительный путь к вашему CSS файлу
   				'./src/styles/custom.css',
   			],
   		}),
   	],
   });
   ```

</Steps>

Вы можете увидеть все кастомные свойства CSS, используемые Starlight, которые вы можете установить для настройки вашего сайта, в [файле `props.css` на GitHub](https://github.com/withastro/starlight/blob/main/packages/starlight/style/props.css).

### Каскадные слои

Starlight использует [каскадные слои](https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Cascade_layers) внутри для управления порядком своих стилей.
Это обеспечивает предсказуемый порядок CSS и упрощает переопределение стилей.
Любые пользовательские CSS-стили без слоёв переопределят стандартные стили Starlight.

Если вы используете каскадные слои, вы можете применить [`@layer`](https://developer.mozilla.org/ru/docs/Web/CSS/@layer) в вашем пользовательском CSS для определения порядка приоритета различных слоёв относительно стилей из слоя `starlight`:

```css "starlight"
/* src/styles/custom.css */
@layer my-reset, starlight, my-overrides;
```

Пример выше определяет пользовательский слой `my-reset`, применяемый перед всеми слоями Starlight, и другой слой `my-overrides`, применяемый после всех слоёв Starlight.
Любые стили в слое `my-overrides` будут иметь приоритет над стилями Starlight, но Starlight всё ещё сможет изменять стили, установленные в слое `my-reset`.

## Tailwind CSS

Поддержка Tailwind CSS v4 в проектах Astro обеспечивается [плагином Tailwind Vite](https://tailwindcss.com/docs/installation/using-vite).
Starlight предоставляет дополнительный CSS для настройки Tailwind, обеспечивающий совместимость со стилями Starlight.

CSS Tailwind от Starlight применяет следующую конфигурацию:

- Настраивает `dark:` варианты Tailwind для работы с тёмным режимом Starlight.
- Использует [цвета и шрифты темы Tailwind](#стилизация-starlight-с-использованием-tailwind) в пользовательском интерфейсе Starlight.
- Восстанавливает основные части стилей сброса Preflight от Tailwind.

### Создание нового проекта с Tailwind

Создайте новый проект Starlight с предварительно настроенным Tailwind CSS, используя `create astro`:

 <Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight/tailwind
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight/tailwind
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight/tailwind
```

</TabItem>
</Tabs>

### Добавление Tailwind в существующий проект

Если у вас уже есть сайт на Starlight и вы хотите добавить Tailwind CSS, следуйте этим шагам.

<Steps>

1.  Настройте Tailwind в вашем проекте, выполнив следующую команду и следуя инструкциям в терминале:

    <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npx astro add tailwind
    ```

    </TabItem>

    <TabItem label="pnpm">

    ```sh
    pnpm astro add tailwind
    ```

    </TabItem>

    <TabItem label="Yarn">

    ```sh
    yarn astro add tailwind
    ```

    </TabItem>

    </Tabs>

2.  Установите пакет совместимости Tailwind для Starlight:

    <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npm install @astrojs/starlight-tailwind
    ```

    </TabItem>

    <TabItem label="pnpm">

    ```sh
    pnpm add @astrojs/starlight-tailwind
    ```

    </TabItem>

    <TabItem label="Yarn">

    ```sh
    yarn add @astrojs/starlight-tailwind
    ```

    </TabItem>

    </Tabs>

3.  Замените содержимое файла `src/styles/global.css`, созданного Astro, для обеспечения совместимости со Starlight:

    ```css
    /* src/styles/global.css */
    @layer base, starlight, theme, components, utilities;

    @import '@astrojs/starlight-tailwind';
    @import 'tailwindcss/theme.css' layer(theme);
    @import 'tailwindcss/utilities.css' layer(utilities);
    ```

    Эта конфигурация темы Tailwind определяет порядок [каскадных слоев](#каскадные-слои) Starlight, импортирует дополнительные стили Tailwind от Starlight, а также стили темы и утилиты Tailwind.
    Если вашему проекту требуется дополнительная конфигурация Tailwind, ознакомьтесь с разделом [Использование нескольких конфигураций Tailwind](#использование-нескольких-конфигураций-tailwind).

4.  Обновите конфигурацию Starlight, добавив файл Tailwind CSS как первый элемент массива `customCss`:

    ```js ins={11-12}
    // astro.config.mjs
    import { defineConfig } from 'astro/config';
    import starlight from '@astrojs/starlight';
    import tailwindcss from '@tailwindcss/vite';

    export default defineConfig({
    	integrations: [
    		starlight({
    			title: 'Docs with Tailwind',
    			customCss: [
    				// Путь к базовым стилям Tailwind:
    				'./src/styles/global.css',
    			],
    		}),
    	],
    	vite: { plugins: [tailwindcss()] },
    });
    ```

</Steps>

### Стилизация Starlight с использованием Tailwind

При [создании нового проекта Starlight с Tailwind](#создание-нового-проекта-с-tailwind) или при [добавлении Tailwind в существующий проект Starlight](#добавление-tailwind-в-существующий-проект), Starlight будет использовать значения из вашей [конфигурации темы Tailwind](https://tailwindcss.com/docs/theme), расположенной в файле `src/styles/global.css`, для стилизации своего пользовательского интерфейса.

Если установлены, следующие пользовательские свойства CSS переопределят стили Starlight по умолчанию:

- `--color-accent-*` — используется для ссылок и выделения текущего элемента;
- `--color-gray-*` — используется для цветов фона и границ;
- `--font-sans` — используется для текста в интерфейсе и контента;
- `--font-mono` — используется для примеров кода.

```css {9,11,13,25}
/* src/styles/global.css */
@layer base, starlight, theme, components, utilities;

@import '@astrojs/starlight-tailwind';
@import 'tailwindcss/theme.css' layer(theme);
@import 'tailwindcss/utilities.css' layer(utilities);

@theme {
	/* Предпочитаемый шрифт для текста. По умолчанию Starlight использует системный стек шрифтов. */
	--font-sans: 'Atkinson Hyperlegible';
	/* Предпочитаемый шрифт для кода. По умолчанию Starlight использует системные моноширинные шрифты. */
	--font-mono: 'IBM Plex Mono';
	/* Предпочитаемый акцентный цвет. Indigo наиболее близок к цветам по умолчанию в Starlight. */
	--color-accent-50: var(--color-indigo-50);
	--color-accent-100: var(--color-indigo-100);
	--color-accent-200: var(--color-indigo-200);
	--color-accent-300: var(--color-indigo-300);
	--color-accent-400: var(--color-indigo-400);
	--color-accent-500: var(--color-indigo-500);
	--color-accent-600: var(--color-indigo-600);
	--color-accent-700: var(--color-indigo-700);
	--color-accent-800: var(--color-indigo-800);
	--color-accent-900: var(--color-indigo-900);
	--color-accent-950: var(--color-indigo-950);
	/* Предпочитаемая серая палитра. Zinc наиболее близок к значениям по умолчанию в Starlight. */
	--color-gray-50: var(--color-zinc-50);
	--color-gray-100: var(--color-zinc-100);
	--color-gray-200: var(--color-zinc-200);
	--color-gray-300: var(--color-zinc-300);
	--color-gray-400: var(--color-zinc-400);
	--color-gray-500: var(--color-zinc-500);
	--color-gray-600: var(--color-zinc-600);
	--color-gray-700: var(--color-zinc-700);
	--color-gray-800: var(--color-zinc-800);
	--color-gray-900: var(--color-zinc-900);
	--color-gray-950: var(--color-zinc-950);
}
```

### Использование нескольких конфигураций Tailwind

Несколько конфигураций Tailwind могут быть использованы для применения различных стилей к разным частям вашего сайта, например, при [использовании Starlight с подкаталогами](/ru/manual-setup/#использование-starlight-с-подкаталогами) или при добавлении [пользовательских страниц](/ru/guides/pages/#пользовательские-страницы) на ваш сайт.
Например, вы можете захотеть использовать стили сброса Preflight от Tailwind на пользовательских страницах, сохраняя при этом слой совместимости Starlight для страниц Starlight.

Следующая конфигурация Tailwind CSS настраивает Tailwind без каких-либо плагинов или дополнительной конфигурации и может использоваться как отправная точка для страниц, не относящихся к Starlight:

```css title="src/styles/custom-pages-tailwind.css"
/* Загрузка Tailwind без дополнительных стилей от Starlight. */
@import 'tailwindcss';
```

<Steps>

1. Для страниц Starlight примените предпочитаемую конфигурацию Tailwind CSS, следуя инструкциям из раздела [Добавление Tailwind в существующий проект](#добавление-tailwind-в-существующий-проект).

2. Для других страниц примените предпочитаемую конфигурацию Tailwind CSS, импортируя её на этих страницах. Это часто делается в компоненте макета, чтобы стили Tailwind могли использоваться на всех страницах, использующих этот макет.
   ```astro
   ---
   // src/layouts/CustomPageLayout.astro
   import '../styles/custom-pages-tailwind.css';
   ---
   ```

</Steps>

Чтобы узнать больше о конфигурациях тем Tailwind, ознакомьтесь с [документацией Tailwind CSS](https://tailwindcss.com/docs/theme).

## Темизация

Цветовая тема Starlight может быть настроена путем переопределения её стандартных кастомных свойств.
Эти переменные используются по всему интерфейсу, причём различные оттенки серого используются для текста и цветов фона, а акцентный цвет используется для ссылок и выделения текущих элементов в навигации.

### Редактор цветовой темы

Используйте ползунки ниже, чтобы изменить палитры акцентного и серого цветов Starlight.
Тёмные и светлые области предпросмотра будут показывать результирующие цвета, и вся страница также обновится, чтобы показать ваши изменения.

Используйте параметр «Уровень контрастности», чтобы указать, какому из [стандартов цветовой контрастности](https://developer.mozilla.org/ru/docs/Web/Accessibility/Understanding_WCAG/Perceivable/Color_contrast) должен соответствовать веб-контент.

Когда вы будете довольны внесёнными изменениями, скопируйте приведённый ниже код CSS или Tailwind и используйте его в своем проекте.

import ThemeDesigner from '~/components/theme-designer.astro';

<ThemeDesigner
	labels={{
		presets: {
			label: 'Заготовки',
			ocean: 'Океан',
			forest: 'Лес',
			oxide: 'Оксид',
			nebula: 'Туман',
			default: 'По умолчанию',
			random: 'Случайно',
		},
		contrast: {
			label: 'Уровень контрастности',
		},
		editor: {
			accentColor: 'Акцентный цвет',
			grayColor: 'Серый',
			hue: 'Оттенок',
			chroma: 'Интенсивность ',
			pickColor: 'Выбор цвета',
		},
		preview: {
			darkMode: 'Тёмный режим',
			lightMode: 'Светлый режим',
			bodyText:
				'Основной текст отображается в оттенке серого с высоким контрастом по отношению к фону.',
			linkText: 'Ссылки выделены цветом.',
			dimText: 'Некоторый текст, например, оглавление, имеет меньший контраст.',
			inlineCode: 'Встроенный код имеет выделенный фон.',
		},
	}}
>
	<Fragment slot="css-docs">
		Добавьте следующий CSS в ваш проект в [пользовательском
		CSS-файле](#ваши-css-стили), чтобы применить эту тему к вашему сайту.
	</Fragment>
	<Fragment slot="tailwind-docs">
		Добавьте следующие CSS-переменные в блок `@theme` вашего [файла Tailwind
		CSS](#стилизация-starlight-с-использованием-tailwind), чтобы применить эту
		тему к вашему сайту.
	</Fragment>
</ThemeDesigner>


================================================
FILE: docs/src/content/docs/ru/guides/customization.mdx
================================================
---
title: Кастомизация Starlight
description: Узнайте, как сделать ваш сайт на Starlight уникальным с вашим логотипом, шрифтами, дизайном главной страницы и многим другим.
---

import { Tabs, TabItem, FileTree, Steps } from '@astrojs/starlight/components';

Starlight предоставляет осмысленные стили и функции по умолчанию, так что вы можете быстро начать работу без необходимости конфигурации.
Когда вы захотите начать настройку внешнего вида вашего сайта на Starlight, это руководство поможет вам в этом.

## Добавление своего логотипа

Добавление логотипа в заголовок сайта - это быстрый способ добавить индивидуальность на ваш сайт Starlight.

<Steps>

1. Добавьте изображение вашего логотипа в директорию `src/assets/`:

   <FileTree>

   - src/
     - assets/
       - **my-logo.svg**
     - content/
   - astro.config.mjs

   </FileTree>

2. Укажите путь к вашему логотипу у параметра [`logo.src`](/ru/reference/configuration/#logo) в `astro.config.mjs`:

   ```diff lang="js"
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Документация с моим логотипом',
   			logo: {
   +				src: './src/assets/my-logo.svg',
   			},
   		}),
   	],
   });
   ```

</Steps>

По умолчанию логотип будет отображаться рядом с `title` вашего сайта.
Если ваше изображение логотипа уже включает в себя название сайта, вы можете визуально скрыть текст заголовка, через параметр `replacesTitle`.
Текст `title` всё равно будет доступен для экранных читалок, чтобы заголовок оставался доступным.

```js {5}
starlight({
  title: 'Документация с моим логотипом',
  logo: {
    src: './src/assets/my-logo.svg',
    replacesTitle: true,
  },
}),
```

### Варианты логотипа для светлой и тёмной темы

Вы можете отображать разные версии вашего логотипа в светлом и тёмном режимах.

<Steps>

1. Добавьте изображения для каждого варианта в директорию `src/assets/`:

   <FileTree>

   - src/
     - assets/
       - **light-logo.svg**
       - **dark-logo.svg**
     - content/
   - astro.config.mjs

   </FileTree>

2. Укажите путь к вариантам вашего логотипа в параметрах `light` и `dark` вместо `src` в `astro.config.mjs`:

   ```diff lang="js"
   starlight({
     title: 'Документация с моим логотипом',
     logo: {
   +    light: './src/assets/light-logo.svg',
   +    dark: './src/assets/dark-logo.svg',
     },
   }),
   ```

</Steps>

## Включение карты сайта

У Starlight есть встроенная поддержка создания карты сайта. Чтобы включить генерацию карты сайта, укажите ваш URL в качестве `site` в `astro.config.mjs`:

```js {4}
// astro.config.mjs

export default defineConfig({
	site: 'https://stargazers.club',
	integrations: [starlight({ title: 'Документация с картой сайта' })],
});
```

Узнайте, как [добавить ссылку на карту сайта в `robots.txt`](https://docs.astro.build/ru/guides/integrations-guide/sitemap/#sitemap-link-in-robotstxt) в документации Astro.

## Макеты страниц

По умолчанию страницы Starlight используют макет с боковой панелью и оглавлением, которое показывает заголовки текущей страницы.

Вы можете применить более широкий макет страницы без боковых панелей, установив [`template: splash`](/ru/reference/frontmatter/#template) в метаданных страницы.
Это хорошо подходит для лендингов, вы можете увидеть живой пример на [главной странице этого сайта](/ru/).

```md {5}
---
# src/content/docs/index.md

title: Моя главная страница
template: splash
---
```

## Оглавление

Starlight отображает оглавление на каждой странице, чтобы читателям было проще перейти к интересующему их заголовку.
Вы можете настроить или даже отключить оглавление полностью в интеграции Starlight или отдельно для каждой страницы в метаданных.

По умолчанию заголовки `<h2>` и `<h3>` включены в оглавление. Укажите уровни заголовков, которые нужно включить на всем сайте, с помощью параметров `minHeadingLevel` и `maxHeadingLevel`, в [`tableOfContents`](/ru/reference/configuration/#tableofcontents). Переопределите эти значения для отдельных страниц, добавив свойства в [метаданные `tableOfContents`](/ru/reference/frontmatter/#tableofcontents):

<Tabs syncKey="config-type">
  <TabItem label="Метаданные">

```md {4-6}
---
# src/content/docs/example.md
title: Страница только с заголовками H2 в оглавлении
tableOfContents:
  minHeadingLevel: 2
  maxHeadingLevel: 2
---
```

  </TabItem>
  <TabItem label="Глобальный конфиг">

```js {7}
// astro.config.mjs

defineConfig({
	integrations: [
		starlight({
			title: 'Документация с изменённой конфигурацией оглавления',
			tableOfContents: { minHeadingLevel: 2, maxHeadingLevel: 2 },
		}),
	],
});
```

  </TabItem>
</Tabs>

Чтобы полностью отключить оглавление, установите параметр `tableOfContents` в значение `false`:

<Tabs syncKey="config-type">
  <TabItem label="Метаданные">

```md {4}
---
# src/content/docs/example.md
title: Страница без оглавления
tableOfContents: false
---
```

  </TabItem>
  <TabItem label="Глобальный конфиг">

```js {7}
// astro.config.mjs

defineConfig({
	integrations: [
		starlight({
			title: 'Документация с глобально отключенным оглавлением',
			tableOfContents: false,
		}),
	],
});
```

  </TabItem>
</Tabs>

## Ссылки на социальные сети

Starlight имеет встроенную поддержку для добавления ссылок на ваши аккаунты в социальных сетях в заголовок сайта через параметр [`social`](/ru/reference/configuration/#social) в интеграции Starlight.

Каждый элемент массива `social` должен быть объектом с тремя свойствами:

- `icon`: одна из [встроенных иконок](/ru/reference/icons/) Starlight, например `"github"`.
- `label`: доступная подпись для ссылки, например `"GitHub"`.
- `href`: URL-адрес ссылки, например `"https://github.com/withastro/starlight"`.

Следующий пример добавляет ссылки на чат Astro в Discord и репозиторий Starlight на GitHub:

```js {9-16}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Документация с социальными ссылками',
			social: [
				{ icon: 'discord', label: 'Discord', href: 'https://astro.build/chat' },
				{
					icon: 'github',
					label: 'GitHub',
					href: 'https://github.com/withastro/starlight',
				},
			],
		}),
	],
});
```

## Ссылки редактирования

Starlight может отображать ссылку «Редактировать страницу» в нижней части каждой страницы.
Это упрощает для читателя поиск файла, который можно редактировать, чтобы улучшить документацию.
Особенно это может помочь open-source проектам, упрощая процесс внесения вклада от сообщества.

Чтобы включить ссылки редактирования, установите URL в параметре [`editLink.baseUrl`](/ru/reference/configuration/#editlink), для редактирования репозитория.
Значение `editLink.baseUrl` будет добавлено в начало пути текущей страницы, чтобы сформировать полную ссылку для редактирования.

Примеры:

- GitHub: `https://github.com/USER_NAME/REPO_NAME/edit/BRANCH_NAME/`
- GitLab: `https://gitlab.com/USER_NAME/REPO_NAME/-/edit/BRANCH_NAME/`

Если ваш проект Starlight не находится в корне вашего репозитория, включите путь к проекту в конце базового URL.

В этом примере показана настройка ссылки для редактирования документации Starlight, которая находится в подкаталоге `docs/` в ветке `main` репозитория `withastro/starlight` на GitHub:

```js {9-11}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Документация со ссылками для редактирования',
			editLink: {
				baseUrl: 'https://github.com/withastro/starlight/edit/main/docs/',
			},
		}),
	],
});
```

## Настройка страницы 404

Сайты на Starlight по умолчанию отображают простую страницу 404.
Вы можете настроить это, добавив файл `404.md` (или `404.mdx`) в директорию `src/content/docs/`:

<FileTree>

- src/
  - content/
    - docs/
      - **404.md**
      - index.md
- astro.config.mjs

</FileTree>

Вы можете использовать другие макеты и настройки страниц Starlight в вашей странице 404.
Например, страница 404 по умолчанию использует макет [`splash`](#макеты-страниц) и компонент [`hero`](/ru/reference/frontmatter/#hero) в метаданных.

```md {4,6-8}
---
title: '404'
template: splash
editUrl: false
hero:
  title: '404'
  tagline: Страница не найдена. Проверьте URL или попробуйте использовать поиск.
---
```

### Отключение стандартной страницы 404

Если вашему проекту требуется полностью настроенный макет 404, вы можете создать маршрут `src/pages/404.astro` и установить параметр конфигурации [`disable404Route`](/ru/reference/configuration/#disable404route), чтобы отключить маршрут Starlight по умолчанию:

```js {9}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Документация с пользовательской страницей 404',
			disable404Route: true,
		}),
	],
});
```

## Пользовательские шрифты

По умолчанию Starlight использует шрифты семейства Sans-Serif, доступные на устройстве пользователя, для всего текста.
Это обеспечивает быструю загрузку документации с использованием шрифта, знакомого каждому пользователю, и не требует скачивания больших файлов шрифтов.

Если вам необходимо добавить пользовательский шрифт на ваш сайт Starlight, вы можете настроить шрифты в CSS-файлах или с помощью любой другой [техники оформления Astro](https://docs.astro.build/ru/guides/styling/).

### Настройка шрифтов

Если у вас уже есть файлы шрифтов, следуйте [руководству по локальной настройке](#настройка-локальных-шрифтов).
Чтобы использовать Google Fonts, следуйте [руководству по настройке Fontsource](#настройка-шрифта-из-fontsource).

#### Настройка локальных шрифтов

<Steps>

1. Добавьте ваши шрифты в директорию `src/fonts/` и создайте пустой файл `font-face.css`:

   <FileTree>

   - src/
     - content/
     - fonts/
       - **CustomFont.woff2**
       - **font-face.css**
   - astro.config.mjs

   </FileTree>

2. Добавьте объявление [`@font-face`](https://developer.mozilla.org/ru/docs/Web/CSS/@font-face) для каждого из ваших шрифтов в файл `src/fonts/font-face.css`.
   Используйте относительный путь к шрифту в функции `url()`.

   ```css
   /* src/fonts/font-face.css */

   @font-face {
   	font-family: 'Custom Font';
   	/* Используйте относительный путь к шрифту в функции `url()`. */
   	src: url('./CustomFont.woff2') format('woff2');
   	font-weight: normal;
   	font-style: normal;
   	font-display: swap;
   }
   ```

3. Добавьте путь к вашему файлу `font-face.css` в массив `customCss` в `astro.config.mjs`:

   ```diff lang="js"
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Документация с пользовательским шрифтом',
   			customCss: [
   +				// Относительный путь к вашему CSS-файлу с @font-face.
   +				'./src/fonts/font-face.css',
   			],
   		}),
   	],
   });
   ```

</Steps>

#### Настройка шрифта из Fontsource

Проект [Fontsource](https://fontsource.org/) упрощает использование шрифтов Google Fonts и других open-source шрифтов.
Проект предоставляет npm-пакеты, для использования шрифтов, которые вас интересуют, и включает готовые CSS-файлы, которые можно добавить в ваш проект.

<Steps>

1.  Найдите шрифт, который вы хотите использовать, в [каталоге Fontsource](https://fontsource.org/).
    В данном примере будет использоваться шрифт [IBM Plex Serif](https://fontsource.org/fonts/ibm-plex-serif).

2.  Установите пакет для выбранного вами шрифта.
    Вы можете найти имя пакета, нажав «Install» на странице шрифта Fontsource.

         <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npm install @fontsource/ibm-plex-serif
    ```

           </TabItem>

        <TabItem label="pnpm">

    ```sh
    pnpm add @fontsource/ibm-plex-serif
    ```

           </TabItem>

        <TabItem label="Yarn">

    ```sh
    yarn add @fontsource/ibm-plex-serif
    ```

           </TabItem>

      </Tabs>

3.  Добавьте CSS-файлы Fontsource в массив `customCss` в `astro.config.mjs`:

    ```diff lang="js"
    // astro.config.mjs
    import { defineConfig } from 'astro/config';
    import starlight from '@astrojs/starlight';

    export default defineConfig({
    	integrations: [
    		starlight({
    			title: 'Документация с пользовательским шрифтом',
    			customCss: [
    +				// Файлы Fontsource для regular и semi-bold шрифтов.
    +				'@fontsource/ibm-plex-serif/400.css',
    +				'@fontsource/ibm-plex-serif/600.css',
    			],
    		}),
    	],
    });
    ```

    Fontsource предоставляет несколько CSS-файлов для каждого шрифта. См. [документацию Fontsource](https://fontsource.org/docs/getting-started/install#4-weights-and-styles) по включению различных начертаний и стилей, чтобы понять, какие использовать.

</Steps>

### Использование шрифтов

Чтобы применить шрифт, который вы настроили для вашего сайта, используйте имя вашего выбранного шрифта в [CSS-файле](/ru/guides/css-and-tailwind/#ваши-css-стили).
Например, чтобы заменить шрифт по умолчанию везде, установите пользовательское свойство `--sl-font`:

```css
/* src/styles/custom.css */

:root {
	--sl-font: 'IBM Plex Serif', serif;
}
```

Вы также можете написать более точные стили CSS, если хотите применить ваш шрифт более выборочно.
Например, чтобы установить шрифт только для основного контента, но не для боковых панелей:

```css
/* src/styles/custom.css */

main {
	font-family: 'IBM Plex Serif', serif;
}
```

Следуйте [инструкциям по настройке пользовательских стилей CSS](/ru/guides/css-and-tailwind/#ваши-css-стили), чтобы добавить свои стили на ваш сайт.


================================================
FILE: docs/src/content/docs/ru/guides/i18n.mdx
================================================
---
title: Интернационализация (i18n)
description: Узнайте, как настроить ваш сайт на Starlight для поддержки нескольких языков.
---

import { FileTree, Steps } from '@astrojs/starlight/components';

Starlight обеспечивает встроенную поддержку многоязычных сайтов, включая маршрутизацию, резервный контент и полную поддержку языков с письмом справа налево (RTL).

## Настройка i18n

<Steps>

1. Сообщите Starlight о поддерживаемых вами языках, передав свойства [`locales`](/ru/reference/configuration/#locales) и [`defaultLocale`](/ru/reference/configuration/#defaultlocale) в интеграцию Starlight:

   ```js {9-26}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Моя документация',
   			// Устанавливаем «Русский» как язык по умолчанию для этого сайта
   			defaultLocale: 'ru',
   			locales: {
   				// Документация на английском в `src/content/docs/en/`
   				en: {
   					label: 'English',
   				},
   				// Документация на китайском в `src/content/docs/zh-cn/`
   				'zh-cn': {
   					label: '简体中文',
   					lang: 'zh-CN',
   				},
   				// Документация на русском в `src/content/docs/ru/`
   				ru: {
   					label: 'Русский',
   					lang: 'ru',
   				},
   			},
   		}),
   	],
   });
   ```

   `defaultLocale` будет использоваться для резервного контента и текста UI, поэтому выберите язык, на котором вы скорее всего начнете писать контент или для которого у вас уже есть материалы.

2. Создайте каталог для каждого языка в `src/content/docs/`.
   Например, для показанной выше конфигурации создайте следующие папки:

   <FileTree>

   - src/
     - content/
       - docs/
         - en/
         - ru/
         - zh-cn/

   </FileTree>

3. Теперь вы можете добавлять контент в свои языковые каталоги. Используйте одно и то же имя файла для связывания страниц на разных языках и воспользуйтесь полным набором функций i18n Starlight, включая резервный контент, уведомления о переводе и многое другое.

   Например, создайте `ru/index.md` и `en/index.md` для отображения главной страницы на русском и английском языках.

</Steps>

Для более продвинутых сценариев использования i18n Starlight также поддерживает настройку интернационализации с помощью [опции `i18n` Astro](https://docs.astro.build/ru/guides/internationalization/#%D0%BD%D0%B0%D1%81%D1%82%D1%80%D0%BE%D0%B9%D0%BA%D0%B0-i18n-%D0%BC%D0%B0%D1%80%D1%88%D1%80%D1%83%D1%82%D0%B8%D0%B7%D0%B0%D1%86%D0%B8%D0%B8).

### Использование корневой локали

Вы можете использовать «корневую» локаль для отображения языка без префикса i18n в его пути. Например, если русский является вашей корневой локалью, путь к странице на русском языке будет выглядеть как `/about` вместо `/ru/about`.

Чтобы установить корневую локаль, используйте ключ `root` в вашей конфигурации `locales`. Если корневая локаль также является локалью по умолчанию для вашего контента, удалите `defaultLocale` или установите его значение как `'root'`.

```js {9,11-14}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Моя документация',
			defaultLocale: 'root', // опционально
			locales: {
				root: {
					label: 'Русский',
					lang: 'ru', // параметр lang обязателен для корневых локалей
				},
				en: {
					label: 'English',
					lang: 'en',
				},
			},
		}),
	],
});
```

При использовании локали `root` храните страницы для этого языка непосредственно в `src/content/docs/`, а не в отдельной языковой папке. Например, вот файлы домашней страницы для английского и русского языков при использовании приведённой выше конфигурации:

<FileTree>

- src/
  - content/
    - docs/
      - **index.md**
      - en/
        - **index.md**

</FileTree>

#### Одноязычные сайты

По умолчанию, Starlight является одноязычным сайтом, с английским языком. Чтобы создать сайт на другом языке, укажите его как `root` в вашей конфигурации `locales`:

```diff lang="js" {10-13}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Моя документация',
			locales: {
				root: {
					label: 'Русский',
					lang: 'ru',
				},
			},
		}),
	],
});
```

Это позволяет вам переопределить язык по умолчанию для Starlight без включения других функций интернационализации для многоязычных сайтов, таких как выбор языка.

## Резервный контент

Starlight предполагает, что вы создадите эквивалентные страницы на всех поддерживаемых языках. Например, если у вас есть файл `en/about.md`, создайте файл `about.md` для каждого другого языка, который вы поддерживаете. Это позволяет Starlight предоставлять автоматически резервный контент для страниц, которые ещё не были переведены.

Если перевод для языка ещё не доступен, Starlight покажет читателям контент этой страницы на языке по умолчанию (установленном через `defaultLocale`). Например, если вы ещё не создали французскую версию вашей страницы «О нас» и вашим языком по умолчанию является английский, посетители `/fr/about` увидят английский контент из `/en/about` с уведомлением о том, что эта страница ещё не была переведена. Это помогает вам добавлять контент на вашем языке по умолчанию и постепенно переводить его, когда у ваших переводчиков есть время.

## Перевод заголовка сайта

По умолчанию Starlight использует одно и то же название сайта для всех языков.
Если вам нужно настроить заголовок для каждой локали, вы можете передать объект [`title`](/ru/reference/configuration/#title-обязателен) в опциях Starlight:

```diff lang="js"
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
  integrations: [
    starlight({
-     title: 'Моя документация',
+     title: {
+       ru: "Моя документация",
+       'zh-CN': '我的文档',
+     },
      defaultLocale: 'ru',
      locales: {
        ru: { label: 'Русский' },
        'zh-cn': { label: '简体中文', lang: 'zh-CN' },
      },
    }),
  ],
});
```

## Перевод интерфейса Starlight

import LanguagesList from '~/components/languages-list.astro';
import UIStringsList from '~/components/ui-strings-list.astro';

Кроме размещения переведённых файлов с контентом, Starlight позволяет вам переводить текст интерфейсе (например, заголовок «На этой странице» в оглавлении), чтобы ваши читатели могли полностью погрузиться в ваш сайт на выбранном языке.

<LanguagesList startsSentence /> — все переведённые строки пользовательского
интерфейса на указанных языках предоставляются «из коробки», и мы приветствуем
[вклад в добавление новых
языков](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md).

Вы можете добавить переводы для дополнительных языков, которые вы поддерживаете — или переопределить наши стандартные тексты — через коллекцию данных `i18n`.

<Steps>

1. Сконфигурируйте коллекцию данных `i18n` в `src/content.config.ts`, если она ещё не настроена:

   ```diff lang="js" ins=/, (i18nLoader|i18nSchema)/
   // src/content.config.ts
   import { defineCollection } from 'astro:content';
   import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
   import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';

   export const collections = {
    docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
   +  i18n: defineCollection({ loader: i18nLoader(), schema: i18nSchema() }),
   };
   ```

2. Создайте файл JSON в `src/content/i18n/` для каждой дополнительной локали, для которой вы хотите добавить строки перевода интерфейса.
   Например, так можно добавить файлы перевода для арабского и русского:

   <FileTree>

   - src/
     - content/
       - i18n/
         - ar.json
         - ru.json

   </FileTree>

3. Добавьте переводы для ключей, которые вы хотите перевести, в файлы JSON. Переводите только значения, оставляя ключи на английском языке (например, `"search.label": "Поиск"`).

   Это английские значения по умолчанию для существующих строк, с которыми поставляется Starlight:

   <UIStringsList />

   Блоки кода Starlight основаны на библиотеке [Expressive Code](https://expressive-code.com/).
   Вы можете установить переводы для строк пользовательского интерфейса в том же файле JSON, используя ключи `expressiveCode`:

   ```json
   {
   	"expressiveCode.copyButtonCopied": "Copied!",
   	"expressiveCode.copyButtonTooltip": "Copy to clipboard",
   	"expressiveCode.terminalWindowFallbackTitle": "Terminal window"
   }
   ```

   Модальное окно поиска в Starlight работает с помощью библиотеки [Pagefind](https://pagefind.app/).
   Вы можете установить переводы для пользовательского интерфейса Pagefind в том же JSON-файле, используя ключи `pagefind`:

   ```json
   {
   	"pagefind.clear_search": "Clear",
   	"pagefind.load_more": "Load more results",
   	"pagefind.search_label": "Search this site",
   	"pagefind.filters_label": "Filters",
   	"pagefind.zero_results": "No results for [SEARCH_TERM]",
   	"pagefind.many_results": "[COUNT] results for [SEARCH_TERM]",
   	"pagefind.one_result": "[COUNT] result for [SEARCH_TERM]",
   	"pagefind.alt_search": "No results for [SEARCH_TERM]. Showing results for [DIFFERENT_TERM] instead",
   	"pagefind.search_suggestion": "No results for [SEARCH_TERM]. Try one of the following searches:",
   	"pagefind.searching": "Searching for [SEARCH_TERM]..."
   }
   ```

</Steps>

### Расширение схемы переводов

Добавьте пользовательские ключи в словари переводов вашего сайта, установив `extend` в опциях `i18nSchema()`.
В следующем примере к ключам по умолчанию добавляется новый необязательный ключ `custom.label`:

```diff lang="js"
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { z } from 'astro/zod';
import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';

export const collections = {
	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
	i18n: defineCollection({
		loader: i18nLoader(),
		schema: i18nSchema({
+			extend: z.object({
+				'custom.label': z.string().optional(),
+			}),
		}),
	}),
};
```

Дополнительную информацию о схемах коллекции контента см. в разделе [Определение схемы коллекции](https://docs.astro.build/ru/guides/content-collections/#%D0%BE%D0%BF%D1%80%D0%B5%D0%B4%D0%B5%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5-%D1%81%D1%85%D0%B5%D0%BC%D1%8B-%D0%BA%D0%BE%D0%BB%D0%BB%D0%B5%D0%BA%D1%86%D0%B8%D0%B8) в документации Astro.

## Использование UI-переводов

Вы можете получить доступ к [встроенным строкам пользовательского интерфейса](/ru/guides/i18n/#перевод-интерфейса-starlight) Starlight, а также к [пользовательским](/ru/guides/i18n/#расширение-схемы-переводов) и [предоставляемым плагинами](/ru/reference/plugins/#injecttranslations) строкам пользовательского интерфейса через единый API на базе [i18next](https://www.i18next.com/).
Это включает поддержку таких функций, как [интерполяция](https://www.i18next.com/translation-function/interpolation) и [плюрализация](https://www.i18next.com/translation-function/plurals).

В компонентах Astro этот API доступен как часть [глобального объекта `Astro`](https://docs.astro.build/en/reference/api-reference/#locals) в виде `Astro.locals.t`:

```astro title="example.astro"
<p dir={Astro.locals.t.dir()}>
	{Astro.locals.t('404.text')}
</p>
```

Вы также можете использовать API в [эндпойнтах](https://docs.astro.build/ru/guides/endpoints/), где объект `locals` доступен как часть контекста [эндпойнта](https://docs.astro.build/en/reference/api-reference/#locals):

```ts title="src/pages/404.ts"
export const GET = (context) => {
	return new Response(context.locals.t('404.text'));
};
```

В контексте плагина Starlight вы можете использовать хелпер [`useTranslations()`](/ru/reference/plugins/#usetranslations) для доступа к этому API для конкретного языка.
Дополнительную информацию смотрите в [справочнике по плагинам](/ru/reference/plugins/).

### Рендеринг строки пользовательского интерфейса

Отрисовка строк пользовательского интерфейса с помощью функции `locals.t()`.
Это экземпляр функции i18next `t()`, которая принимает в качестве первого аргумента строку-ключ UI и возвращает соответствующий перевод для текущего языка.

Например, задан файл пользовательского перевода со следующим содержанием:

```json title="src/content/i18n/ru.json"
{
	"link.astro": "Документация Astro",
	"link.astro.custom": "Документация Astro о {{feature}}"
}
```

Первую строку пользовательского интерфейса можно отобразить, передав `'link.astro'` в функцию `t()`:

```astro {3}
<!-- src/components/Example.astro -->
<a href="https://docs.astro.build/">
	{Astro.locals.t('link.astro')}
</a>
<!-- Отрисовывает: <a href="...">Документация Astro</a> -->
```

Вторая строка пользовательского интерфейса использует [синтаксис интерполяции](https://www.i18next.com/translation-function/interpolation) i18next для размещения `{{feature}}`.
Значение для `feature` должно быть задано в объекте options, передаваемом в качестве второго аргумента в `t()`:

```astro {3}
<!-- src/components/Example.astro -->
<a href="https://docs.astro.build/ru/guides/astro-db/">
	{Astro.locals.t('link.astro.custom', { feature: 'Astro DB' })}
</a>
<!-- Отрисовывает: <a href="...">Документация Astro о Astro DB</a> -->
```

Подробнее о том, как использовать функцию `t()` для интерполяции, форматирования и т. д., см. в [документации i18next](https://www.i18next.com/overview/api#t).

### Расширенные API

#### `t.all()`

Функция `locals.t.all()` возвращает объект, содержащий все строки пользовательского интерфейса, доступные для текущей локали.

```astro
---
// src/components/Example.astro
const allStrings = Astro.locals.t.all();
//    ^
//    {
//      "skipLink.label": "Перейти к содержанию",
//      "search.label": "Поиск",
//      …
//    }
---
```

#### `t.exists()`

Чтобы проверить, существует ли ключ перевода, используйте функцию `locals.t.exists()` с ключом перевода в качестве первого аргумента.
Передайте необязательный второй аргумент, если нужно проверить наличие перевода для определённой локали.

```astro
---
// src/components/Example.astro
const keyExists = Astro.locals.t.exists('a.key');
//    ^ true
const keyExistsInFrench = Astro.locals.t.exists('other.key', { lngs: ['fr'] });
//    ^ false
---
```

Дополнительную информацию см. в статье [`exists()` в документации i18next](https://www.i18next.com/overview/api#exists).

#### `t.dir()`

Функция `locals.t.dir()` возвращает направление текста текущей или определённой локали.

```astro
---
// src/components/Example.astro
const currentDirection = Astro.locals.t.dir();
//    ^
//    'ltr'
const arabicDirection = Astro.locals.t.dir('ar');
//    ^
//    'rtl'
---
```

Дополнительную информацию см. в статье [`dir()` в документации i18next](https://www.i18next.com/overview/api#dir).

## Доступ к текущей локали

Вы можете использовать [`Astro.currentLocale`](https://docs.astro.build/en/reference/api-reference/#currentlocale) для получения текущей локали в компонентах `.astro`.

Следующий пример считывает текущую локаль и использует её с помощью хелпера [`getRelativeLocaleUrl()`](https://docs.astro.build/ru/reference/modules/astro-i18n/#getrelativelocaleurl) для генерации ссылки на страницу «О сайте» на текущем языке:

```astro
---
// src/components/AboutLink.astro
import { getRelativeLocaleUrl } from 'astro:i18n';
---

<a href={getRelativeLocaleUrl(Astro.currentLocale ?? 'en', 'about')}>О сайте</a>
```


================================================
FILE: docs/src/content/docs/ru/guides/overriding-components.mdx
================================================
---
title: Переопределение компонентов
description: Узнайте, как переопределить встроенные компоненты Starlight, чтобы добавить пользовательские элементы в интерфейс вашего сайта документации.
---

import { Steps } from '@astrojs/starlight/components';

Пользовательский интерфейс и параметры конфигурации Starlight по умолчанию разработаны таким образом, чтобы быть гибкими и работать с разнообразным контентом. Большую часть внешнего вида Starlight по умолчанию можно настроить с помощью [CSS](/ru/guides/css-and-tailwind/) и [параметров конфигурации](/ru/guides/customization/).

Если вам нужно больше, чем возможно из коробки, Starlight поддерживает создание собственных пользовательских компонентов для расширения или переопределения (полной замены) компонентов по умолчанию.

## Когда переопределять

Переопределение стандартных компонентов Starlight может быть полезно, когда:

- Вы хотите изменить внешний вид интерфейса Starlight, если это невозможно сделать с использованием [пользовательских CSS](/ru/guides/css-and-tailwind/).
- Вы хотите изменить поведение интерфейса Starlight.
- Вы хотите добавить какой-то дополнительный интерфейс наряду с существующим интерфейсом Starlight.

## Как выполнить переопределение

<Steps>

1. Выберите компонент Starlight, который вы хотите переопределить.
   Вы можете найти полный список компонентов в [Справочнике по переопределениям](/ru/reference/overrides/).

   :::tip
   Не уверены, какой компонент нужно переопределить? Используйте [интерактивную карту переопределений Starlight](https://starlight-overrides-map.netlify.app/), чтобы узнать названия UI-компонентов Starlight.
   :::

   В этом примере будет переопределён компонент [`SocialIcons`](/ru/reference/overrides/#socialicons) в навигационной панели страницы.

2. Создайте компонент Astro для замены компонента Starlight.
   В этом примере отображается ссылка для связи.

   ```astro
   ---
   // src/components/EmailLink.astro

   const email = 'houston@example.com';
   ---

   <a href=`mailto:${email}`>Напишите мне</a>
   ```

3. Сообщите Starlight, что нужно использовать ваш компонент, указав его в параметре конфигурации [`components`](/ru/reference/configuration/#components) в `astro.config.mjs`:

   ```js {9-12}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Моя документация, с переопределением компонентов',
   			components: {
   				// Переопределение компонента `SocialIcons`.
   				SocialIcons: './src/components/EmailLink.astro',
   			},
   		}),
   	],
   });
   ```

</Steps>

## Переиспользование встроенного компонента

Вы можете работать со стандартными UI-компонентами Starlight так же, как и со своими собственными: импортировать их и использовать в своих компонентах. Это позволяет вам сохранить весь интерфейс Starlight в рамках вашего дизайна, добавляя свой интерфейс рядом с ними.

Пример ниже показывает компонент, который отображает ссылку на электронную почту наряду со стандартным компонентом `SocialIcons`:

```astro {3,7}
---
// src/components/EmailLink.astro
import Default from '@astrojs/starlight/components/SocialIcons.astro';
---

<a href="mailto:houston@example.com"> Связаться с нами по электронной почте </a>
<Default><slot /></Default>
```

При рендеринге встроенного компонента внутри пользовательского компонента добавьте [`<slot />`](https://docs.astro.build/ru/basics/astro-components/#%D1%81%D0%BB%D0%BE%D1%82%D1%8B) внутрь компонента по умолчанию. Это гарантирует, что если компоненту переданы дочерние элементы, Astro будет знать, где их отобразить.

Если вы повторно используете компоненты [`PageFrame`](/ru/reference/overrides/#pageframe) или [`TwoColumnContent`](/ru/reference/overrides/#twocolumncontent), содержащие [именованные слоты](https://docs.astro.build/ru/basics/astro-components/#именованые-слоты), вам также необходимо [перенести](https://docs.astro.build/ru/basics/astro-components/#перенос-слотов) эти слоты.

Ниже показан пользовательский компонент, который повторно использует компонент `TwoColumnContent`, содержащий дополнительный именованный слот `right-sidebar`, нуждающийся в переносе:

```astro {8}
---
// src/components/CustomContent.astro
import Default from '@astrojs/starlight/components/TwoColumnContent.astro';
---

<Default>
	<slot />
	<slot name="right-sidebar" slot="right-sidebar" />
</Default>
```

## Использование данных страницы

При переопределении компонента Starlight вы можете получить доступ к глобальному объекту [`starlightRoute`](/ru/guides/route-data/), который содержит все данные для текущей страницы.
Это позволяет вам использовать эти значения для управления тем, как ваш компонент будет отображаться.

В следующем примере заменяющий компонент [`PageTitle`](/ru/reference/overrides/#pagetitle) отображает заголовок текущей страницы, установленный в метаданных контента:

```astro {4} "{title}"
---
// src/components/Title.astro

const { title } = Astro.locals.starlightRoute.entry.data;
---

<h1 id="_top">{title}</h1>

<style>
	h1 {
		font-family: 'Comic Sans';
	}
</style>
```

Узнайте больше обо всех доступных свойствах в [Справочнике по данным маршрута](/ru/reference/route-data/).

### Переопределение только на определённых страницах

Переопределение компонентов применяется ко всем страницам. Тем не менее, вы можете осуществлять условную отрисовку, используя значения из `starlightRoute`, чтобы определить, когда показывать ваш интерфейс, когда показывать интерфейс Starlight, или даже когда показывать что-то совершенно другое.

В следующем примере компонент, переопределяющий [`Footer`](/ru/reference/overrides/#footer) от Starlight, отображает надпись «Создано с помощью Starlight 🌟» только на главной странице, а на всех остальных страницах показывает футер по умолчанию:

```astro
---
// src/components/ConditionalFooter.astro
import Default from '@astrojs/starlight/components/Footer.astro';

const isHomepage = Astro.locals.starlightRoute.id === '';
---

{
	isHomepage ? (
		<footer>Создано с помощью Starlight 🌟</footer>
	) : (
		<Default>
			<slot />
		</Default>
	)
}
```

Узнайте больше об отрисовке по условию в руководстве [Синтаксис Astro](https://docs.astro.build/ru/basics/astro-syntax/#динамический-html).


================================================
FILE: docs/src/content/docs/ru/guides/pages.mdx
================================================
---
title: Страницы
description: Узнайте, как создавать страницы вашего сайта документации и управлять ими с помощью Starlight.
sidebar:
  order: 1
tableOfContents:
  maxHeadingLevel: 4
---

Starlight генерирует HTML-страницы вашего сайта на основе вашего контента с гибкими опциями, предоставляемыми через интерфейс Markdown.
Кроме того, проекты Starlight имеют полный доступ к [мощным инструментам создания страниц Astro](https://docs.astro.build/ru/basics/astro-pages/).
В этом руководстве объясняется, как работает генерация страниц в Starlight.

## Содержимое страниц

### Форматы файлов

Starlight поддерживает создание контента в Markdown и MDX без необходимости настройки.
Вы можете добавить поддержку Markdoc, следуя [руководству](/ru/guides/authoring-content/#markdoc).

### Добавление страниц

Добавляйте новые страницы на свой сайт, создавая файлы `.md` или `.mdx` в `src/content/docs/`.
Используйте подпапки для организации файлов и создания нескольких сегментов пути.

Например, следующая файловая структура будет генерировать страницы `example.com/hello-world` и `example.com/reference/faq`:

import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src/
  - content/
    - docs/
      - hello-world.md
      - reference/
        - faq.md

</FileTree>

### Типобезопасные метаданные

Все страницы Starlight используют настраиваемый [общий набор свойств метаданных](/ru/reference/frontmatter/) для контроля отображения страницы:

```md
---
title: Привет, мир!
description: Это страница на моем сайте, работающем на Starlight
---
```

Если вы что-то забудете, Starlight сообщит вам об этом.

## Пользовательские страницы

Для расширенных вариантов использования вы можете добавлять собственные страницы, создав каталог `src/pages/`.
Каталог `src/pages/` использует [маршрутизацию на основе файлов Astro](https://docs.astro.build/ru/basics/astro-pages/#%D0%BC%D0%B0%D1%80%D1%88%D1%80%D1%83%D1%82%D0%B8%D0%B7%D0%B0%D1%86%D0%B8%D1%8F-%D0%BD%D0%B0-%D0%BE%D1%81%D0%BD%D0%BE%D0%B2%D0%B5-%D1%84%D0%B0%D0%B9%D0%BB%D0%BE%D0%B2) и включает поддержку файлов с расширением `.astro` помимо других форматов страниц.
Это полезно, если вам нужно создать страницу с полностью настраиваемым макетом или создать страницу из альтернативного источника данных.

Например, в этом проекте содержимое Markdown смешивается в `src/content/docs/` с маршрутами Astro и HTML в `src/pages/`:

<FileTree>

- src/
  - content/
    - docs/
      - hello-world.md
  - pages/
    - custom.astro
    - archived.html

</FileTree>

Подробнее читайте в [руководстве «Страницы» в документации Astro](https://docs.astro.build/ru/basics/astro-pages/).

### Использование дизайна Starlight на пользовательских страницах

Чтобы использовать макет Starlight на пользовательских страницах, оберните содержимое страницы [компонентом `<StarlightPage>`](#компонент-starlightpage).
Это может быть полезно, если вы динамически генерируете контент, но всё же хотите использовать дизайн Starlight.

Чтобы добавить ссылки-якоря к заголовкам, соответствующие стилю ссылок-якорей Markdown в Starlight, вы можете использовать компонент [`<AnchorHeading>`](#компонент-anchorheading) на своих пользовательских страницах.

```astro
---
// src/pages/custom-page/example.astro
import StarlightPage from '@astrojs/starlight/components/StarlightPage.astro';
import AnchorHeading from '@astrojs/starlight/components/AnchorHeading.astro';
import CustomComponent from './CustomComponent.astro';
---

<StarlightPage frontmatter={{ title: 'Моя персонализированная страница' }}>
	<p>Это пользовательская страница с пользовательским компонентом:</p>
	<CustomComponent />

	<AnchorHeading level="2" id="learn-more">Узнать больше</AnchorHeading>
	<p>
		<a href="https://starlight.astro.build/"
			>Узнайте больше в документации Starlight</a
		>
	</p>
</StarlightPage>
```

#### Компонент `<StarlightPage>`

Компонент `<StarlightPage />` отображает полную страницу контента с использованием макета и стилей Starlight.

```astro
---
import StarlightPage from '@astrojs/starlight/components/StarlightPage.astro';
---

<StarlightPage frontmatter={{ title: 'Моя пользовательская страница' }}>
	<!-- Содержимое пользовательской страницы -->
</StarlightPage>
```

Компонент `<StarlightPage />` принимает следующие параметры.

##### `frontmatter`

**обязательный**  
**тип:** `StarlightPageFrontmatter`

Установка [метаданных](/ru/reference/frontmatter/) для этой страницы, аналогично метаданным на страницах Markdown.
Свойство [`title`](/ru/reference/frontmatter/#title-обязательно) является обязательным, а все остальные свойства — нет.

Следующие свойства отличаются от метаданных Markdown:

- Свойство [`slug`](/ru/reference/frontmatter/#slug) не поддерживается и устанавливается автоматически на основе URL-адреса пользовательской страницы.
- Свойство [`editUrl`](/ru/reference/frontmatter/#editurl) требует указания URL-адреса для отображения ссылки на редактирование.
- Свойство [`sidebar`](/ru/reference/frontmatter/#sidebar) для настройки отображения страницы в [автогенерируемых группах ссылок](/ru/reference/configuration/#sidebar) недоступно. Страницы, использующие компонент `<StarlightPage />`, не являются частью коллекции и не могут быть добавлены в автоматически созданную группу боковой панели.
- Свойство [`draft`](/ru/reference/frontmatter/#draft) лишь отображает [уведомление](/ru/reference/overrides/#draftcontentnotice) о том, что страница является черновиком, но не исключает её автоматически из продакшен-сборок.

##### `sidebar`

**тип:** [`SidebarItem[]`](/ru/reference/configuration/#sidebaritem)  
**по умолчанию:** боковая панель, созданная на основе [глобальной конфигурации `sidebar`](/ru/reference/configuration/#sidebar)

Предоставление настраиваемой боковой панели навигации для этой страницы.
Если этот параметр не установлен, на странице будет использоваться глобальная боковая панель по умолчанию.

Например, следующая страница переопределяет стандартную боковую панель со ссылкой на главную страницу и группой ссылок на другие пользовательские страницы.

```astro {3-13}
<StarlightPage
	frontmatter={{ title: 'Орион' }}
	sidebar={[
		{ label: 'Главная', link: '/' },
		{
			label: 'Созвездия',
			items: [
				{ label: 'Андромеда', link: '/andromeda/' },
				{ label: 'Орион', link: '/orion/' },
				{ label: 'Малая Медведица', link: '/ursa-minor/', badge: 'Заглушка' },
			],
		},
	]}
>
	Пример контента.
</StarlightPage>
```

Подробнее о доступных вариантах настройки боковой панели см. в руководстве [Боковая панель](/ru/guides/sidebar/).

##### `hasSidebar`

**тип:** `boolean`  
**по умолчанию:** `false` если [`frontmatter.template`](/ru/reference/frontmatter/#template) имеет значение `'splash'`, в противном случае `true`

Отображение боковой панели на этой странице.

##### `headings`

**тип:** `{ depth: number; slug: string; text: string }[]`  
**по умолчанию:** `[]`

Предоставление массива всех заголовков на этой странице.
Starlight сгенерирует оглавление страницы из этих заголовков, если они предусмотрены.

##### `dir`

**тип:** `'ltr' | 'rtl'`  
**по умолчанию:** направление письма для текущей локали

Установка направления письма для содержимого этой страницы.

##### `lang`

**тип:** `string`  
**по умолчанию:** язык текущей локали

Установка языкового тега BCP-47 для содержимого этой страницы, например: `en`, `zh-CN` или `pt-BR`.

##### `isFallback`

**тип:** `boolean`  
**по умолчанию:** `false`

Отображение [резервного контента](/ru/guides/i18n/#резервный-контент), если перевод на текущий язык отсутствует.

#### Компонент `<AnchorHeading>`

Компонент `<AnchorHeading />` отображает HTML-элемент заголовка с кликабельной ссылкой-якорем, соответствующей стилям Markdown в Starlight.

```astro
---
import AnchorHeading from '@astrojs/starlight/components/AnchorHeading.astro';
---

<AnchorHeading level="2" id="sub-heading">Подзаголовок</AnchorHeading>
```

Он принимает следующие свойства, а также любые другие допустимые [глобальные HTML-атрибуты](https://developer.mozilla.org/ru/docs/Web/HTML/Reference/Global_attributes).

##### `level`

**обязательный**  
**тип:** `1 | 2 | 3 | 4 | 5 | 6`

Уровень заголовка для отображения.
Например, `level="1"` отобразит элемент `<h1>`.

##### `id`

**обязательный**  
**тип:** `string`

Уникальный идентификатор для этого заголовка.
Он будет использован в качестве атрибута `id` отображаемого заголовка, и значок якоря будет ссылаться на него.


================================================
FILE: docs/src/content/docs/ru/guides/project-structure.mdx
================================================
---
title: Структура проекта
description: Узнайте, как организовать файлы в вашем проекте Starlight.
---

Это руководство покажет вам, как организован проект Starlight и какую роль выполняют различные файлы в вашем проекте.

Проекты Starlight, как правило, следуют той же структуре файлов и каталогов, что и другие проекты Astro. Подробнее смотрите в [документации по структуре проекта Astro](https://docs.astro.build/ru/basics/project-structure/).

## Файлы и папки

- `astro.config.mjs` — Файл конфигурации Astro; включает интеграцию и конфигурацию Starlight.
- `src/content.config.ts` — Файл конфигурации коллекций контента; добавляет метаданные (frontmatter) от Starlight в ваш проект.
- `src/content/docs/` — Файлы контента. Starlight преобразует каждый файл `.md`, `.mdx` или `.mdoc` в этом каталоге в страницу на вашем сайте.
- `src/content/i18n/` (по необходимости) — Данные перевода для поддержки [интернационализации](/ru/guides/i18n/).
- `src/` — Другой исходный код и файлы (компоненты, стили, изображения и т. д.) для вашего проекта.
- `public/` — Статические активы (шрифты, значки, PDF и т. д.), которые не будут обработаны Astro.

## Пример проекта

Директория проекта Starlight может выглядеть так:

import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- public/
  - favicon.svg
- src/
  - assets/
    - logo.svg
    - screenshot.jpg
  - components/
    - CustomButton.astro
    - InteractiveWidget.jsx
  - content/
    - docs/
      - guides/
        - 01-getting-started.md
        - 02-advanced.md
      - index.mdx
  - content.config.ts
- astro.config.mjs
- package.json
- tsconfig.json

</FileTree>


================================================
FILE: docs/src/content/docs/ru/guides/route-data.mdx
================================================
---
title: Данные маршрута
description: Узнайте, как модель данных страниц Starlight используется для рендеринга ваших страниц и как вы можете её настроить.
---

import { Steps } from '@astrojs/starlight/components';

Когда Starlight рендерит страницу в вашей документации, он сначала создаёт объект данных маршрута, чтобы представить содержимое этой страницы.
В этом руководстве объясняется, как генерируются данные маршрута, как их использовать и как настроить, чтобы изменить поведение Starlight по умолчанию.

Полный список доступных свойств см. в [«Справочнике по данным маршрута»](/ru/reference/route-data/).

## Что такое данные маршрута?

Данные маршрута в Starlight — это объект, содержащий всю информацию, необходимую для рендеринга отдельной страницы.
Он включает сведения о текущей странице, а также данные, сгенерированные на основе вашей конфигурации Starlight.

## Использование данных маршрута

Все компоненты Starlight используют данные маршрута, чтобы определить, что рендерить на каждой странице.
Например, строка [`siteTitle`](/ru/reference/route-data/#sitetitle) используется для отображения заголовка сайта, а массив [`sidebar`](/ru/reference/route-data/#sidebar) — для рендеринга глобальной боковой навигации.

Вы можете получить доступ к этим данным через глобальный объект `Astro.locals.starlightRoute` в компонентах Astro:

```astro title="example.astro" {2}
---
const { siteTitle } = Astro.locals.starlightRoute;
---

<p>Заголовок этого сайта — «{siteTitle}»</p>
```

Это может быть полезно, например, при создании [переопределений компонентов](/ru/guides/overriding-components/), чтобы настроить отображаемый контент.

## Настройка данных маршрута

Данные маршрута в Starlight работают «из коробки» и не требуют дополнительной настройки.
Однако в сложных сценариях может понадобиться настроить данные маршрута для отдельных страниц или всех страниц, чтобы изменить отображение вашего сайта.

Этот процесс похож на [переопределение компонентов](/ru/guides/overriding-components/), но вместо изменения того, как Starlight рендерит ваши данные, вы изменяете сами данные, которые рендерит Starlight.

### Когда настраивать данные маршрута

Настройка данных маршрута полезна, когда вам нужно изменить способ обработки данных Starlight так, как это невозможно сделать с помощью существующих параметров конфигурации.

Например, вы можете захотеть отфильтровать элементы боковой панели или настроить заголовки для отдельных страниц.
Такие изменения не требуют модификации стандартных компонентов Starlight, а только данных, передаваемых этим компонентам.

### Как настроить данные маршрута

Вы можете настроить данные маршрута с помощью специальной формы «мидлвара».
Это функция, которая вызывается каждый раз при рендеринге страницы в Starlight и может изменять значения в объекте данных маршрута.

<Steps>

1. Создайте новый файл, экспортирующий функцию `onRequest`, используя утилиту `defineRouteMiddleware()` из Starlight:

   ```ts
   // src/routeData.ts
   import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

   export const onRequest = defineRouteMiddleware(() => {});
   ```

2. Укажите Starlight местоположение файла мидлвара для данных маршрута в `astro.config.mjs`:

   ```js ins={9}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Мой замечательный сайт документации',
   			routeMiddleware: './src/routeData.ts',
   		}),
   	],
   });
   ```

3. Обновите вашу функцию `onRequest`, чтобы изменить данные маршрута.

   Первый аргумент, который получит ваш мидлвар, — это [объект `context` Astro](https://docs.astro.build/en/reference/api-reference/).
   Он содержит полную информацию о рендеринге текущей страницы, включая текущий URL и `locals`.

   В этом примере мы сделаем нашу документацию более выразительной, добавляя восклицательный знак в конец заголовка каждой страницы.

   ```ts
   // src/routeData.ts
   import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

   export const onRequest = defineRouteMiddleware((context) => {
   	// Получаем запись из коллекции контента для этой страницы.
   	const { entry } = context.locals.starlightRoute;
   	// Обновляем заголовок, добавляя восклицательный знак.
   	entry.data.title = entry.data.title + '!';
   });
   ```

</Steps>

#### Несколько мидлваров для маршрута

Starlight также поддерживает использование нескольких мидлваров.
Установите `routeMiddleware` как массив путей, чтобы добавить более одного обработчика мидлвара:

```js {9}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Мой сайт с несколькими мидлварами',
			routeMiddleware: ['./src/middleware-one.ts', './src/middleware-two.ts'],
		}),
	],
});
```

#### Ожидание выполнения последующих мидлваров для маршрута

Чтобы дождаться выполнения мидлваров, расположенных позже в стеке, перед выполнением вашего кода, вы можете использовать `await` для вызова колбэка `next()`, передаваемого как второй аргумент в вашу функцию-мидлвар.
Это может быть полезно, если нужно дождаться выполнения мидлвара плагина перед внесением изменений. Например:

```ts "next" "await next();"
// src/routeData.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

export const onRequest = defineRouteMiddleware(async (context, next) => {
	// Ожидаем выполнения последующих мидлваров.
	await next();
	// Изменяем данные маршрута.
	const { entry } = context.locals.starlightRoute;
	entry.data.title = entry.data.title + '!';
});
```


================================================
FILE: docs/src/content/docs/ru/guides/sidebar.mdx
================================================
---
title: Боковая панель
description: Узнайте, как установить и настроить навигационные ссылки в боковой панели сайта Starlight.
---

import { FileTree } from '@astrojs/starlight/components';
import SidebarPreview from '~/components/sidebar-preview.astro';

Хорошо организованная боковая панель — ключ к хорошей документации, поскольку это один из основных способов навигации пользователей по вашему сайту. Starlight предоставляет полный набор опций для настройки макета и содержимого боковой панели.

## Стандартная боковая панель

По умолчанию Starlight автоматически генерирует боковую панель на основе структуры файловой системы вашей документации, используя свойство `title` каждого файла в качестве элемента боковой панели.

Например, при следующей структуре файлов:

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - andromeda.md
        - orion.md
      - stars/
        - betelgeuse.md

</FileTree>

Будет автоматически сгенерирована следующая боковая панель:

<SidebarPreview
	config={[
		{
			label: 'constellations',
			items: [
				{ label: 'Андромеда', link: '' },
				{ label: 'Орион', link: '' },
			],
		},
		{
			label: 'stars',
			items: [{ label: 'Бетельгейзе', link: '' }],
		},
	]}
/>

Узнайте больше об автоматически генерируемых боковых панелях в разделе [Автогенерируемые группы](#автогенерируемые-группы).

## Добавление ссылок и групп ссылок

Чтобы настроить ссылки и группы ссылок на боковой панели (внутри сворачиваемого заголовка), используйте свойство [`starlight.sidebar`](/ru/reference/configuration/#sidebar) в `astro.config.mjs`.

Комбинируя ссылки и группы, вы можете создавать разнообразные макеты боковой панели.

### Внутренние ссылки

Добавьте ссылку на страницу в `src/content/docs/`, используя объект со свойством `slug`.
Заголовок связанной страницы будет использоваться в качестве метки по умолчанию.

Например, со следующей конфигурацией:

```js "slug:"
starlight({
	sidebar: [
		{ slug: 'constellations/andromeda' },
		{ slug: 'constellations/orion' },
	],
});
```

И следующей файловой структурой:

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - andromeda.md
        - orion.md

</FileTree>

Будет создана следующая боковая панель:

<SidebarPreview
	config={[
		{ label: 'Андромеда', link: '' },
		{ label: 'Орион', link: '' },
	]}
/>

Чтобы переопределить значения, полученные из метаданных связанной страницы, вы можете добавить свойства `label`, [`translations`](#интернационализация) и [`attrs`](#пользовательские-html-атрибуты).

См. [Настройка сгенерированных ссылок](#настройка-сгенерированных-ссылок-через-метаданные) для получения более подробной информации об управлении внешним видом боковой панели из метаданных страницы.

#### Сокращенное обозначение внутренних ссылок

Внутренние ссылки также можно определить, указав только строку для обозначения страницы в качестве сокращения.

Например, следующая конфигурация эквивалентна конфигурации выше, в которой используется `slug`:

```js "slug:"
starlight({
	sidebar: ['constellations/andromeda', 'constellations/orion'],
});
```

### Другие ссылки

Добавьте ссылку на внешнюю страницу или страницу, не являющуюся документацией, используя объект со свойствами `label` и `link`.

```js "label:" "link:"
starlight({
	sidebar: [
		// Ссылка на страницу, не связанную с документацией, на этом сайте.
		{ label: 'Meteor Store', link: '/shop/' },
		// Внешняя ссылка на веб-сайт NASA.
		{ label: 'NASA', link: 'https://www.nasa.gov/' },
	],
});
```

Конфигурация выше создаёт следующую боковую панель:

<SidebarPreview
	config={[
		{ label: 'Meteor Store', link: '' },
		{ label: 'NASA', link: 'https://www.nasa.gov/' },
	]}
/>

### Группы

Вы можете структурировать вашу боковую панель, группируя связанные ссылки вместе под раскрывающимся заголовком.
Группы могут содержать как ссылки, так и другие подгруппы.

Добавьте группу, используя объект со свойствами `label` и `items`.
`label` будет использован как заголовок для группы.
Добавляйте ссылки или подгруппы в массив `items`.

```js /^\s*(label:|items:)/
starlight({
	sidebar: [
		// Группа ссылок с названием «Созвездия».
		{
			label: 'Созвездия',
			items: [
				'constellations/carina',
				'constellations/centaurus',
				// Вложенная группа ссылок для сезонных созвездий.
				{
					label: 'Сезонные',
					items: [
						'constellations/andromeda',
						'constellations/orion',
						'constellations/ursa-minor',
					],
				},
			],
		},
	],
});
```

Вышеуказанная конфигурация генерирует следующую боковую панель:

<SidebarPreview
	config={[
		{
			label: 'Созвездия',
			items: [
				{ label: 'Карина', link: '' },
				{ label: 'Центавр', link: '' },
				{
					label: 'Сезонные',
					items: [
						{ label: 'Андромеда', link: '' },
						{ label: 'Орион', link: '' },
						{ label: 'Малая Медведица', link: '' },
					],
				},
			],
		},
	]}
/>

### Автогенерируемые группы

Starlight может автоматически генерировать группу в вашей боковой панели, основываясь на директориях в вашей документации.
Это полезно, когда вы не хотите вручную вводить каждый элемент боковой панели в группе.

По умолчанию страницы сортируются в алфавитном порядке в соответствии со свойством [`id`](/ru/reference/route-data/#id). или именем файла.

Добавьте автогенерируемую группу, используя объект со свойствами `label` и `autogenerate`. Ваша конфигурация `autogenerate` должна указывать `directory`, которая будет использоваться для записей боковой панели. Например, со следующей конфигурацией:

```js "label:" "autogenerate:"
starlight({
	sidebar: [
		{
			label: 'Созвездия',
			// Автогенерация группы ссылок для директории 'constellations'.
			autogenerate: { directory: 'constellations' },
		},
	],
});
```

И следующей структурой файлов:

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - carina.md
        - centaurus.md
        - seasonal/
          - andromeda.md

</FileTree>

Будет сгенерирована следующая боковая панель:

<SidebarPreview
	config={[
		{
			label: 'Созвездия',
			items: [
				{ label: 'Карина', link: '' },
				{ label: 'Центавр', link: '' },
				{
					label: 'seasonal',
					items: [{ label: 'Андромеда', link: '' }],
				},
			],
		},
	]}
/>

## Настройка сгенерированных ссылок через метаданные

Используйте [поле `sidebar`](/ru/reference/frontmatter/#sidebar) в метаданных страниц для настройки автоматически генерируемых ссылок.

Параметры в метаданных для боковой панели позволяют установить [пользовательскую метку](/ru/reference/frontmatter/#label), использовать [пользовательские атрибуты](/ru/reference/frontmatter/#attrs), добавить [значок](/ru/reference/frontmatter/#badge) к ссылке, [скрыть](/ru/reference/frontmatter/#hidden) ссылку из боковой панели или определить [порядок её сортировки](/ru/reference/frontmatter/#order).

```md "sidebar:"
---
# src/content/docs/example.md
title: Моя страница
sidebar:
  # Установить текст для ссылки
  label: Текст в боковой панели
  # Установить порядок для ссылки (чем ниже число, тем выше будет отображаться ссылка)
  order: 2
  # Добавить значок к ссылке
  badge:
    text: Новое
    variant: tip
---
```

Автоматически созданная группа, включающая страницу с вышеуказанными метаданными, сгенерирует следующую боковую панель:

<SidebarPreview
	config={[
		{
			label: 'Руководства',
			items: [
				{ label: 'Моя страница', link: '' },
				{
					label: 'Текст в боковой панели',
					link: '',
					badge: { text: 'Новое', variant: 'tip' },
				},
				{ label: 'Другая страница', link: '' },
			],
		},
	]}
/>

:::note
Параметр `sidebar` в метаданных используется только для ссылок в автогенерируемых группах и ссылок на документы, заданных с помощью свойства `slug`. Он не применяется к ссылкам, заданным с помощью свойства `link`.
:::

## Значки

Ссылки также могут включать свойство `badge` для отображения значка рядом с текстом ссылки.

```js {9,16}
starlight({
	sidebar: [
		{
			label: 'Звёзды',
			items: [
				// Ссылка со значком «Сверхгигант».
				{
					slug: 'stars/persei',
					badge: 'Сверхгигант',
				},
			],
		},
		// Автогенерируемая группа со значком "Устарело".
		{
			label: 'Луны',
			badge: 'Устарело',
			autogenerate: { directory: 'moons' },
		},
	],
});
```

Конфигурация выше создаст следующую боковую панель:

<SidebarPreview
	config={[
		{
			label: 'Звёзды',
			items: [
				{
					label: 'Персей',
					link: '',
					badge: { text: 'Сверхгигант', variant: 'default' },
				},
			],
		},
		{
			label: 'Луны',
			badge: { text: 'Устарело', variant: 'default' },
			items: [
				{
					label: 'Ио',
					link: '',
				},
				{
					label: 'Европа',
					link: '',
				},
				{
					label: 'Ганимед',
					link: '',
				},
			],
		},
	]}
/>

### Варианты значков и индивидуальная стилизация

Настройте стиль значка, используя объект со свойствами `text`, `variant` и `class`.

`text` представляет содержимое для отображения (например, «Новое»).
По умолчанию значок будет использовать акцентный цвет вашего сайта. Чтобы использовать встроенный стиль значка, установите для свойства `variant` одно из следующих значений: `note`, `tip`, `danger`, `caution` или `success`.

Кроме того, можно создать собственный стиль значка, задав свойству `class` имя класса CSS.

```js {9}
starlight({
	sidebar: [
		{
			label: 'Звёзды',
			items: [
				// Ссылка с жёлтым значком «Заглушка»
				{
					slug: 'stars/sirius',
					badge: { text: 'Заглушка', variant: 'caution' },
				},
			],
		},
	],
});
```

Конфигурация выше создаст следующую боковую панель:

<SidebarPreview
	config={[
		{
			label: 'Звёзды',
			items: [
				{
					label: 'Сириус',
					link: '',
					badge: { text: 'Заглушка', variant: 'caution' },
				},
			],
		},
	]}
/>

Узнайте больше об [использовании и настройке значков](/ru/components/badges/#использование).

## Пользовательские HTML-атрибуты

Ссылки также могут включать свойство `attrs` для добавления пользовательских HTML-атрибутов к элементу ссылки.

В следующем примере `attrs` используется для добавления атрибута `target="_blank"`, чтобы ссылка открывалась в новой вкладке, а также для применения атрибута `style`, чтобы курсивом выделить метку ссылки:

```js {10}
starlight({
	sidebar: [
		{
			label: 'Ресурсы',
			items: [
				// Внешняя ссылка на сайт NASA, открывающаяся в новой вкладке.
				{
					label: 'NASA',
					link: 'https://www.nasa.gov/',
					attrs: { target: '_blank', style: 'font-style: italic' },
				},
			],
		},
	],
});
```

Конфигурация выше создаст следующую боковую панель:

<SidebarPreview
	config={[
		{
			label: 'Ресурсы',
			items: [
				{
					label: 'NASA',
					link: 'https://www.nasa.gov/',
					attrs: {
						target: '_blank',
						style: 'font-style: italic',
					},
				},
			],
		},
	]}
/>

### Пользовательские HTML-атрибуты для автоматически сгенерированных ссылок

Настройте HTML-атрибуты всех ссылок в [автоматически сгенерированных группах](#автогенерируемые-группы), указав свойство `attrs` в конфигурации `autogenerate`.
Отдельные страницы могут задавать пользовательские атрибуты с помощью поля [`sidebar.attrs`](/ru/reference/frontmatter/#attrs) в метаданных, которое будет объединено с конфигурацией `autogenerate.attrs`.

Например, со следующей конфигурацией:

```js {9}
starlight({
	sidebar: [
		{
			label: 'Созвездия',
			autogenerate: {
				// Автоматически генерируем группу ссылок для директории 'constellations'
				directory: 'constellations',
				// Выделяем курсивом все ярлыки ссылок в этой группе
				attrs: { style: 'font-style: italic' },
			},
		},
	],
});
```

и следующей файловой структурой:

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - carina.md
        - centaurus.md
        - seasonal/
          - andromeda.md

</FileTree>

Будет сгенерирована боковая панель с выделением всех автоматически созданных ссылок курсивом:

<SidebarPreview
	config={[
		{
			label: 'Созвездия',
			items: [
				{ label: 'Карина', link: '', attrs: { style: 'font-style: italic' } },
				{
					label: 'Центавр',
					link: '',
					attrs: { style: 'font-style: italic' },
				},
				{
					label: 'seasonal',
					items: [
						{
							label: 'Андромеда',
							link: '',
							attrs: { style: 'font-style: italic' },
						},
					],
				},
			],
		},
	]}
/>

## Интернационализация

Используйте свойство `translations` для записей ссылок и групп, чтобы перевести метку ссылки или группы для каждого поддерживаемого языка, указав тег языка [BCP-47](https://www.w3.org/International/questions/qa-choosing-language-tags), например, `"en"`, `"ru"` или `"zh-CN"` в качестве ключа, и перевод метки — в качестве значения.
Свойство `label` будет использоваться для локали по умолчанию и для языков без перевода.

```js {5-7,11-13,18-20}
starlight({
	sidebar: [
		{
			label: 'Созвездия',
			translations: {
				'pt-BR': 'Constelações',
			},
			items: [
				{
					label: 'Андромеда',
					translations: {
						'pt-BR': 'Andrômeda',
					},
					slug: 'constellations/andromeda',
				},
				{
					label: 'Скорпион',
					translations: {
						'pt-BR': 'Escorpião',
					},
					slug: 'constellations/scorpius',
				},
			],
		},
	],
});
```

При просмотре документации на бразильском португальском языке будет сгенерирована следующая боковая панель:

<SidebarPreview
	config={[
		{
			label: 'Constelação',
			items: [
				{ label: 'Andrômeda', link: '' },
				{ label: 'Escorpião', link: '' },
			],
		},
	]}
/>

### Интернационализация с внутренними ссылками

[Внутренние ссылки](#внутренние-ссылки) по умолчанию будут автоматически использовать переведённые заголовки страниц из метаданных контента:

```js {9-10}
starlight({
	sidebar: [
		{
			label: 'Созвездия',
			translations: {
				'pt-BR': 'Constelações',
			},
			items: [
				{ slug: 'constellations/andromeda' },
				{ slug: 'constellations/scorpius' },
			],
		},
	],
});
```

При просмотре документации на бразильском португальском языке появится следующая боковая панель:

<SidebarPreview
	config={[
		{
			label: 'Constelações',
			items: [
				{ label: 'Andrômeda', link: '' },
				{ label: 'Escorpião', link: '' },
			],
		},
	]}
/>

На многоязычных сайтах значение `slug` не включает языковую часть URL.
Например, если у вас есть страницы `en/intro` и `pt-br/intro`, при настройке боковой панели в качестве slug будет `intro`.

### Интернационализация с помощью значков

Для [значков](#значки) свойство `text` может быть строкой, а для многоязычных сайтов — объектом со значениями для каждой локали.
При использовании объектной формы ключи должны быть тегами [BCP-47](https://www.w3.org/International/questions/qa-choosing-language-tags) (например: `en`, `ar` или `zh-CN`):

```js {11-16}
starlight({
	sidebar: [
		{
			label: 'Созвездия',
			translations: {
				'pt-BR': 'Constelações',
			},
			items: [
				{
					slug: 'constellations/andromeda',
					badge: {
						text: {
							ru: 'Новинка',
							'pt-BR': 'Novo',
						},
					},
				},
			],
		},
	],
});
```

При просмотре документации на бразильском португальском языке появится следующая боковая панель:

<SidebarPreview
	config={[
		{
			label: 'Constelações',
			items: [
				{
					label: 'Andrômeda',
					link: '',
					badge: { text: 'Novo', variant: 'default' },
				},
			],
		},
	]}
/>

## Сворачиваемые группы

Группы ссылок могут быть свёрнуты по умолчанию, если установить свойство `collapsed` в `true`.

```js {5-6}
starlight({
	sidebar: [
		{
			label: 'Созвездия',
			// Сворачивание группы по умолчанию
			collapsed: true,
			items: [
				items: ['constellations/andromeda', 'constellations/orion'],
			],
		},
	],
});
```

Конфигурация выше создает следующую боковую панель:

<SidebarPreview
	config={[
		{
			label: 'Созвездия',
			collapsed: true,
			items: [
				{ label: 'Андромеда', link: '' },
				{ label: 'Орион', link: '' },
			],
		},
	]}
/>

[Автогенерируемые группы](#автогенерируемые-группы) учитывают значение `collapsed` родительской группы:

```js {5-6}
starlight({
	sidebar: [
		{
			label: 'Созвездия',
			// Сворачивание группы и её автогенерируемых подгрупп по умолчанию.
			collapsed: true,
			autogenerate: { directory: 'constellations' },
		},
	],
});
```

Конфигурация выше создает следующую боковую панель:

<SidebarPreview
	config={[
		{
			label: 'Созвездия',
			collapsed: true,
			items: [
				{ label: 'Карина', link: '' },
				{ label: 'Центавр', link: '' },
				{
					label: 'seasonal',
					collapsed: true,
					items: [{ label: 'Андромеда', link: '' }],
				},
			],
		},
	]}
/>

Это поведение может быть переопределено путём установки свойства `autogenerate.collapsed`.

```js {5-7} "collapsed: true"
starlight({
	sidebar: [
		{
			label: 'Созвездия',
			// Не сворачивать группу «Созвездия», но сворачивать её
			// автоматически сгенерированные подгруппы.
			collapsed: false,
			autogenerate: { directory: 'constellations', collapsed: true },
		},
	],
});
```

Конфигурация выше создает следующую боковую панель:

<SidebarPreview
	config={[
		{
			label: 'Созвездия',
			items: [
				{ label: 'Карина', link: '' },
				{ label: 'Центавр', link: '' },
				{
					label: 'seasonal',
					collapsed: true,
					items: [{ label: 'Андромеда', link: '' }],
				},
			],
		},
	]}
/>


================================================
FILE: docs/src/content/docs/ru/guides/site-search.mdx
================================================
---
title: Поиск по сайту
description: Узнайте о встроенных в Starlight функциях поиска по сайту и о том, как их настроить.
tableOfContents:
  maxHeadingLevel: 4
---

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

По умолчанию сайты Starlight включают полнотекстовый поиск на основе [Pagefind](https://pagefind.app/), который является быстрым и не требующим большой пропускной способности инструментом поиска для статических сайтов.

Для включения поиска не требуется никакой настройки. Создайте и разверните свой сайт, а затем используйте строку поиска в шапке сайта для поиска контента.

## Скрытие содержимого из результатов поиска

### Исключение страницы

Чтобы исключить страницу из поискового индекса, добавьте [`pagefind: false`](/ru/reference/frontmatter/#pagefind) в метаданных страницы:

```md title="src/content/docs/not-indexed.md" ins={3}
---
title: Содержимое, которое нужно скрыть от поиска
pagefind: false
---
```

### Исключение части страницы

Pagefind будет игнорировать содержимое внутри элемента с атрибутом [`data-pagefind-ignore`](https://pagefind.app/docs/indexing/#removing-individual-elements-from-the-index).

В следующем примере первый абзац будет отображаться в результатах поиска, а содержимое `<div>` — нет:

```md title="src/content/docs/partially-indexed.md" ins="data-pagefind-ignore"
---
title: Частично проиндексированная страница
---

Этот текст можно будет найти с помощью поиска.

<div data-pagefind-ignore>

Этот текст будет скрыт от поиска.

</div>
```

## Альтернативные поставщики услуг поиска

### Algolia DocSearch

Если у вас есть доступ к [программе DocSearch от Algolia](https://docsearch.algolia.com/) и вы хотите использовать её вместо Pagefind, вы можете воспользоваться официальным плагином Starlight DocSearch.

<Steps>

1. Установите `@astrojs/starlight-docsearch`:

   <Tabs syncKey="pkg">

   <TabItem label="npm">

   ```sh
   npm install @astrojs/starlight-docsearch
   ```

   </TabItem>

   <TabItem label="pnpm">

   ```sh
   pnpm add @astrojs/starlight-docsearch
   ```

   </TabItem>

   <TabItem label="Yarn">

   ```sh
   yarn add @astrojs/starlight-docsearch
   ```

   </TabItem>

   </Tabs>

2. Добавьте DocSearch в конфигурацию Starlight [`plugins`](/ru/reference/configuration/#plugins) в `astro.config.mjs` и передайте ему ваши Algolia `appId`, `apiKey` и `indexName`:

   ```js ins={4,10-16}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';
   import starlightDocSearch from '@astrojs/starlight-docsearch';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Сайт с DocSearch',
   			plugins: [
   				starlightDocSearch({
   					appId: 'YOUR_APP_ID',
   					apiKey: 'YOUR_SEARCH_API_KEY',
   					indexName: 'YOUR_INDEX_NAME',
   				}),
   			],
   		}),
   	],
   });
   ```

</Steps>

С этой обновлённой конфигурацией строка поиска на вашем сайте теперь будет открывать модальное окно Algolia вместо стандартного модального окна поиска.

#### Конфигурация DocSearch

Плагин Starlight DocSearch поддерживает настройку компонента DocSearch с помощью следующих встроенных опций:

- `maxResultsPerGroup`: Ограничивает количество результатов, отображаемых для каждой группы поиска. По умолчанию `5`.
- `disableUserPersonalization`: Предотвращает сохранение недавних поисков и избранных элементов пользователя в локальном хранилище. По умолчанию `false`.
- `insights`: Включает плагин Algolia Insights и отправляет события поиска в ваш индекс DocSearch. По умолчанию `false`.
- `searchParameters`: Объект, настраивающий [параметры поиска Algolia](https://www.algolia.com/doc/api-reference/search-api-parameters/).

##### Дополнительные опции DocSearch

Для передачи в компонент DocSearch параметров-функций, таких как `transformItems()` или `resultsFooterComponent()`, необходим отдельный файл конфигурации.

<Steps>

1. Создайте файл TypeScript, экспортирующий вашу конфигурацию DocSearch.

   ```ts
   // src/config/docsearch.ts
   import type { DocSearchClientOptions } from '@astrojs/starlight-docsearch';

   export default {
   	appId: 'YOUR_APP_ID',
   	apiKey: 'YOUR_SEARCH_API_KEY',
   	indexName: 'YOUR_INDEX_NAME',
   	getMissingResultsUrl({ query }) {
   		return `https://github.com/algolia/docsearch/issues/new?title=${query}`;
   	},
   	// ...
   } satisfies DocSearchClientOptions;
   ```

2. Передайте путь к вашему файлу конфигурации плагину Starlight DocSearch в `astro.config.mjs`.

   ```js {11-13}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';
   import starlightDocSearch from '@astrojs/starlight-docsearch';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Сайт с DocSearch',
   			plugins: [
   				starlightDocSearch({
   					clientOptionsModule: './src/config/docsearch.ts',
   				}),
   			],
   		}),
   	],
   });
   ```

</Steps>

Смотрите [Документацию по API JavaScript-клиента DocSearch](https://docsearch.algolia.com/docs/api/), чтобы узнать все поддерживаемые параметры.

#### Перевод пользовательского интерфейса DocSearch

По умолчанию DocSearch предоставляет только английские строки пользовательского интерфейса.
Добавьте перевод модального пользовательского интерфейса для вашего языка, используя встроенную [систему интернационализации](/ru/guides/i18n/#перевод-интерфейса-starlight) Starlight.

<Steps>

1. Расширьте определение коллекции контента Starlight `i18n` схемой DocSearch в файле `src/content.config.ts`:

   ```js ins={5} ins=/{ extend: .+ }/
   // src/content.config.ts
   import { defineCollection } from 'astro:content';
   import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
   import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';
   import { docSearchI18nSchema } from '@astrojs/starlight-docsearch/schema';

   export const collections = {
   	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
   	i18n: defineCollection({
   		loader: i18nLoader(),
   		schema: i18nSchema({ extend: docSearchI18nSchema() }),
   	}),
   };
   ```

2. Добавьте переводы в JSON-файлы в `src/content/i18n/`.

   Это английские значения по умолчанию, используемые DocSearch:

   ```json title="src/content/i18n/en.json"
   {
   	"docsearch.searchBox.resetButtonTitle": "Clear the query",
   	"docsearch.searchBox.resetButtonAriaLabel": "Clear the query",
   	"docsearch.searchBox.cancelButtonText": "Cancel",
   	"docsearch.searchBox.cancelButtonAriaLabel": "Cancel",
   	"docsearch.searchBox.searchInputLabel": "Search",

   	"docsearch.startScreen.recentSearchesTitle": "Recent",
   	"docsearch.startScreen.noRecentSearchesText": "No recent searches",
   	"docsearch.startScreen.saveRecentSearchButtonTitle": "Save this search",
   	"docsearch.startScreen.removeRecentSearchButtonTitle": "Remove this search from history",
   	"docsearch.startScreen.favoriteSearchesTitle": "Favorite",
   	"docsearch.startScreen.removeFavoriteSearchButtonTitle": "Remove this search from favorites",

   	"docsearch.errorScreen.titleText": "Unable to fetch results",
   	"docsearch.errorScreen.helpText": "You might want to check your network connection.",

   	"docsearch.footer.selectText": "to select",
   	"docsearch.footer.selectKeyAriaLabel": "Enter key",
   	"docsearch.footer.navigateText": "to navigate",
   	"docsearch.footer.navigateUpKeyAriaLabel": "Arrow up",
   	"docsearch.footer.navigateDownKeyAriaLabel": "Arrow down",
   	"docsearch.footer.closeText": "to close",
   	"docsearch.footer.closeKeyAriaLabel": "Escape key",
   	"docsearch.footer.searchByText": "Search by",

   	"docsearch.noResultsScreen.noResultsText": "No results for",
   	"docsearch.noResultsScreen.suggestedQueryText": "Try searching for",
   	"docsearch.noResultsScreen.reportMissingResultsText": "Believe this query should return results?",
   	"docsearch.noResultsScreen.reportMissingResultsLinkText": "Let us know."
   }
   ```

</Steps>

### Поисковые провайдеры от сообщества

[Плагины от сообщества](/ru/resources/plugins/#плагины-от-сообщества) также могут предоставлять альтернативы встроенному поисковому провайдеру Pagefind от Starlight.

#### Typesense DocSearch

Плагин от сообщества [Starlight DocSearch Typesense](https://starlight-docsearch.typesense.org/) предоставляет полностью открытую альтернативу, которую можно развернуть на собственном сервере. Он интегрирует интерфейс [DocSearch](https://github.com/typesense/typesense-docsearch.js) с бэкендом [Typesense](https://typesense.org/).

См. руководство [«Getting Started»](https://starlight-docsearch.typesense.org/getting-started/) в документации Starlight DocSearch Typesense, чтобы узнать, как использовать его в вашем проекте.


================================================
FILE: docs/src/content/docs/ru/index.mdx
================================================
---
title: Starlight 🌟 Создавайте сайты с документацией с помощью Astro
head:
  - tag: title
    content: Starlight 🌟 Создавайте сайты с документацией с помощью Astro
description: Starlight помогает вам создавать красивые, высокопроизводительные веб-сайты с документацией с Astro.
template: splash
editUrl: false
lastUpdated: false
hero:
  title: Сделайте свою документацию яркой с помощью Starlight
  tagline: Всё, что вам нужно, чтобы создать впечатляющий сайт с документацией. Быстро, доступно и просто в использовании.
  image:
    file: ~/assets/hero-star.webp
  actions:
    - text: Начать
      icon: right-arrow
      link: /ru/getting-started/
    - text: Открыть в GitHub
      icon: external
      variant: minimal
      link: https://github.com/withastro/starlight
---

import { CardGrid, Card } from '@astrojs/starlight/components';
import AboutAstro from '~/components/about-astro.astro';
import TestimonialGrid from '~/components/testimonial-grid.astro';
import Testimonial from '~/components/testimonial.astro';

<CardGrid stagger>
	<Card title="Документация, которая восхищает" icon="open-book">
		Включает в себя: навигацию по сайту, поиск, интернационализацию, оптимизацию
		для поисковых систем (SEO), удобную типографику, подсветку кода, тёмный
		режим и многое другое.
	</Card>
	<Card title="Работает на Astro" icon="rocket">
		Воспользуйтесь всей мощью и производительностью Astro. Расширьте Starlight с
		вашими любимыми интеграциями и библиотеками Astro.
	</Card>
	<Card title="Markdown, Markdoc и MDX" icon="document">
		Используйте свой любимый язык разметки. Starlight предоставляет встроенную
		проверку метаданных с поддержкой TypeScript для обеспечения
		типобезопасности.
	</Card>
	<Card title="Используйте свои UI компоненты" icon="puzzle">
		Starlight не зависим от других фреймворков. Используйте с ним React, Vue,
		Svelte, Solid и другие фреймворки.
	</Card>
</CardGrid>

<TestimonialGrid title="Что говорят люди">
  <Testimonial
    name="Rachel"
    handle="rachelnabors"
    cite="https://twitter.com/astrodotbuild/status/1724934718745915558"
  >
    Команда Astro РАЗВИВАЛА способы создания документации, и вы можете получить всё это прямо из коробки с их проектом Starlight.
  </Testimonial>
  <Testimonial
    name="Flavio"
    handle="flaviocopes"
    cite="https://twitter.com/flaviocopes/status/1738237658717905108"
  >
    Официальный стартовый комплект Astro Starlight — поистине невероятный инструмент для создания веб-сайта документации.
  </Testimonial>
  <Testimonial
    name="Tomek"
    handle="sulco"
    cite="https://twitter.com/sulco/status/1735610348730802342"
  >
    Starlight — наш лучший пример отличного DX: скорость, удобство и
    внимание к деталям вдохновляет. Он заботится о технологиях и внешнем виде,
    чтобы вы могли сосредоточиться на своем контенте 👏

    Команде StackBlitz это очень нравится!

  </Testimonial>
  <Testimonial
    name="Roberto"
    handle="RmeetsH"
    cite="https://twitter.com/RmeetsH/status/1735783992018760090"
  >
    Starlight изменил правила игры для меня, позволив мне сосредоточиться на создании контента.

    Его интуитивно понятный дизайн не только оптимизирует мой рабочий процесс, но и сокращает время адаптации для разработчиков ПО с открытым исходным кодом.

  </Testimonial>
  <Testimonial
    name="Joel"
    handle="jhooks"
    cite="https://twitter.com/jhooks/status/1727405160547418405"
  >
    Потратил ещё немного времени на Starlight для документации Course Builder, и до сих пор всё было отлично. Множество приятных мелочей и возможность сосредоточиться на написании в Markdown, а не на возне с сайтом.
  </Testimonial>
  <Testimonial
    name="Rick"
    handle="rick_viscomi"
    cite="https://twitter.com/rick_viscomi/status/1665867447910510593"
  >
    Начал играть со Starlight. Должен сказать, что я очень впечатлен производительностью «из коробки».

    💯💯💯💯

  </Testimonial>
  <Testimonial
    name="Nicolas"
    handle="beaussan"
    cite="https://twitter.com/beaussan/status/1735625189583466893"
  >
    Starlight — лучший способ начать работу с документацией:
	мощь и скорость Astro и инструменты Starlight — это идеальное сочетание.

    Я уже давно это делаю и продолжаю любить!

  </Testimonial>
  <Testimonial
    name="Sylwia"
    handle="SylwiaVargas"
    cite="https://x.com/SylwiaVargas/status/1726556825741578286"
  >
    Я использовала Starlight на своей последней работе, и мне он понравился. Отличные компоненты, интуитивно понятный
    дизайн и сверхотзывчивое сообщество (всякий раз, когда кому-то что-то нужно,
    они очень быстро направят его в нужном направлении или подскажут обходной путь). Очень приятный опыт.
  </Testimonial>
  <Testimonial
    name="Lou Cyx"
    handle="loucyx"
    cite="https://elk.zone/m.webtoo.ls/@loucyx@mastodon.social/111587380021362284"
  >
    Документы на моем сайте монорепозитория выглядят лучше, чем когда-либо, благодаря Starlight. Его чрезвычайно легко использовать, не теряя при этом всей мощи Astro. Спасибо за работу над этим!
  </Testimonial>
  <Testimonial
    name="BowTiedWebReaper"
    handle="BowTiedWebReapr"
    cite="https://twitter.com/BowTiedWebReapr/status/1735633399501697517"
  >
    Starlight — мой любимый инструмент для документирования. Благодаря этому стало очень легко добавлять документы на мой существующий веб-сайт продукта Astro, вместо того, чтобы использовать поддомен с другим инструментом.
  </Testimonial>
  <Testimonial
    name="Jeff"
    handle="J_Everhart383"
    cite="https://twitter.com/J_Everhart383/status/1691900590048292908"
  >
    Я перестраивал документацию платформы WPEngine Atlas. Поверьте мне, когда я говорю, что у Starlight есть всё необходимое для создания платформы документации A+ 🙌
  </Testimonial>
  <Testimonial
    name="Chloe"
    handle="solelychloe"
    cite="https://twitter.com/solelychloe/status/1695115277602628082"
  >
    Попробуйте Starlight!

    Я использую его для нескольких своих сайтов, и это здорово.

  </Testimonial>
</TestimonialGrid>

<AboutAstro title="Предоставлено вам">
Astro — универсальный веб-фреймворк, разработанный для максимальной производительности.
Используйте контент из любых источников и развёртывайте его везде, используя ваши любимые UI-компоненты и библиотеки.

[Узнать больше об Astro](https://astro.build/)

</AboutAstro>


================================================
FILE: docs/src/content/docs/ru/manual-setup.mdx
================================================
---
title: Установка вручную
description: Узнайте, как настроить Starlight вручную, чтобы добавить его к существующему проекту Astro.
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

Самый быстрый способ создать новый сайт на Starlight - использовать `create astro`, как показано во [введении](/ru/getting-started/#создание-нового-проекта).
Если вы хотите добавить Starlight к существующему проекту Astro, это руководство расскажет, как это сделать.

## Настройка Starlight

Для работы по этому руководству вам понадобится существующий проект на Astro.

### Интеграция Starlight

Starlight является [интеграцией Astro](https://docs.astro.build/ru/guides/integrations-guide/). Добавьте её на ваш сайт, запустив команду `astro add` в корневой директории вашего проекта:

<Tabs syncKey="pkg">
    <TabItem label="npm">
        ```sh
        npx astro add starlight
        ```

    </TabItem>
    <TabItem label="pnpm">
        ```sh
        pnpm astro add starlight
        ```
    </TabItem>
    <TabItem label="Yarn">
        ```sh
        yarn astro add starlight
        ```
    </TabItem>

</Tabs>

Это установит необходимые зависимости и добавит Starlight в массив `integrations` в конфигурационном файле Astro.

### Настройка интеграции

Интеграция Starlight настраивается в вашем файле `astro.config.mjs`.

Добавьте `title`, чтобы начать:

```js ins={8}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Мой замечательный сайт с документацией',
		}),
	],
});
```

Найдите все доступные параметры в [справочнике конфигурации Starlight](/ru/reference/configuration/).

### Настройка коллекций контента

Starlight создан на основе [коллекций контента](https://docs.astro.build/ru/guides/content-collections/) Astro, которые настраиваются в файле `src/content.config.ts`.

Создайте или обновите файл конфигурации контента, добавив коллекцию `docs`, которая использует схемы [`docsLoader`](/ru/reference/configuration/#docsloader) и [`docsSchema`](/ru/reference/configuration/#docsschema): от Starlight:

```js ins={3-4,7}
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
};
```

Starlight также поддерживает флаг [`legacy.collectionsBackwardsCompat`](https://docs.astro.build/ru/reference/legacy-flags/#collectionsbackwardscompat), который сохраняет некоторые устаревшие возможности коллекций контента из версии 4.
Это полезно, если у вас уже есть существующий проект на Astro и в данный момент нет возможности внести изменения в коллекции, чтобы перейти на API Content Layer, появившийся в версии 5.0.

### Добавление контента

Starlight настроен, и пришло время добавить контент!

Создайте директорию `src/content/docs/` и начните с добавления файла `index.md`.
Это будет главной страницей вашего нового сайта:

```md
---
# src/content/docs/index.md
title: Моя документация
description: Узнайте больше о моем проекте на этом сайте с документацией, созданном с помощью Starlight.
---

Добро пожаловать в мой проект!
```

Starlight использует маршрутизацию на основе файлов, что означает, что каждый файл Markdown, MDX или Markdoc в `src/content/docs/` становится страницей на вашем сайте. Метаданные в начале файла (например, поля `title` и `description` в приведённом выше примере) могут изменить отображение страниц.
Посмотрите все доступные параметры в [справочнике по метаданным](/ru/reference/frontmatter/).

## Советы для существующих сайтов

Если у вас уже есть существующий проект Astro, вы можете использовать Starlight, чтобы быстро добавить раздел с документацией на ваш сайт.

### Использование Starlight с подкаталогами

Чтобы добавить все страницы Starlight по подкаталогу, поместите всё содержимое ваших документов в подкаталог `src/content/docs/`.

Например, если все страницы Starlight должны начинаться с `/guides/`, добавьте свой контент в каталог `src/content/docs/guides/`:

import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src/
  - content/
    - docs/
      - **guides/**
        - guide.md
        - index.md
  - pages/
- astro.config.mjs

</FileTree>

В будущем мы планируем улучшить такой вариант использования путей, чтобы избежать необходимости в лишнем вложенном каталоге в `src/content/docs/`.

### Использование Starlight с SSR

Чтобы включить SSR, следуйте руководству [Адаптеры рендеринга по требованию](https://docs.astro.build/ru/guides/on-demand-rendering/) в документации Astro, для добавления серверного адаптера в ваш проект Starlight.

Страницы документации, создаваемые Starlight, по умолчанию предварительно отрисовываются независимо от режима вывода вашего проекта. Для отключения предварительного рендеринга страниц установите для [параметра `prerender`](/ru/reference/configuration/#prerender) значение `false`.

Если вы используете [адаптер Cloudflare](https://docs.astro.build/ru/guides/integrations-guide/cloudflare/) для включения серверного рендеринга в вашем проекте документации, обязательно также [добавьте флаг совместимости `nodejs_compat` в файл конфигурации Wrangler](https://developers.cloudflare.com/workers/runtime-apis/nodejs/#get-started).


================================================
FILE: docs/src/content/docs/ru/reference/configuration.mdx
================================================
---
title: Конфигурация
description: Обзор всех опций конфигурации, поддерживаемых Starlight.
---

## Настройка интеграции `starlight`

Starlight — это интеграция, построенная на основе веб-фреймворка [Astro](https://astro.build). Вы можете настроить свой проект в файле конфигурации `astro.config.mjs`:

```js
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Мой восхитительный сайт документации',
		}),
	],
});
```

Вы можете передать следующие параметры интеграции `starlight`.

### `title` (обязателен)

**тип:** `string | Record<string, string>`

Задайте название для вашего сайта. Будет использоваться в метаданных и в заголовке вкладки браузера.

Значение может быть строкой, а для многоязычных сайтов — объектом со значениями для каждой локали.
При использовании объектной формы ключи должны быть тегами BCP-47 (например, `en`, `ru` или `zh-CN`):

```ts
starlight({
	title: {
		en: 'My delightful docs site',
		ru: 'Моя восхитительная документация',
	},
});
```

### `description`

**тип:** `string`

Задайте описание для вашего сайта. Используется в метаданных, передаваемых поисковым системам, в теге `<meta name="description">`, если `description` не задан в метаданных страницы.

### `logo`

**тип:** [`LogoConfig`](#logoconfig)

Установите изображение логотипа, которое будет отображаться в навигационной панели вместе с заголовком сайта или вместо него. Вы можете задать одно свойство `src` или установить отдельные источники изображения для стилей `light` и `dark`.

```js
starlight({
	logo: {
		src: './src/assets/my-logo.svg',
	},
});
```

#### `LogoConfig`

```ts
type LogoConfig = { alt?: string; replacesTitle?: boolean } & (
	| { src: string }
	| { light: string; dark: string }
);
```

### `tableOfContents`

**тип:** `false | { minHeadingLevel?: number; maxHeadingLevel?: number }`  
**по умолчанию:** `{ minHeadingLevel: 2, maxHeadingLevel: 3 }`

Настройте оглавление, отображаемое справа на каждой странице. По умолчанию в оглавление будут включены заголовки `<h2>` и `<h3>`.

### `editLink`

**тип:** `{ baseUrl: string }`

Включите ссылки "Редактировать эту страницу", задав базовый URL, который они должны использовать. Конечной ссылкой будет `editLink.baseUrl` + путь к текущей странице. Например, чтобы разрешить редактирование страниц в репозитории `withastro/starlight` на GitHub:

```js
starlight({
	editLink: {
		baseUrl: 'https://github.com/withastro/starlight/edit/main/',
	},
});
```

При такой конфигурации страница `/introduction` будет иметь ссылку редактирования, указывающую на `https://github.com/withastro/starlight/edit/main/src/content/docs/introduction.md`.

### `sidebar`

**тип:** [`SidebarItem[]`](#sidebaritem)

Настройте элементы навигации боковой панели вашего сайта.

Боковая панель — это массив ссылок и групп ссылок.
За исключением элементов, использующих `slug`, каждый элемент должен иметь `label` и одно из следующих свойств:

- `link` — одиночная ссылка на определённый URL, например, `'/home'` или `'https://example.com'`.

- `slug` — ссылка на внутреннюю страницу, например, `'guides/getting-started'`.

- `items` — массив, содержащий дополнительные ссылки и подгруппы боковой панели.

- `autogenerate` — объект, указывающий каталог ваших документов для автоматической генерации группы ссылок.

Внутренние ссылки также могут быть указаны в виде строки, а не объекта со свойством `slug`.

```js
starlight({
	sidebar: [
		// Одиночный элемент ссылки, помеченный как «Главная».
		{ label: 'Главная', link: '/' },
		// Группа с надписью «Первые шаги» содержит четыре ссылки.
		{
			label: 'Первые шаги',
			items: [
				// Использование `slug` для внутренних ссылок.
				{ slug: 'intro' },
				{ slug: 'installation' },
				// Или использование сокращения для обозначения внутренних ссылок.
				'tutorial',
				'next-steps',
			],
		},
		// Группа, связывающая все страницы директории reference.
		{
			label: 'Справочник',
			autogenerate: { directory: 'reference' },
		},
	],
});
```

#### Сортировка

Автогенерируемые группы боковых панелей сортируются по имени файла в алфавитном порядке.
Например, страница, созданная на основе `astro.md`, будет отображаться выше страницы для `starlight.md`.

#### Сворачиваемые группы

Группы ссылок раскрываются по умолчанию. Вы можете изменить это поведение, установив для свойства `collapsed` группы значение `true`.

Автогенерируемые подгруппы по умолчанию уважают свойство `collapsed` своей родительской группы. Установите свойство `autogenerate.collapsed`, чтобы переопределить его.

```js {5,13}
sidebar: [
  // Группа свёрнутых ссылок.
  {
    label: 'Свёрнутые ссылки',
    collapsed: true,
		items: ['intro', 'next-steps'],
  },
  // Развёрнутая группа, содержащая свёрнутые автогенерируемые подгруппы.
  {
    label: 'Справочник',
    autogenerate: {
      directory: 'reference',
      collapsed: true,
    },
  },
],
```

#### Перевод меток

Если ваш сайт многоязычный, считается, что `label` каждого элемента соответствует локали по умолчанию. Вы можете установить свойство `translations`, чтобы предоставить метки для других поддерживаемых вами языков:

```js {5,9,14}
sidebar: [
  // Пример боковой панели с метками, переведёнными на бразильский португальский язык.
  {
    label: 'Первые шаги',
    translations: { 'pt-BR': 'Comece Aqui' },
    items: [
      {
        label: 'Введение',
        translations: { 'pt-BR': 'Introdução' },
        link: '/getting-started',
      },
      {
        label: 'Структура проекта',
        translations: { 'pt-BR': 'Estrutura de Projetos' },
        link: '/structure',
      },
    ],
  },
],
```

#### `SidebarItem`

```ts
type SidebarItem =
	| string
	| ({
			translations?: Record<string, string>;
			badge?: string | BadgeConfig;
	  } & (
			| {
					// Обычная ссылка
					link: string;
					label: string;
					attrs?: Record<string, string | number | boolean | undefined>;
			  }
			| {
					// Внутренняя ссылка
					slug: string;
					label?: string;
					attrs?: Record<string, string | number | boolean | undefined>;
			  }
			| {
					// Группа ссылок
					label: string;
					items: SidebarItem[];
					collapsed?: boolean;
			  }
			| {
					// Автоматически созданная группа ссылок
					label: string;
					autogenerate: {
						directory: string;
						collapsed?: boolean;
						attrs?: Record<string, string | number | boolean | undefined>;
					};
					collapsed?: boolean;
			  }
	  ));
```

#### `BadgeConfig`

```ts
interface BadgeConfig {
	text: string;
	variant?: 'note' | 'tip' | 'caution' | 'danger' | 'success' | 'default';
	class?: string;
}
```

### `locales`

**тип:** <code>\{ \[dir: string\]: [LocaleConfig](#localeconfig) \}</code>

[Настройте интернационализацию (i18n)](/ru/guides/i18n/) для вашего сайта, установив, какие `locales` поддерживаются.

В каждой записи в качестве ключа должен использоваться каталог, в котором хранятся файлы этого языка.

```js
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Мой сайт',
			// Устанавливаем русский язык в качестве языка по умолчанию для этого сайта.
			defaultLocale: 'ru',
			locales: {
				// Английская документация в `src/content/docs/en/`
				en: {
					label: 'English',
				},
				// Китайская документация в `src/content/docs/zh-cn/`
				'zh-cn': {
					label: '简体中文',
					lang: 'zh-CN',
				},
				// Арабская документация в `src/content/docs/ar/`
				ar: {
					label: 'العربية',
					dir: 'rtl',
				},
				// Русская документация в `src/content/docs/ru/`
				ru: {
					label: 'Русский',
				},
			},
		}),
	],
});
```

#### `LocaleConfig`

```ts
interface LocaleConfig {
	label: string;
	lang?: string;
	dir?: 'ltr' | 'rtl';
}
```

Для каждой локали можно задать следующие параметры:

##### `label` (required)

**тип:** `string`

Метка для этого языка, которую нужно показывать пользователям, например, в переключателе языков. Чаще всего вы хотите, чтобы это было название языка в том виде, в котором пользователь этого языка ожидал бы его прочитать, например `"English"`, `"Русский` или `"简体中文"`.

##### `lang`

**тип:** `string`

Метка BCP-47 для этого языка, например, `"en"`, `"ru"`, или `"zh-CN"`. Если не задано, то по умолчанию будет использоваться имя каталога языка. Языковые теги с региональными подтегами (например, `"pt-BR"` или `"en-US"`) будут использовать встроенные переводы пользовательского интерфейса для своего базового языка, если не будут найдены переводы для конкретного региона.

##### `dir`

**тип:** `'ltr' | 'rtl'`

Направление письма на этом языке; `"ltr"` — слева направо (по умолчанию) или `"rtl"` — справа налево.

#### Корневая локаль

Вы можете использовать язык по умолчанию без каталога `/lang/`, установив локаль `root`:

```js {3-6}
starlight({
	locales: {
		root: {
			label: 'English',
			lang: 'en',
		},
		ru: {
			label: 'Русский',
		},
	},
});
```

Например, это позволит вам обслуживать `/getting-started/` как маршрут по умолчанию и использовать `/ru/getting-started/` как эквивалентную русскую страницу.

### `defaultLocale`

**тип:** `string`

Установите язык, который используется по умолчанию для этого сайта.
Значение должно соответствовать одному из ключей вашего объекта [`locales`](#locales).
(Если языком по умолчанию является ваша [корневая локаль](#корневая-локаль), это можно пропустить).

Локаль по умолчанию будет использоваться для предоставления резервного содержимого, если перевод отсутствует.

### `social`

**тип:** <code>{`Array<{ label: string; icon: `}[StarlightIcon](/ru/reference/icons/){`; href: string }>`}</code>

Необязательные данные об аккаунтах в социальных сетях для этого сайта.
Каждая запись будет отображаться в виде иконки-ссылки в шапке сайта.

```js
starlight({
	social: [
		{ icon: 'codeberg', label: 'Codeberg', href: 'https://codeberg.org/knut' },
		{ icon: 'discord', label: 'Discord', href: 'https://astro.build/chat' },
		{ icon: 'github', label: 'GitHub', href: 'https://github.com/withastro' },
		{ icon: 'gitlab', label: 'GitLab', href: 'https://gitlab.com/delucis' },
		{ icon: 'mastodon', label: 'Mastodon', href: 'https://m.webtoo.ls/@astro' },
	],
}),
```

### `customCss`

**тип:** `string[]`

Предоставьте CSS-файлы для настройки внешнего вида вашего сайта Starlight.

Поддерживаются локальные CSS-файлы относительно корня вашего проекта, например: `'./src/custom.css'`, и CSS, которые вы установили как модуль npm, например: `'@fontsource/roboto'`.

```js
starlight({
	customCss: ['./src/custom-styles.css', '@fontsource/roboto'],
});
```

### `markdown`

**тип:** `{ headingLinks?: boolean; processedDirs?: string[] }`  
**по умолчанию:** `{ headingLinks: true, processedDirs: [] }`

Настройте обработку Markdown в Starlight.

#### `headingLinks`

**тип:** `boolean`  
**по умолчанию:** `true`

Определяет, будут ли заголовки отображаться с кликабельной якорной ссылкой.

```js
starlight({
	markdown: {
		// Отключаем кликабельные якорные ссылки заголовков в Starlight.
		headingLinks: false,
	},
}),
```

#### `processedDirs`

**тип:** `string[]`  
**по умолчанию:** `[]`

Определяет дополнительные директории, в которых файлы должны обрабатываться конвейером Markdown от Starlight.
По умолчанию Starlight обрабатывает только Markdown и MDX-файлы, загруженные через [`docsLoader()`](/ru/reference/configuration/#docsloader).
Поддерживаются локальные директории относительно корня проекта, например `'./src/data/comments/'`.

Обработка Starlight включает [кликабельные якорные ссылки в заголовках](#headinglinks), [синтаксис директивы `<aside>`](/ru/guides/authoring-content/#вставки), и поддержку RTL для блоков кода.
Эта опция полезна, если вы выводите контент из собственной коллекции в [кастомной странице](/ru/guides/pages/#пользовательские-страницы) с помощью компонента `<StarlightPage>` и хотите, чтобы к этому контенту применялась стандартная обработка Markdown от Starlight.

```js
starlight({
	markdown: {
		// Обработка Markdown-файлов из коллекции `reviews`, расположенной в
    // директории src/data/reviews/
		processedDirs: ['./src/data/reviews/'],
	},
}),
```

### `expressiveCode`

**тип:** `StarlightExpressiveCodeOptions | boolean`  
**по умолчанию:** `true`

Starlight использует [Expressive Code](https://expressive-code.com) для визуализации блоков кода и добавляет поддержку выделения частей примеров кода, добавления имён файлов к блокам кода и многое другое.
Смотрите руководство [Блоки кода](/ru/guides/authoring-content/#блоки-кода), чтобы узнать, как использовать синтаксис выразительного кода в Markdown и MDX-содержимом.

Вы также можете использовать любые стандартные [параметры конфигурации Expressive Code](https://expressive-code.com/reference/configuration/), как некоторые свойства, специфичные для Starlight, установив их в опции `expressiveCode` Starlight.
Например, установите опцию `styleOverrides` в Expressive Code, чтобы переопределить CSS по умолчанию. Это позволяет настраивать код, например, сделать блокам кода закругленные углы:

```js ins={2-4}
starlight({
	expressiveCode: {
		styleOverrides: { borderRadius: '0.5rem' },
	},
});
```

Если вы хотите отключить Expressive Code, установите `expressiveCode: false` в конфигурации Starlight:

```js ins={2}
starlight({
	expressiveCode: false,
});
```

В дополнение к стандартным параметрам Expressive Code вы также можете установить следующие свойства, специфичные для Starlight, в вашей конфигурации `expressiveCode` для дальнейшей настройки поведения темы для ваших блоков кода:

#### `themes`

**тип:** `Array<string | ThemeObject | ExpressiveCodeTheme>`  
**по умолчанию:** `['starlight-dark', 'starlight-light']`

Установите темы, используемые для оформления блоков кода.
См. [документацию по темам Expressive Code](https://expressive-code.com/guides/themes/) для получения подробной информации о поддерживаемых форматах тем.

По умолчанию Starlight использует тёмный и светлый варианты [темы Night Owl](https://github.com/sdras/night-owl-vscode-theme) Сары Драснер.

Если вы предоставите хотя бы одну тёмную и одну светлую тему, Starlight автоматически синхронизирует активную тему блока кода с текущей темой сайта.
Настройте это поведение с помощью параметра [`useStarlightDarkModeSwitch`](#usestarlightdarkmodeswitch).

#### `useStarlightDarkModeSwitch`

**тип:** `boolean`  
**по умолчанию:** `true`

Если установлено значение true, блоки кода автоматически переключаются между светлой и тёмной темами при изменении темы сайта.
Если установлено значение false, вам придется вручную добавить CSS для переключения между несколькими темами.

:::note
При настройке `themes` вы должны указать хотя бы одну тёмную и одну светлую тему, чтобы переключатель темного режима Starlight работал.
:::

#### `useStarlightUiThemeColors`

**тип:** `boolean`  
**по умолчанию:** `true` если `themes` не задано, иначе — `false`

Если `true`, то для цветов элементов пользовательского интерфейса кодового блока (фонов, кнопок, теней и т. д.) используются CSS-переменные Starlight, соответствующие [цветовой теме сайта](/ru/guides/css-and-tailwind/#темизация).
Если `false`, то для этих элементов используются цвета, предоставляемые активной темой подсветки синтаксиса.

:::note
При использовании пользовательских тем и установке для этого параметра значения `true` необходимо указать хотя бы одну тёмную и одну светлую тему, чтобы обеспечить правильный цветовой контраст.
:::

### `pagefind`

**тип:** <code>boolean | <a href="#pagefindoptions">PagefindOptions</a></code>  
**по умолчанию:** `true`

Настройте стандартный поставщик поиска по сайту Starlight — [Pagefind](https://pagefind.app/).

Установите значение `false`, чтобы отключить индексацию вашего сайта с помощью Pagefind.
Это также скроет стандартный пользовательский интерфейс поиска, если он используется.

Pagefind не может быть включен, если для параметра [`prerender`](#prerender) установлено значение `false`.

Установите объект в качестве значения `pagefind` для настройки клиента поиска Pagefind:

- Смотрите [Настройка ранжирования результатов Pagefind (English)](https://pagefind.app/docs/ranking/) в документации Pagefind для получения дополнительных сведений об использовании опции `pagefind.ranking` для управления порядком сортировки результатов поиска.
- Смотрите [Поиск по нескольким сайтам (English)](https://pagefind.app/docs/multisite/) в документации Pagefind для получения дополнительных сведений об использовании опции `pagefind.mergeIndex` для управления поиском по нескольким сайтам.

#### `PagefindOptions`

```ts
interface PagefindOptions {
	ranking?: {
		pageLength?: number;
		termFrequency?: number;
		termSaturation?: number;
		termSimilarity?: number;
	};
	indexWeight?: number;
	mergeIndex?: Array<{
		bundlePath: string;
		indexWeight?: number;
		basePath?: string;
		baseUrl?: string;
		mergeFilter?: Record<string, string | string[]>;
		language?: string;
		ranking?: {
			pageLength?: number;
			termFrequency?: number;
			termSaturation?: number;
			termSimilarity?: number;
		};
	}>;
}
```

### `prerender`

**тип:** `boolean`  
**по умолчанию:** `true`

Определите, должны ли страницы Starlight предварительно отрисовываться в статический HTML или отрисовываться по требованию с помощью [SSR-адаптера](https://docs.astro.build/ru/guides/on-demand-rendering/).

Страницы Starlight предварительно отрисовываются по умолчанию.
Если вы используете адаптер SSR и хотите рендерить страницы Starlight по требованию, установите `prerender: false`.

### `head`

**тип:** [`HeadConfig[]`](#headconfig)

Добавьте пользовательские теги в `<head>` вашего сайта Starlight.
Может пригодиться для добавления аналитики и других сторонних скриптов и ресурсов.

```js
starlight({
	head: [
		// Пример: добавляем тег скрипта аналитики Fathom.
		{
			tag: 'script',
			attrs: {
				src: 'https://cdn.usefathom.com/script.js',
				'data-site': 'MY-FATHOM-ID',
				defer: true,
			},
		},
	],
});
```

Записи в `head` преобразуются непосредственно в HTML-элементы и не проходят через обработку [скриптов](https://docs.astro.build/ru/guides/client-side-scripts/#обработка-скриптов) или [стилей](https://docs.astro.build/ru/guides/styling/#styling-in-astro) Astro.
Если вам нужно импортировать локальные ресурсы, такие как скрипты, стили или изображения, [переопределите компонент Head](/ru/guides/overriding-components/#переиспользование-встроенного-компонента).

#### `HeadConfig`

```ts
interface HeadConfig {
	tag: string;
	attrs?: Record<string, string | boolean | undefined>;
	content?: string;
}
```

### `lastUpdated`

**тип:** `boolean`  
**по умолчанию:** `false`

Укажите, показывать ли в нижнем колонтитуле дату последнего обновления страницы.

По умолчанию эта функция полагается на историю Git вашего репозитория и может быть неточной на некоторых платформах развёртывания, создающих [копии репозитория, включающие только самый последний коммит](https://git-scm.com/docs/git-clone#Documentation/git-clone.txt---depthltdepthgt). Страница может переопределить эту настройку или дату, основанную на Git, с помощью поля [`lastUpdated` frontmatter](/ru/reference/frontmatter/#lastupdated).

### `pagination`

**тип:** `boolean`  
**по умолчанию:** `true`

Определите, должен ли нижний колонтитул включать ссылки на предыдущую и следующую страницы.

Страница может переопределить эту настройку или текст ссылки и/или URL с помощью полей [`prev`](/ru/reference/frontmatter/#prev) и [`next`](/ru/reference/frontmatter/#next) в метаданных страницы.

### `favicon`

**тип:** `string`  
**по умолчанию:** `'/favicon.svg'`

Задайте путь к фавиконке по умолчанию для вашего сайта, который должен находиться в директории `public/` и быть валидным (`.ico`, `.gif`, `.jpg`, `.png` или `.svg`) файлом иконок.

```js
starlight({
  favicon: '/images/favicon.svg',
}),
```

Если вам нужно задать дополнительные варианты или резервные фавиконки, вы можете добавить теги с помощью опции [`head`](#head):

```js
starlight({
	favicon: '/images/favicon.svg',
	head: [
		// Добавляем резервную фавиконку для Safari
		{
			tag: 'link',
			attrs: {
				rel: 'icon',
				href: '/images/favicon.ico',
				sizes: '32x32',
			},
		},
	],
});
```

### `titleDelimiter`

**тип:** `string`  
**по умолчанию:** `'|'`

Устанавливает разделитель между заголовком страницы и заголовком сайта в теге `<title>`, который отображается на вкладках браузера.

По умолчанию каждая страница имеет `<title>` вида `Заголовок страницы | Заголовок сайта`.
Например, эта страница называется «Конфигурация», а этот сайт — «Starlight», поэтому `<title>` для этой страницы будет «Конфигурация | Starlight».

### `disable404Route`

**тип:** `boolean`  
**по умолчанию:** `false`

Отключает внедрение стандартной [страницы 404](https://docs.astro.build/ru/basics/astro-pages/#custom-404-error-page) Starlight. Чтобы использовать в своем проекте собственный маршрут `src/pages/404.astro`, установите для этого параметра значение `true`.

### `routeMiddleware`

**тип:** `string | string[]`

Укажите пути к мидлвару маршрута, который может изменять обработку данных в Starlight.  
Эти пути к файлам не должны конфликтовать с [мидлварами Astro](https://docs.astro.build/ru/guides/middleware/).

Подробнее о создании мидлваров маршрута см. в [руководстве по данным маршрута](/ru/guides/route-data/#настройка-данных-маршрута).

### `components`

**тип:** `Record<string, string>`

Укажите пути к компонентам для переопределения реализаций Starlight по умолчанию.

```js
starlight({
	components: {
		SocialLinks: './src/components/MySocialLinks.astro',
	},
});
```

См. [Справочник по переопределениям](/ru/reference/overrides/) для получения подробной информации обо всех компонентах, которые можно переопределить.

### `plugins`

**тип:** [`StarlightPlugin[]`](/ru/reference/plugins/#краткая-справка-по-api)

Расширьте Starlight с помощью пользовательских плагинов.
Плагины вносят изменения в ваш проект, чтобы изменить или добавить функции Starlight.

Посетите [витрину плагинов](/ru/resources/plugins/#плагины), чтобы увидеть список доступных плагинов.

```js
starlight({
	plugins: [starlightPlugin()],
});
```

См. [Справочник по плагинам](/ru/reference/plugins/) для получения подробной информации о создании собственных плагинов.

### `credits`

**тип:** `boolean`  
**по умолчанию:** `false`

Включите отображение ссылки «Сделано с помощью Starlight» в подвале вашего сайта.

```js
starlight({
	credits: true,
});
```

## Настройка коллекций контента

Starlight использует [коллекции контента](https://docs.astro.build/ru/guides/content-collections/) Astro для загрузки вашего контента.
Загрузчики контента и схемы Starlight помогают настроить коллекции в соответствии с вашими потребностями.

```js
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';

export const collections = {
	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
	// Необязательно: коллекция i18n используется для перевода
	// пользовательского интерфейса на многоязычных сайтах
	i18n: defineCollection({ loader: i18nLoader(), schema: i18nSchema() }),
};
```

### Загрузчики

Starlight экспортирует следующие [загрузчики Astro](https://docs.astro.build/ru/reference/content-loader-reference/) из модуля `@astrojs/starlight/loaders`, чтобы упростить настройку коллекций контента.

#### `docsLoader()`

Загрузчик `docsLoader()` загружает локальные файлы Markdown, MDX и Markdoc из директории `src/content/docs/`. Файлы, названия которых начинаются с подчёркивания (`_`), игнорируются.

##### Импорт

```js
import { docsLoader } from '@astrojs/starlight/loaders';
```

##### Параметры

###### `generateId()`

**тип:** `({ entry: string; base: URL; data: Record<string, unknown> }) => string`

По умолчанию страницы, созданные с помощью `docsLoader()`, обрабатывают имена файлов с помощью «слагификатора» (sluggifier), который удаляет специальные символы и приводит имя к нижнему регистру.  
Если вы хотите переопределить это поведение, можно предоставить собственную функцию `generateId()`.

Например, это может быть полезно для сохранения специальных символов, которые в противном случае были бы удалены.  
По умолчанию файл `Example.File.md` будет доступен по пути `/examplefile`.  
Если нужно, чтобы он был доступен по пути `/Example.File`, можно определить кастомную функцию `generateId()`:

```js
docsLoader({
	// Удаляет расширение `.md` или `.mdx`, но в остальном не изменяет названия файлов.
	generateId: ({ entry }) => entry.split('.').slice(0, -1).join('.'),
}),
```

Подробнее см. [`generateId()` в документации Astro](https://docs.astro.build/ru/reference/content-loader-reference/#generateid).

#### `i18nLoader()`

Загрузчик `i18nLoader()` загружает локальные файлы JSON и YAML из директории `src/content/i18n/`.  
Файлы, названия которых начинаются с подчёркивания (`_`), игнорируются.

##### Импорт

```js
import { i18nLoader } from '@astrojs/starlight/loaders';
```

##### Параметры

На данный момент у `i18nLoader()` нет доступных параметров.

### Схемы

Starlight предоставляет следующие [схемы для коллекций контента](https://docs.astro.build/ru/guides/content-collections/#%D0%BE%D0%BF%D1%80%D0%B5%D0%B4%D0%B5%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5-%D1%81%D1%85%D0%B5%D0%BC%D1%8B-%D0%BA%D0%BE%D0%BB%D0%BB%D0%B5%D0%BA%D1%86%D0%B8%D0%B8) из модуля `@astrojs/starlight/schema`.  
Эти схемы обязательны для использования в коллекциях `docs` и `i18n`, от которых зависит Starlight.

#### `docsSchema()`

`schema()` обрабатывает метаданные для всего контента в коллекции `docs`.

##### Импорт

```js
import { docsSchema } from '@astrojs/starlight/schema';
```

##### Параметры

###### `extend`

**тип:** схема Zod или функция, возвращающая схему Zod  
**по умолчанию:** `z.object({})`

Расширяет схему метаданных Starlight дополнительными полями.  
Подробнее об использовании опции `extend` см. в разделе [Настройка схемы метаданных](/ru/reference/frontmatter/#настройка-схемы-метаданных).

#### `i18nSchema()`

Схема `i18nSchema()` обрабатывает все файлы данных в коллекции `i18n`.

##### Импорт

```js
import { i18nSchema } from '@astrojs/starlight/schema';
```

##### Параметры

###### `extend`

**тип:** объект Zod  
**по умолчанию:** `z.object({})`

Расширяет схему интернационализации (i18n) Starlight дополнительными полями.  
Подробнее об использовании опции `extend` см. в разделе [Расширение схемы переводов](/ru/guides/i18n/#расширение-схемы-переводов).


================================================
FILE: docs/src/content/docs/ru/reference/frontmatter.md
================================================
---
title: Метаданные
description: Обзор полей метаданных, поддерживаемых Starlight по умолчанию.
---

Вы можете настроить отдельные страницы Markdown и MDX в Starlight, задав значения в их метаданных. Например, на обычной странице можно задать поля `title` и `description`:

```md {3-4}
---
# src/content/docs/example.md
title: Об этом проекте
description: Узнайте больше о проекте, над которым я работаю.
---

Добро пожаловать на страницу «О сайте»!
```

## Поля метаданных

### `title` (обязательно)

**тип:** `string`

Вы должны указать заголовок для каждой страницы. Это будет отображаться в верхней части страницы, на вкладках браузера и в метаданных страницы.

### `description`

**тип:** `string`

Описание страницы используется в качестве метаданных страницы и будет воспринято поисковыми системами и в превью социальных сетей.

### `slug`

**type**: `string`

Переопределите slug страницы. Более подробную информацию вы найдете в разделе [Определение пользовательских идентификаторов](https://docs.astro.build/en/guides/content-collections/#defining-custom-ids) в документации Astro.

### `editUrl`

**тип:** `string | boolean`

Переопределяет [глобальную конфигурацию `editLink`](/ru/reference/configuration/#editlink). Установите значение `false`, чтобы отключить ссылку «Редактировать страницу» для конкретной страницы или предоставить альтернативный URL, по которому можно редактировать содержимое этой страницы.

### `head`

**тип:** [`HeadConfig[]`](/ru/reference/configuration/#headconfig)

Вы можете добавить дополнительные теги в `<head>` вашей страницы, используя поле `head` метаданных. Это означает, что вы можете добавлять пользовательские стили, метаданные и другие теги на одну страницу. Аналогично [глобальной опции `head`](/ru/reference/configuration/#head).

```md
---
# src/content/docs/example.md
title: О нас
head:
  # Используем свой тег <title>
  - tag: title
    content: Пользовательский заголовок
---
```

### `tableOfContents`

**тип:** `false | { minHeadingLevel?: number; maxHeadingLevel?: number; }`

Переопределяет [глобальную конфигурацию `tableOfContents`](/ru/reference/configuration/#tableofcontents).
Настройте уровни заголовков, которые будут включены, или установите значение `false`, чтобы скрыть оглавление на этой странице.

```md
---
# src/content/docs/example.md
title: Страница, содержащая только H2 в оглавлении
tableOfContents:
  minHeadingLevel: 2
  maxHeadingLevel: 2
---
```

```md
---
# src/content/docs/example.md
title: Страница без оглавления
tableOfContents: false
---
```

### `template`

**тип:** `'doc' | 'splash'`  
**по умолчанию:** `'doc'`

Установите шаблон макета для этой страницы.
Страницы используют макет `'doc'` по умолчанию.
Установите значение `'splash'`, чтобы использовать более широкий макет без боковых панелей, предназначенный для целевых страниц.

### `hero`

**тип:** [`HeroConfig`](#heroconfig)

Добавьте компонент hero в верхнюю часть этой страницы. Хорошо сочетается с `template: splash`.

Например, в этом конфиге показаны некоторые общие опции, включая загрузку изображения из вашего репозитория.

```md
---
# src/content/docs/example.md
title: Моя домашняя страница
template: splash
hero:
  title: 'Мой проект: Быстрая доставка в космосе'
  tagline: Доставьте свои вещи на Луну и обратно в мгновение ока.
  image:
    alt: Сверкающий, ярко раскрашенный логотип
    file: ~/assets/logo.png
  actions:
    - text: Расскажите мне больше
      link: /getting-started/
      icon: right-arrow
    - text: Просмотр на GitHub
      link: https://github.com/astronaut/my-project
      icon: external
      variant: minimal
      attrs:
        rel: me
---
```

Вы можете отображать разные версии главного изображения в светлом и тёмном режимах.

```md
---
# src/content/docs/example.md
hero:
  image:
    alt: Сверкающий, ярко раскрашенный логотип
    dark: ~/assets/logo-dark.png
    light: ~/assets/logo-light.png
---
```

#### `HeroConfig`

```ts
interface HeroConfig {
  title?: string;
  tagline?: string;
  image?:
    | {
        // Относительный путь к изображению в вашем репозитории.
        file: string;
        // Alt-текст, чтобы сделать изображение доступным для вспомогательных технологий
        alt?: string;
      }
    | {
        // Относительный путь к изображению в вашем репозитории, которое будет использоваться для тёмного режима.
        dark: string;
        // Относительный путь к изображению в вашем репозитории, которое будет использоваться для светлого режима.
        light: string;
        // Alt-текст, чтобы сделать изображение доступным для вспомогательных технологий
        alt?: string;
      }
    | {
        // Необработанный HTML для использования в слоте изображения.
        // Это может быть пользовательский тег `<img>` или встроенный `<svg>`.
        html: string;
      };
  actions?: Array<{
    text: string;
    link: string;
    variant?: 'primary' | 'secondary' | 'minimal';
    icon?: string;
    attrs?: Record<string, string | number | boolean>;
  }>;
}
```

### `banner`

**тип:** `{ content: string }`

Отображает баннер объявления в верхней части этой страницы.

Значение `content` может включать HTML для ссылок или другого содержимого.
Например, на этой странице отображается баннер со ссылкой на `example.com`.

```md
---
# src/content/docs/example.md
title: Страница с баннером
banner:
  content: |
    Мы только что запустили нечто крутое!
    <a href="https://example.com">Проверьте</a>
---
```

### `lastUpdated`

**тип:** `Date | boolean`

Переопределяет [глобальную опцию `lastUpdated`](/ru/reference/configuration/#lastupdated). Если указана дата, она должна быть действительной [временной меткой YAML](https://yaml.org/type/timestamp.html) и будет переопределять дату, хранящуюся в истории Git для этой страницы.

```md
---
# src/content/docs/example.md
title: Страница с пользовательской датой последнего обновления
lastUpdated: 2022-08-09
---
```

### `prev`

**тип:** `boolean | string | { link?: string; label?: string }`

Переопределяет [глобальную опцию `pagination`](/ru/reference/configuration/#pagination). Если указана строка, будет заменен сгенерированный текст ссылки, а если указан объект, будут переопределены и ссылка, и текст.

```md
---
# src/content/docs/example.md
# Скрываем ссылку на предыдущую страницу
prev: false
---
```

```md
---
# src/content/docs/example.md
# Переопределяем текст ссылки на предыдущую страницу
prev: Продолжить обучение
---
```

```md
---
# src/content/docs/example.md
# Переопределяем ссылку и текст предыдущей страницы
prev:
  link: /unrelated-page/
  label: Загляните на другую страницу
---
```

### `next`

**тип:** `boolean | string | { link?: string; label?: string }`

То же самое, что и [`prev`](#prev), но для ссылки на следующую страницу.

```md
---
# src/content/docs/example.md
# Скрываем ссылку на следующую страницу
next: false
---
```

### `pagefind`

**тип:** `boolean`  
**по умолчанию:** `true`

Установите, должна ли эта страница быть включена в поисковый индекс [Pagefind](https://pagefind.app/). Установите значение `false`, чтобы исключить страницу из результатов поиска:

```md
---
# src/content/docs/example.md
# Скрываем эту страницу из поискового индекса
pagefind: false
---
```

### `draft`

**тип:** `boolean`  
**по умолчанию:** `false`

Установите, следует ли считать эту страницу черновиком и не включать её в [продакшен-сборки](https://docs.astro.build/ru/reference/cli-reference/#astro-build). Установите значение `true`, чтобы пометить страницу как черновик и сделать её видимой только во время разработки.

```md
---
# src/content/docs/example.md
# Исключить эту страницу из продакшен-сборок
draft: true
---
```

Поскольку черновики страниц не включаются в выходные данные сборки, вы не можете добавить черновики страниц напрямую в конфигурацию боковой панели вашего сайта, используя [слаги](/ru/guides/sidebar/#внутренние-ссылки).
Черновики страниц в каталогах, используемых для [автоматически сгенерированных групп боковой панели](/ru/guides/sidebar/#автогенерируемые-группы), автоматически исключаются в продакшен-сборках.

### `sidebar`

**тип:** [`SidebarConfig`](#sidebarconfig)

Управление отображением этой страницы в [боковой панели](/ru/reference/configuration/#sidebar) при использовании автогенерируемой группы ссылок.

#### `SidebarConfig`

```ts
interface SidebarConfig {
  label?: string;
  order?: number;
  hidden?: boolean;
  badge?: string | BadgeConfig;
  attrs?: Record<string, string | number | boolean | undefined>;
}
```

#### `label`

**тип:** `string`  
**по умолчанию:** [`title`](#title-обязательно) страницы

Устанавливает метку для этой страницы в боковой панели при отображении в автогенерируемой группе ссылок.

```md
---
# src/content/docs/example.md
title: Об этом проекте
sidebar:
  label: О сайте
---
```

#### `order`

**тип:** `number`

Управляйте порядком этой страницы при сортировке автоматически созданной группы ссылок.
Страницы с меньшим значением параметра `order` отображаются выше в группе ссылок.

```md
---
# src/content/docs/example.md
title: Страница, которая будет отображаться первой
sidebar:
  order: 1
---
```

#### `hidden`

**тип:** `boolean`  
**по умолчанию:** `false`

Запрещает включать эту страницу в автоматически создаваемую группу боковой панели.

```md
---
# src/content/docs/example.md
title: Страница, которую нужно скрыть из автоматически созданной боковой панели
sidebar:
  hidden: true
---
```

#### `badge`

**тип:** <code>string | <a href="/ru/reference/configuration/#badgeconfig">BadgeConfig</a></code>

Добавьте значок на страницу в боковой панели, если она отображается в автогенерируемой группе ссылок.
При использовании строки значок будет отображаться с акцентным цветом по умолчанию.
В качестве опции передайте объект [`BadgeConfig`](/ru/reference/configuration/#badgeconfig) с полями `text`, `variant` и `class` для настройки значка.

```md
---
# src/content/docs/example.md
title: Страница со значком
sidebar:
  # Используется вариант по умолчанию, соответствующий акцентному цвету вашего сайта
  badge: Новое
---
```

```md
---
# src/content/docs/example.md
title: Страница со значком
sidebar:
  badge:
    text: Экспериментально
    variant: caution
---
```

#### `attrs`

**тип:** `Record<string, string | number | boolean | undefined>`

Атрибуты HTML для добавления к ссылке на страницу в боковой панели при отображении в автогенерируемой группе ссылок.
Если поле [`autogenerate.attrs`](/ru/guides/sidebar/#пользовательские-html-атрибуты-для-автоматически-сгенерированных-ссылок) установлено для автоматически сгенерированной группы, к которой относится эта страница, атрибуты в метаданных будут объединены с атрибутами группы.

```md
---
# src/content/docs/example.md
title: Открытие страницы в новой вкладке
sidebar:
  # Открывает страницу в новой вкладке
  attrs:
    target: _blank
---
```

## Настройка схемы метаданных

Схема метаданных для коллекции контента Starlight `docs` настраивается в файле `src/content.config.ts` с помощью хелпера `docsSchema()`:

```ts {4,7}
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
  docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
};
```

Подробнее о схемах коллекций содержимого читайте в разделе [Определение схемы коллекции](https://docs.astro.build/ru/guides/content-collections/#%D0%BE%D0%BF%D1%80%D0%B5%D0%B4%D0%B5%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5-%D1%81%D1%85%D0%B5%D0%BC%D1%8B-%D0%BA%D0%BE%D0%BB%D0%BB%D0%B5%D0%BA%D1%86%D0%B8%D0%B8) в документации Astro.

`docsSchema()` принимает следующие параметры:

### `extend`

**тип:** Схема Zod или функция, возвращающая схему Zod  
**по умолчанию:** `z.object({})`

Расширьте схему Starlight дополнительными полями, задав `extend` в опциях `docsSchema()`.
Значение должно быть [схемой Zod](https://docs.astro.build/ru/guides/content-collections/#defining-datatypes-with-zod).

В следующем примере мы задаем более строгий тип для `description`, чтобы сделать его обязательным, и добавляем новое необязательное поле `category`:

```ts {11-16}
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { z } from 'astro/zod';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
  docs: defineCollection({
    loader: docsLoader(),
    schema: docsSchema({
      extend: z.object({
        // Делаем встроенное поле обязательным
        description: z.string(),
        // Добавляем новое поле в схему
        category: z.enum(['tutorial', 'guide', 'reference']).optional(),
      }),
    }),
  }),
};
```

Чтобы воспользоваться преимуществами [хелпера `image()`](https://docs.astro.build/ru/guides/images/#images-in-content-collections), используйте функцию, которая возвращает расширение вашей схемы:

```ts {11-16}
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { z } from 'astro/zod';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
  docs: defineCollection({
    loader: docsLoader(),
    schema: docsSchema({
      extend: ({ image }) => {
        return z.object({
          // Добавляем поле, которое должно разрешаться в локальное изображение
          cover: image(),
        });
      },
    }),
  }),
};
```


================================================
FILE: docs/src/content/docs/ru/reference/icons.mdx
================================================
---
title: Иконки
description: Обзор всех иконок, доступных в Starlight.
---

Starlight предоставляет набор общих иконок, которые вы можете отображать в своем контенте, используя компонент `<Icon>`.

## Использование иконок

Иконки можно отображать с помощью компонента [`<Icon>`](/ru/components/icons/).
Они также часто используются в других компонентах, таких как [карточки](/ru/components/cards/) или в настройках, таких как [hero](/ru/reference/frontmatter/#hero).

## Тип `StarlightIcon`

Используйте тип TypeScript `StarlightIcon`, чтобы ссылаться на названия [встроенных иконок Starlight](#все-иконки).

```ts {2} /icon: (StarlightIcon)/
// src/icon.ts
import type { StarlightIcon } from '@astrojs/starlight/types';

function getIconLabel(icon: StarlightIcon) {
	// …
}
```

## Все иконки

Список всех доступных иконок показан ниже с их соответствующими именами. Кликните по значку, чтобы скопировать код компонента для него.

import IconsList from '~/components/icons-list.astro';

<IconsList labels={{ copied: 'Скопировано!' }} />


================================================
FILE: docs/src/content/docs/ru/reference/overrides.md
================================================
---
title: Переопределения
description: Обзор компонентов и параметров компонентов, поддерживаемых переопределениями Starlight.
tableOfContents:
  maxHeadingLevel: 4
---

Вы можете переопределить встроенные компоненты Starlight, указав пути к заменяющим компонентам в опции конфигурации Starlight [`components`](/ru/reference/configuration/#components).
На этой странице перечислены все компоненты, доступные для переопределения, и даны ссылки на их реализации по умолчанию на GitHub.

Подробнее см. в [Руководстве по переопределению компонентов](/ru/guides/overriding-components/).

## Компоненты

### Элемент `head`

Эти компоненты отображаются внутри элемента `<head>` каждой страницы.
Они должны включать только [элементы, разрешённые внутри `<head>`](https://developer.mozilla.org/ru/docs/Web/HTML/Element/head#%D1%81%D0%BC%D0%BE%D1%82%D1%80%D0%B8%D1%82%D0%B5_%D1%82%D0%B0%D0%BA%D0%B6%D0%B5).

#### `Head`

**Стандартный компонент:** [`Head.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Head.astro)

Компонент, отображаемый внутри `<head>` каждой страницы.

Переопределяйте этот компонент только в крайнем случае.
По возможности используйте [параметр `head` в конфигурации](/ru/reference/configuration/#head), [поле `head` в метаданных](/ru/reference/frontmatter/#head) или [мидлвар для данных маршрута](/ru/guides/route-data/#настройка-данных-маршрута), чтобы настроить данные маршрута, отображаемые компонентом по умолчанию.

#### `ThemeProvider`

**Стандартный компонент:** [`ThemeProvider.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/ThemeProvider.astro)

Компонент, отображаемый внутри `<head>`, который устанавливает поддержку тёмной/светлой темы.
Реализация по умолчанию включает в себя встроенный скрипт и `<template>`, используемый скриптом в [`<ThemeSelect />`](#themeselect).

---

### Доступность

#### `SkipLink`

**Стандартный компонент:** [`SkipLink.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/SkipLink.astro)

Компонент, отображаемый как первый элемент внутри `<body>`, который ссылается на основное содержимое страницы для обеспечения доступности.
Реализация по умолчанию скрыта до тех пор, пока пользователь не наведет на нее курсор с помощью табуляции на клавиатуре.

---

### Макет

Эти компоненты отвечают за компоновку компонентов Starlight и управление представлениями в различных точках останова.
Их переопределение сопряжено со значительными сложностями.
По возможности предпочитайте переопределять компоненты более низкого уровня.

#### `PageFrame`

**Стандартный компонент:** [`PageFrame.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/PageFrame.astro)
**Именованные слоты:** `header`, `sidebar`

Компонент макета оборачивается вокруг большей части содержимого страницы.
Реализация по умолчанию устанавливает макет header-sidebar-main и включает в себя именованные слоты `header` и `sidebar`, а также слот по умолчанию для основного содержимого.
Он также отображает [`<MobileMenuToggle />`](#mobilemenutoggle) для поддержки переключения навигации в боковой панели на маленьких (мобильных) экранах просмотра.

#### `MobileMenuToggle`

**Стандартный компонент:** [`MobileMenuToggle.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MobileMenuToggle.astro)

Компонент, отображаемый внутри [`<PageFrame>`](#pageframe), который отвечает за переключение навигации боковой панели на маленьких (мобильных) экранах просмотра.

#### `TwoColumnContent`

**Стандартный компонент:** [`TwoColumnContent.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/TwoColumnContent.astro)
**Именованный слот:** `right-sidebar`

Компонент макета оборачивается вокруг колонки с основным содержанием и правой боковой панели (оглавление).
Реализация по умолчанию управляет переключением между одноколоночным макетом с малой областью просмотра и двухколоночным макетом с большей областью просмотра.

---

### Шапка

Эти компоненты отображают верхнюю навигационную панель Starlight.

#### `Header`

**Стандартный компонент:** [`Header.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Header.astro)

Компонент заголовка отображается в верхней части каждой страницы.
По умолчанию отображаются [`<SiteTitle />`](#sitetitle), [`<Search />`](#search), [`<SocialIcons />`](#socialicons), [`<ThemeSelect />`](#themeselect), и [`<LanguageSelect />`](#languageselect).

#### `SiteTitle`

**Стандартный компонент:** [`SiteTitle.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/SiteTitle.astro)

Компонент, отображаемый в начале заголовка сайта для отображения заголовка сайта.
Реализация по умолчанию включает логику для отрисовки логотипов, определённую в конфигурации Starlight.

#### `Search`

**Стандартный компонент:** [`Search.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Search.astro)

Компонент, используемый для отображения пользовательского интерфейса поиска Starlight.
Реализация по умолчанию включает кнопку в заголовке и код для отображения модального окна поиска при нажатии на нее и загрузки [интерфейса Pagefind](https://pagefind.app/).

Когда [`pagefind`](/ru/reference/configuration/#pagefind) отключен, компонент поиска по умолчанию не будет отображаться.
Однако если вы переопределите `Search`, ваш пользовательский компонент будет отображаться всегда, даже если параметр конфигурации `pagefind` будет равен `false`.
Это позволяет добавить пользовательский интерфейс для альтернативных поставщиков поиска при отключении Pagefind.

#### `SocialIcons`

**Стандартный компонент:** [`SocialIcons.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/SocialIcons.astro)

Компонент, отображаемый в шапке сайта, включая ссылки на социальные иконки.
Реализация по умолчанию использует опцию [`social`](/ru/reference/configuration/#social) в конфигурации Starlight для отображения иконок и ссылок.

#### `ThemeSelect`

**Стандартный компонент:** [`ThemeSelect.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/ThemeSelect.astro)

Компонент, отображаемый в шапке сайта, который позволяет пользователям выбрать желаемую цветовую схему.

#### `LanguageSelect`

**Стандартный компонент:** [`LanguageSelect.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/LanguageSelect.astro)

Компонент, отображаемый в заголовке сайта, который позволяет пользователям переключиться на другой язык.

---

### Глобальная боковая панель

В глобальной боковой панели Starlight находится основная навигация сайта.
На узких экранах она скрывается за выпадающим меню.

#### `Sidebar`

**Стандартный компонент:** [`Sidebar.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Sidebar.astro)

Компонент, отображаемый перед содержимым страницы, содержащим глобальную навигацию.
Реализация по умолчанию отображается в виде боковой панели на достаточно широких экранах и в виде выпадающего меню на маленьких (мобильных) экранах.
Он также отображает [`<MobileMenuFooter />`](#mobilemenufooter), чтобы показать дополнительные пункты внутри мобильного меню.

#### `MobileMenuFooter`

**Стандартный компонент:** [`MobileMenuFooter.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MobileMenuFooter.astro)

Компонент, отображаемый в нижней части мобильного выпадающего меню.
Реализация по умолчанию отображает [`<ThemeSelect />`](#themeselect) и [`<LanguageSelect />`](#languageselect).

---

### Боковая панель страницы

Боковая панель страницы Starlight отвечает за отображение оглавления, в котором указаны подзаголовки текущей страницы.
На узких экранах это сворачивается в липкое выпадающее меню.

#### `PageSidebar`

**Стандартный компонент:** [`PageSidebar.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/PageSidebar.astro)

Компонент, отображаемый перед содержимым главной страницы для вывода оглавления.
Реализация по умолчанию отображает [`<TableOfContents />`](#tableofcontents) и [`<MobileTableOfContents />`](#mobiletableofcontents).

#### `TableOfContents`

**Стандартный компонент:** [`TableOfContents.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/TableOfContents.astro)

Компонент, который отображает оглавление текущей страницы на широких экранах просмотра.

#### `MobileTableOfContents`

**Стандартный компонент:** [`MobileTableOfContents.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MobileTableOfContents.astro)

Компонент, который отображает оглавление текущей страницы на маленьких (мобильных) экранах просмотра.

---

### Контент

Эти компоненты отображаются в основной колонке содержимого страницы.

#### `Banner`

**Стандартный компонент:** [`Banner.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Banner.astro)

Баннерный компонент, отображаемый в верхней части каждой страницы.
Реализация по умолчанию использует значение [`banner`](/ru/reference/frontmatter/#banner) метаданных страницы для принятия решения о необходимости отрисовки.

#### `ContentPanel`

**Стандартный компонент:** [`ContentPanel.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/ContentPanel.astro)

Компонент макета, используемый для обёртывания секций колонки основного содержимого.

#### `PageTitle`

**Стандартный компонент:** [`PageTitle.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/PageTitle.astro)

Компонент, содержащий элемент `<h1>` для текущей страницы.

Реализации должны обеспечить установку `id="_top"` для элемента `<h1>`, как в реализации по умолчанию.

#### `DraftContentNotice`

**Стандартный компонент:** [`DraftContentNotice.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/DraftContentNotice.astro)

Уведомление, отображаемое пользователям во время разработки, когда текущая страница помечена как черновик.

#### `FallbackContentNotice`

**Стандартный компонент:** [`FallbackContentNotice.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/FallbackContentNotice.astro)

Уведомление, отображаемое пользователям на страницах, где перевод на текущий язык недоступен.
Используется только на многоязычных сайтах.

#### `Hero`

**Стандартный компонент:** [`Hero.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Hero.astro)

Компонент, отображаемый в верхней части страницы, когда в метаданных задан параметр [`hero`](/ru/reference/frontmatter/#hero).
В стандартном варианте на экране отображается крупный заголовок, теглайн и ссылки, призывающие к действию, а также дополнительное изображение.

#### `MarkdownContent`

**Стандартный компонент:** [`MarkdownContent.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MarkdownContent.astro)

Компонент отображается вокруг основного содержимого каждой страницы.
Реализация по умолчанию устанавливает базовые стили для применения к содержимому Markdown.

Стили контента Markdown также представлены в `@astrojs/starlight/style/markdown.css` и ограничены классом CSS `.sl-markdown-content`.

---

### Подвал

Эти компоненты отображаются внизу основного столбца содержимого страницы.

#### `Footer`

**Стандартный компонент:** [`Footer.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Footer.astro)

Компонент нижнего колонтитула отображается внизу каждой страницы.
Реализация по умолчанию отображает [`<LastUpdated />`](#lastupdated), [`<Pagination />`](#pagination) и [`<EditLink />`](#editlink).

#### `LastUpdated`

**Стандартный компонент:** [`LastUpdated.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/LastUpdated.astro)

Компонент отображается в нижнем колонтитуле страницы для отображения даты последнего обновления.

#### `EditLink`

**Стандартный компонент:** [`EditLink.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/EditLink.astro)

Компонент, отображаемый в нижнем колонтитуле страницы для отображения ссылки на страницу, где её можно редактировать.

#### `Pagination`

**Стандартный компонент:** [`Pagination.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Pagination.astro)

Компонент отображается в нижнем колонтитуле страницы для отображения стрелок навигации между предыдущими и следующими страницами.


================================================
FILE: docs/src/content/docs/ru/reference/plugins.md
================================================
---
title: Плагины
description: Обзор API плагинов Starlight.
tableOfContents:
  maxHeadingLevel: 4
---

Плагины Starlight могут настраивать конфигурацию, пользовательский интерфейс и поведение Starlight, а также легко распространяться и использоваться повторно.
На этой справочной странице описаны API, к которым имеют доступ плагины.

Подробнее об использовании плагинов Starlight можно узнать в разделе [Конфигурация](/ru/reference/configuration/#plugins) или на [Витрине плагинов](/ru/resources/plugins/#плагины), чтобы посмотреть список доступных плагинов.

## Краткая справка по API

Плагин Starlight имеет следующую форму.
Подробнее о различных свойствах и параметрах хуков см. ниже.

<!-- prettier-ignore-start -->

```ts
interface StarlightPlugin {
  name: string;
  hooks: {
    'i18n:setup'?: (options: {
      injectTranslations: (
        translations: Record<string, Record<string, string>>
      ) => void;
    }) => void | Promise<void>;
    'config:setup': (options: {
      config: StarlightUserConfig;
      updateConfig: (newConfig: StarlightUserConfig) => void;
      addIntegration: (integration: AstroIntegration) => void;
      addRouteMiddleware: (config: {
        entrypoint: string;
        order?: 'pre' | 'post' | 'default';
      }) => void;
      astroConfig: AstroConfig;
      command: 'dev' | 'build' | 'preview';
      isRestart: boolean;
      logger: AstroIntegrationLogger;
      useTranslations: (lang: string) => I18nT;
      absolutePathToLang: (path: string) => string;
    }) => void | Promise<void>;
  };
}
```

<!-- prettier-ignore-start -->

## `name`

**тип:** `string`

Плагин должен иметь уникальное имя, описывающее его. Имя используется при [регистрации сообщений](#logger), связанных с этим плагином, и может использоваться другими плагинами для определения присутствия этого плагина.

## `hooks`

Хуки — это функции, которые Starlight вызывает для запуска кода плагина в определённое время.

Чтобы получить тип аргументов хука, используйте утилиту `HookParameters` и передайте в неё имя хука.
В следующем примере параметр `options` типизирован таким образом, чтобы соответствовать аргументам, передаваемым в хук `config:setup`:

```ts
import type { HookParameters } from '@astrojs/starlight/types';

function configSetup(options: HookParameters['config:setup']) {
  options.useTranslations('ru');
}
```

### `i18n:setup`

Функция настройки интернационализации плагина, вызываемая при инициализации Starlight.
Хук `i18n:setup` можно использовать для добавления строк перевода, чтобы плагин поддерживал разные локали.
Эти переводы будут доступны через [`useTranslations()`](#usetranslations) в хуке `config:setup` и в UI-компонентах через [`Astro.locals.t()`](/ru/guides/i18n/#использование-ui-переводов).

Хук `i18n:setup` вызывается со следующими параметрами:

#### `injectTranslations`

**тип:** `(translations: Record<string, Record<string, string>>) => void`

Функция обратного вызова для добавления или обновления строк перевода, используемых в [API локализации](/ru/guides/i18n/#использование-ui-переводов) Starlight.

В следующем примере плагин добавляет переводы для пользовательской строки интерфейса `myPlugin.doThing` для локалей `en` и `ru`:

```ts {6-13} /(injectTranslations)[^(]/
// plugin.ts
export default {
  name: 'plugin-with-translations',
  hooks: {
    'i18n:setup'({ injectTranslations }) {
      injectTranslations({
        en: {
          'myPlugin.doThing': 'Do the thing',
        },
        ru: {
          'myPlugin.doThing': 'Делаем что-то',
        },
      });
    },
  },
};
```

Чтобы использовать добавленные переводы в интерфейсе вашего плагина, следуйте [руководству по использованию UI-переводов](/ru/guides/i18n/#использование-ui-переводов).
Если вам нужно использовать строки интерфейса в контексте хука [`config:setup`](#configsetup) вашего плагина, примените функцию [`useTranslations()`](#usetranslations).

Типы для строк перевода, добавленных плагином, автоматически генерируются в проекте пользователя, но пока недоступны при работе с кодовой базой самого плагина.
Чтобы задать тип объекта `locals.t` в контексте вашего плагина, объявите следующие глобальные пространства имён в файле деклараций TypeScript:

```ts
// env.d.ts
declare namespace App {
  type StarlightLocals = import('@astrojs/starlight').StarlightLocals;
  // Определяем объект `locals.t` в контексте плагина.
  interface Locals extends StarlightLocals {}
}

declare namespace StarlightApp {
  // Определяем дополнительные переводы плагина в интерфейсе `I18n`.
  interface I18n {
    'myPlugin.doThing': string;
  }
}
```

Вы также можете вывести типы для интерфейса `StarlightApp.I18n` из исходного файла, если у вас есть объект, содержащий ваши переводы.

Например, для следующего исходного файла:

```ts title="ui-strings.ts"
export const UIStrings = {
  en: { 'myPlugin.doThing': 'Do the thing' },
  ru: { 'myPlugin.doThing': 'Делаем что-то' },
};
```

Следующее объявление будет выводить типы на основе английских ключей в исходном файле:

```ts title="env.d.ts"
declare namespace StarlightApp {
  type UIStrings = typeof import('./ui-strings').UIStrings.en;
  interface I18n extends UIStrings {}
}
```

### `config:setup`

Функция настройки конфигурации плагина, вызываемая при инициализации Starlight (во время выполнения хука интеграции [`astro:config:setup`](https://docs.astro.build/ru/reference/integrations-reference/#astroconfigsetup)).
Хук `config:setup` можно использовать для обновления конфигурации Starlight или добавления интеграций Astro.

Этот хук вызывается со следующими параметрами:

#### `config`

**тип:** `StarlightUserConfig`

Доступная только для чтения копия предоставленной пользователем [конфигурации Starlight](/ru/reference/configuration/).
Эта конфигурация могла быть обновлена другими плагинами, настроенными до текущего.

#### `updateConfig`

**тип:** `(newConfig: StarlightUserConfig) => void`

Функция обратного вызова для обновления предоставленной пользователем [конфигурации Starlight](/ru/reference/configuration/).
Укажите ключи конфигурации корневого уровня, которые вы хотите отменить.
Чтобы обновить значения вложенной конфигурации, необходимо предоставить весь вложенный объект.

Чтобы расширить существующий параметр конфигурации, не переопределяя его, добавьте существующее значение в новое.
В следующем примере новый аккаунт в [`social`](/ru/reference/configuration/#social) добавляется в существующую конфигурацию путем расширения `config.social` в новом массиве `social`:

```ts {6-15}
// plugin.ts
export default {
  name: 'add-twitter-plugin',
  hooks: {
    'config:setup'({ config, updateConfig }) {
      updateConfig({
        social: [
          ...config.social,
          {
            icon: 'twitter',
            label: 'Twitter',
            href: 'https://twitter.com/astrodotbuild',
          },
        ],
      });
    },
  },
};
```

#### `addIntegration`

**тип:** `(integration: AstroIntegration) => void`

Функция обратного вызова для добавления [интеграции Astro](https://docs.astro.build/ru/reference/integrations-reference/), необходимой плагину.

В следующем примере плагин сначала проверяет, настроена ли [интеграция Astro с React](https://docs.astro.build/ru/guides/integrations-guide/react/), и, если нет, использует `addIntegration()` для её добавления:

```ts {14} "addIntegration,"
// plugin.ts
import react from '@astrojs/react';

export default {
  name: 'plugin-using-react',
  hooks: {
    'config:setup'({ addIntegration, astroConfig }) {
      const isReactLoaded = astroConfig.integrations.find(
        ({ name }) => name === '@astrojs/react'
      );

      // Добавляем интеграцию React только в том случае, если она ещё не загружена.
      if (!isReactLoaded) {
        addIntegration(react());
      }
    },
  },
};
```

#### `addRouteMiddleware`

**тип:** `(config: { entrypoint: string; order?: 'pre' | 'post' | 'default' }) => void`

Функция обратного вызова для добавления [мидлвара-обработчика маршрутов](/ru/guides/route-data/) на сайт.

Свойство `entrypoint` должно быть указателем модуля для файла мидлвара вашего плагина, который экспортирует обработчик `onRequest`.

В следующем примере плагин, опубликованный как `@example/starlight-plugin`, добавляет мидлвар маршрутов, используя указатель модуля npm:

```js {6-9}
// plugin.ts
export default {
  name: '@example/starlight-plugin',
  hooks: {
    'config:setup'({ addRouteMiddleware }) {
      addRouteMiddleware({
        entrypoint: '@example/starlight-plugin/route-middleware',
      });
    },
  },
};
```

##### Контроль порядка выполнения

По умолчанию мидлвары плагинов выполняются в порядке их добавления.

Если вам нужно больше контроля над порядком выполнения, используйте необязательное свойство `order`.
Установите `order: "pre"`, чтобы мидлвар выполнялся перед пользовательскими мидлварами.
Установите `order: "post"`, чтобы мидлвар выполнялся после всех остальных мидлваров.

Если два плагина добавляют мидлвары с одинаковым значением `order`, первым выполнится плагин, добавленный первым.

#### `astroConfig`

**тип:** `AstroConfig`

Доступная только для чтения копия предоставленной пользователем [конфигурации Astro](https://docs.astro.build/ru/reference/configuration-reference/).

#### `command`

**тип:** `'dev' | 'build' | 'preview'`

Команда, используемая для запуска Starlight:

- `dev` — Проект выполняется с помощью `astro dev`.
- `build` — Проект выполняется с помощью `astro build`.
- `preview` — Проект выполняется с `astro preview`.

#### `isRestart`

**тип:** `boolean`

`false` при запуске dev-сервера, `true` при перезагрузке.
Частыми причинами перезапуска являются редактирование пользователем файла `astro.config.mjs` во время работы dev-сервера.

#### `logger`

**тип:** `AstroIntegrationLogger`

Экземпляр [логгера интеграции Astro](https://docs.astro.build/ru/reference/integrations-reference/#astrointegrationlogger), который можно использовать для записи журналов.
Все сообщения в журнале будут иметь префикс с названием плагина.

```ts {6}
// plugin.ts
export default {
  name: 'long-process-plugin',
  hooks: {
    'config:setup'({ logger }) {
      logger.info('Начало длительного процесса…');
      // Долгий процесс...
    },
  },
};
```

В приведённом выше примере в журнал будет выведено сообщение, включающее в себя предоставленное информационное сообщение:

```shell
[long-process-plugin] Начало длительного процесса...
```

#### `useTranslations`

**тип:** `(lang: string) => I18nT`

Вызовите `useTranslations()` с тегом языка BCP-47, чтобы сгенерировать утилиту для доступа к строкам интерфейса для этого языка.
`useTranslations()` возвращает аналог API `Astro.locals.t()`, который доступен в компонентах Astro.
Чтобы узнать больше о доступных API, ознакомьтесь с руководством [«Использование UI-переводов»](/ru/guides/i18n/#использование-ui-переводов).

```ts {6}
// plugin.ts
export default {
  name: 'plugin-use-translations',
  hooks: {
    'config:setup'({ useTranslations, logger }) {
      const t = useTranslations('zh-CN');
      logger.info(t('builtWithStarlight.label'));
    },
  },
};
```

Пример выше выведет сообщение, которое включает встроенную строку интерфейса для упрощённого китайского языка:

```shell
[plugin-use-translations] 基于 Starlight 构建
```

#### `absolutePathToLang`

**тип:** `(path: string) => string`

Вызовите `absolutePathToLang()` с абсолютным путём к файлу, чтобы получить язык для этого файла.

Это может быть особенно полезно при добавлении [плагинов remark или rehype](https://docs.astro.build/ru/guides/markdown-content/#%D0%BF%D0%BB%D0%B0%D0%B3%D0%B8%D0%BD%D1%8B-markdown) для обработки файлов Markdown или MDX.
Виртуальный формат файлов, используемый этими плагинами, включает [абсолютный путь](https://github.com/vfile/vfile#filepath) обрабатываемого файла, который можно использовать с `absolutePathToLang()`, чтобы определить язык файла.
Возвращаемый язык можно использовать с хелпером [`useTranslations()`](#usetranslations) для получения строк интерфейса для этого языка.

Например, с учётом следующей конфигурации Starlight:

```js
starlight({
  title: 'Моя документация',
  defaultLocale: 'en',
  locales: {
    // Англоязычная документация в `src/content/docs/en/`
    en: { label: 'English' },
    // Русскоязычная документация в `src/content/docs/ru/`
    ru: { label: 'Русский', lang: 'ru' },
  },
});
```

Плагин может определить язык файла, используя его абсолютный путь:

```ts {6-8} /ru/
// plugin.ts
export default {
  name: 'plugin-use-translations',
  hooks: {
    'config:setup'({ absolutePathToLang, useTranslations, logger }) {
      const lang = absolutePathToLang(
        '/absolute/path/to/project/src/content/docs/ru/index.mdx'
      );
      const t = useTranslations(lang);
      logger.info(t('aside.tip'));
    },
  },
};
```

Пример выше выведет сообщение, которое включает встроенную строку интерфейса для русского языка:

```shell
[plugin-use-translations] Совет
```


================================================
FILE: docs/src/content/docs/ru/reference/route-data.mdx
================================================
---
title: Данные маршрута
description: Полная справочная документация по объекту данных маршрута Starlight.
---

Объект данных маршрута Starlight содержит информацию о текущей странице.
Подробнее о том, как работает модель данных Starlight, читайте в [руководстве «Данные маршрута»](/ru/guides/route-data/).

В компонентах Astro доступ к данным маршрута осуществляется через `Astro.locals.starlightRoute`:

```astro {4}
---
// src/components/Custom.astro

const { hasSidebar } = Astro.locals.starlightRoute;
---
```

В [мидлварах для маршрутов](/ru/guides/route-data/#настройка-данных-маршрута) доступ к данным маршрута осуществляется через объект `context`, передаваемый в вашу функцию-мидлвар:

```ts {5}
// src/routeData.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

export const onRequest = defineRouteMiddleware((context) => {
	const { hasSidebar } = context.locals.starlightRoute;
});
```

## `starlightRoute`

Объект `starlightRoute` имеет следующие свойства:

### `dir`

**Тип:** `'ltr' | 'rtl'`

Направление текста страницы.

### `lang`

**Тип:** `string`

Тег языка BCP-47 для локали этой страницы. Например: `en`, `zh-CN` или `pt-BR`.

### `locale`

**Тип:** `string | undefined`

Базовый путь, по которому доступен язык. `undefined` для корневых локалей.

### `siteTitle`

**Тип:** `string`

Заголовок сайта для локали этой страницы.

### `siteTitleHref`

**Тип:** `string`

Значение для атрибута `href` заголовка сайта, ссылающегося на главную страницу, например, `/`.
Для многоязычных сайтов это будет включать текущую локаль. Например: `/en/` или `/zh-cn/`.

### `id`

**Тип:** `string`

Слаг для этой страницы.

### `isFallback`

**Тип:** `boolean | undefined`

`true`, если эта страница не переведена на текущий язык и отображает контент по умолчанию из основной локали.
Используется только на многоязычных сайтах.

### `entryMeta`

**Тип:** `{ dir: 'ltr' | 'rtl'; lang: string }`

Метаданные локали для контента страницы. Могут отличаться от значений локали верхнего уровня, если страница использует контент по умолчанию.

### `entry`

Запись коллекции контента Astro для текущей страницы.
Включает значения метаданных для текущей страницы в `entry.data`.

```ts
entry: {
	data: {
		title: string;
		description: string | undefined;
		// и т. д.
	}
}
```

Узнайте больше о структуре этого объекта в справочнике: [`CollectionEntry`](https://docs.astro.build/en/reference/modules/astro-content/#collectionentry).

### `sidebar`

**Тип:** `SidebarEntry[]`

Элементы боковой панели навигации сайта для этой страницы.

### `hasSidebar`

**Тип:** `boolean`

Отображать ли боковую панель на этой странице.

### `pagination`

**Тип:** `{ prev?: Link; next?: Link }`

Ссылки на предыдущую и следующую страницы в боковой панели, если она включена.

### `toc`

**Тип:** `{ minHeadingLevel: number; maxHeadingLevel: number; items: TocItem[] } | undefined`

Содержание для этой страницы, если оно включено.

### `headings`

**Тип:** `{ depth: number; slug: string; text: string }[]`

Массив всех заголовков Markdown, извлечённых с текущей страницы.  
Используйте [`toc`](#toc), если хотите создать компонент содержания, который будет учитывать параметры конфигурации Starlight.

### `lastUpdated`

**Тип:** `Date | undefined`

Объект JavaScript `Date`, представляющий дату последнего обновления этой страницы, если это включено.

### `editUrl`

**Тип:** `URL | undefined`

Объект `URL` для адреса, по которому можно отредактировать эту страницу, если это включено.

### `head`

**Тип:** [`HeadConfig[]`](/ru/reference/configuration/#headconfig)

Массив всех тегов, которые следует включить в `<head>` текущей страницы.
Включает важные теги, такие как `<title>` и `<meta charset="utf-8">`.

## Утилиты

### `defineRouteMiddleware()`

Используйте утилиту `defineRouteMiddleware()`, чтобы типизировать мидлвар-модуль для маршрута:

```ts "defineRouteMiddleware"
// src/routeData.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

export const onRequest = defineRouteMiddleware((context) => {
	// ...
});
```

### Тип `StarlightRouteData`

Если вы пишете код, который должен работать с данными маршрута Starlight, вы можете импортировать тип `StarlightRouteData`, чтобы соответствовать структуре `Astro.locals.starlightRoute`.

В следующем примере функция `usePageTitleInTOC()` обновляет данные маршрута, чтобы использовать заголовок текущей страницы в качестве метки для первого элемента в содержании, заменяя стандартную метку «Обзор».
Тип `StarlightRouteData` позволяет проверить, являются ли изменения данных маршрута допустимыми.

```ts "StarlightRouteData"
// src/route-utils.ts
import type { StarlightRouteData } from '@astrojs/starlight/route-data';

export function usePageTitleInTOC(starlightRoute: StarlightRouteData) {
	const overviewLink = starlightRoute.toc?.items[0];
	if (overviewLink) {
		overviewLink.text = starlightRoute.entry.data.title;
	}
}
```

Эту функцию затем можно вызвать из мидлвара маршрута:

```ts {3,6}
// src/route-middleware.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';
import { usePageTitleInTOC } from './route-utils';

export const onRequest = defineRouteMiddleware((context) => {
	usePageTitleInTOC(context.locals.starlightRoute);
});
```


================================================
FILE: docs/src/content/docs/ru/resources/community-content.mdx
================================================
---
title: Контент сообщества
description: Откройте для себя подготовленные сообществом руководства, статьи и видео, которые помогут вам учиться и строить с помощью Starlight!
---

:::tip[Добавьте собственную работу!]
Вы создали какой-то материал о Starlight?
Откройте PR, добавляющий вашу ссылку на эту страницу!
:::

import { CardGrid, LinkCard } from '@astrojs/starlight/components';

## Статьи и обзоры

Вот подборка постов и статей, в которых вы узнаете больше о Starlight и опыте других людей:

<CardGrid>
	<LinkCard
		href="https://devm.io/open-source/starlight-astro"
		title="Генерация статических сайтов с помощью Starlight"
		description="«При разработке компонентов ни одна идея не является слишком большой или слишком маленькой» — интервью с Крисом Свитинбанком, руководителем Starlight"
	/>
	<LinkCard
		href="https://frontendatscale.com/blog/hybrid-frontend-architecture/"
		title="Гибридная архитектура фронтенда с Astro и Starlight"
		description="Макси Феррейра и Бен Холмс создают сайт документации с помощью Starlight, TinaCMS и интерактивной площадки API Playground с аутентификацией."
	/>
	<LinkCard
		href="https://www.olets.dev/posts/comparing-docs-site-builders-vuepress-vs-starlight/"
		title="Сравнение конструкторов сайтов документаций: VuePress против Starlight"
		description="Как соотносятся эти две системы?"
	/>
	<LinkCard
		href="https://astro.build/case-studies/wp-engine/"
		title="Кейс: Снижение затрат на разработку"
		description="Как WP Engine снизил затраты на разработку более чем на 50% с помощью Starlight от Astro."
	/>
	<LinkCard
		href="https://maciekpalmowski.dev/blog/building-a-documentation-site-using-astro-starlight/"
		title="Создание сайта документации с использованием Astro Starlight"
		description="Мачек Пальмовски описывает, как Patchstack мигрировал свою документацию на Starlight."
	/>
	<LinkCard
		href="https://blog.cloudflare.com/open-source-all-the-way-down-upgrading-our-developer-documentation/"
		title="Открытый код на каждом уровне"
		description="Как Cloudflare использовал Starlight для обновления своей документации для разработчиков."
	/>
	<LinkCard
		href="https://starlight-changelog.netlify.app/"
		title="Журнал изменений Starlight"
		description="Просмотр всех релизов пакета @astrojs/starlight на одной удобной странице."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/contributing-to-starlight"
		title="Вклад в Starlight"
		description="Мой личный опыт и рекомендации по внесению вклада в open-source проекты, такие как Starlight."
	/>
</CardGrid>

## Рецепты и руководства

Рецепты — это, как правило, короткие, целенаправленные руководства, которые помогают читателю выполнить конкретную задачу на рабочем примере. Это отличный способ добавить новые функции или поведение в проект Starlight, следуя пошаговым инструкциям! Другие руководства могут объяснять концепции, связанные с той или иной областью контента, например, использование изображений или работа с MDX.

Изучите контент, созданный пользователями Starlight:

<CardGrid>
	<LinkCard
		href="https://www.webpro.nl/scraps/versioned-docs-with-starlight-and-vercel"
		title="Версионированная документация с помощью Starlight и Vercel"
		description="Руководство по внедрению отдельных версий документации для каждой основной версии проекта."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-heading-links"
		title="Добавление ссылок на рубрики Starlight"
		description="Руководство по использованию плагина rehype для обмена ссылками на определенные разделы вашей документации."
	/>
	<LinkCard
		href="https://blog.otterlord.dev/posts/starlight-sponsors/"
		title="Добавление спонсоров на сайт Starlight"
		description="Руководство по внедрению пользовательского компонента спонсора в боковую панель документации."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-og-images"
		title="Добавление изображений Open Graph к Starlight"
		description="Руководство по созданию социальных изображений и соответствующих метатегов для ваших страниц."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-third-party-icon-sets"
		title="Использование сторонних наборов иконок в Starlight"
		description="Руководство по использованию unplugin-icons для расширения выбора доступных иконок для Starlight."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-custom-html-head"
		title="Редактирование HTML-заголовка страниц Starlight"
		description="Узнайте, как добавлять дополнительные данные в head страницы: веб-аналитику, шрифты и скрипты."
	/>
	<LinkCard
		href="https://dev.to/mrrobot/publishing-documentation-with-astro-starlight-691"
		title="Публикация документации с помощью Astro Starlight"
		description="Начало работы с документацией в Starlight."
	/>
	<LinkCard
		href="https://events-3bg.pages.dev/jotter/starlight/"
		title="Включение View Transitions"
		description="Добавьте поддержку анимаций переходов между представлениями, клиентской маршрутизации и навигации в стиле SPA на ваш сайт документации Starlight."
	/>
	<LinkCard
		href="https://jamcomments.com/posts/structured-data-with-starlight"
		title="Добавление структурированных данных на страницы Starlight"
		description="Узнайте, как создавать динамические структурированные данные JSON-LD для страниц документации."
	/>
	<LinkCard
		href="https://starlight-examples.netlify.app/"
		title="Примеры Starlight"
		description="Коллекция вставок StackBlitz, демонстрирующих практические способы работы с сайтами документации Starlight."
	/>
	<LinkCard
		href="https://hideoo.dev/notebooks/starlight-plugins-by-example"
		title="Плагины Starlight на примерах"
		description="Коллекция заметок и примеров по плагинам Starlight и распространённым шаблонам для их создания."
	/>
	<LinkCard
		href="https://blog.trueberryless.org/blog/starlight-progress-indicator/"
		title="Добавление индикатора прогресса чтения"
		description="Узнайте, как добавить горизонтальную полосу прогресса чтения на ваш сайт Starlight."
	/>
	<LinkCard
		href="https://blog.trueberryless.org/blog/starlight-sidebar-whitespace/"
		title="Применяем свои стили к боковой панели Starlight"
		description="Используем CSS, чтобы настроить шрифты, цвета и другие элементы боковой панели Starlight."
	/>
	<LinkCard
		href="https://blog.trueberryless.org/blog/starlight-dropdown-and-list-together/"
		title="Выпадающее меню тем на мобильных, обычный список — на десктопе"
		description="Объединяем два плагина, чтобы на мобильных устройствах было выпадающее меню, а на десктопе — обычный список."
	/>
	<LinkCard
		href="https://blog.trueberryless.org/blog/starlight-autogenerate-whole-sidebar/"
		title="Обработка боковой панели Starlight через мидлвар"
		description="Используем мидлвар маршрутов для управления порядком и подписями групп в боковой панели по аналогии с Nuxt Content."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-custom-social-links"
		title="Добавляем социальные ссылки с собственными иконками в Starlight"
		description="Узнайте, как добавить в шапку сайта Starlight социальные ссылки с собственными иконками."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-paste-images-with-visual-studio-code"
		title="Вставляем изображения в страницы Starlight прямо из Visual Studio Code"
		description="Ускоряем работу с документацией Starlight: вставляем изображения прямо из Visual Studio Code."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-add-diagrams-using-d2"
		title="Добавляем диаграммы в документацию Starlight с помощью D2"
		description="Узнайте, как добавлять диаграммы в документацию Starlight с помощью языка D2."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-og-images-cloudinary-astro-sdk"
		title="Генерируем Open Graph-изображения для Starlight через Cloudinary Astro SDK"
		description="Узнайте, как использовать Cloudinary Astro SDK для генерации изображений Open Graph для сайта на Starlight."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-list-recent-github-releases"
		title="Выводим последние GitHub-релизы в Starlight через Astro Content Layer API"
		description="Узнайте, как использовать Astro Content Layer APIВ для получения списка последних GitHub-релизов в проекте на Starlight."
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-sitewide-banner"
		title="Добавляем общий баннер на весь сайт Starlight"
		description="Как сделать общий для всего сайта баннер, используя встроенную функцию Starlight для баннеров на отдельных страницах."
	/>
	<LinkCard
		href="https://lirantal.com/blog/customizing-astro-starlight-sidebar-gated-content-auth"
		title="Настройка боковой панели Astro Starlight для закрытого контента с аутентификацией"
		description="Защитите свои учебные материалы, используя Clerk и SSR для динамического скрытия или отображения разделов сайдбара Starlight в зависимости от статуса авторизации пользователя."
	/>
</CardGrid>

## Видеоконтент

Откройте для себя видео и каналы с контентом Starlight, включая прямые трансляции и образовательный контент.

import YouTubeGrid from '~/components/youtube-grid.astro';

### Официальные видео

<YouTubeGrid
	videos={[
		{
			href: 'https://www.youtube.com/watch?v=5u0Ds7wzUeI',
			title: 'Starlight от Astro',
			description: 'Смотрите официальное видео запуска Starlight',
		},
		{
			href: 'https://www.youtube.com/watch?v=j8K-ESJF814',
			title: 'Starlight один год!',
			description:
				'Sarah рассказывает о созданной сообществом Astro теме для документации',
		},
	]}
/>

### Видео и стримы от сообщества

<YouTubeGrid
	videos={[
		{
			href: 'https://www.youtube.com/shorts/zjOWezSzd18',
			title: '🌟 Запуск сайта на Starlight менее чем за минуту',
			description:
				'Смотрите, как Ben запускает новый сайт на Starlight меньше чем за минуту!',
		},
		{
			href: 'https://www.youtube.com/watch?v=sF6UcV3moZg',
			title: 'Создание документов с помощью Starlight и Astro',
			description:
				'Посмотрите, как Крис и Алекс погружаются в Starlight с помощью CodingCat.dev',
		},
		{
			href: 'https://www.youtube.com/watch?v=sWkkHbwDeQc',
			title: 'Astro Starlight',
			description: 'Знакомство со Starlight за одну минуту',
		},
		{
			href: 'https://www.youtube.com/watch?v=-Ki-1E5gNCk',
			title:
				'Шаблон документации Astro Starlight (создаём документацию для пользовательского приложения!)',
			description: 'Запустите новый сайт Starlight примерно за 5 минут',
		},
		{
			href: 'https://www.youtube.com/watch?v=12o7WxjAxjM',
			title:
				'Включите документацию Starlight в проект Next.js с помощью прокси',
			description:
				'Установите Starlight в подкаталоге проекта сайта на Next.js',
		},
		{
			href: 'https://www.youtube.com/watch?v=5pq80drDrNs',
			title:
				'Я воссоздал документы Shadcn за 30 минут с помощью этого удивительного инструмента',
			description:
				'В этом видео я рассказываю о том, что делает Starlight таким крутым и почему вы можете попробовать его в своем следующем проекте.',
		},
		{
			href: 'https://www.youtube.com/watch?v=Q1E4Gkt63ko',
			title: 'Astro Starlight и взрыв эмоций с Крисом Свитинбанком',
			description:
				'В этой статье Крис, создатель Starlight, рассказывает о том, как настроить этот фреймворк для нового сайта, посвящённого эмодзи. 🌟 🎇',
		},
	]}
/>


================================================
FILE: docs/src/content/docs/ru/resources/plugins.mdx
================================================
---
title: Плагины и интеграции
description: Откройте для себя инструменты сообщества, такие как плагины и интеграции, которые расширяют возможности Starlight!
sidebar:
  order: 1
---

:::tip[Добавьте собственную работу!]
Вы создали плагин или инструмент для Starlight?
Откройте PR, добавляющий ваш плагин на эту страницу!
:::

## Плагины

[Плагины](/ru/reference/plugins/) могут настраивать конфигурацию, пользовательский интерфейс и поведение Starlight, а также легко распространяться и использоваться повторно.
Расширяйте свой сайт с помощью официальных плагинов, поддерживаемых командой Starlight, и плагинов сообщества, поддерживаемых пользователями Starlight.

### Официальные плагины

<CardGrid>
	<LinkCard
		href="/ru/guides/site-search/#algolia-docsearch"
		title="Algolia DocSearch"
		description="Замена Pagefind, провайдера поиска по умолчанию, на Algolia DocSearch."
	/>
</CardGrid>

### Плагины от сообщества

<CardGrid>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-links-validator"
		title="starlight-links-validator"
		description="Поиск нерабочих ссылок на страницах Starlight."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-typedoc"
		title="starlight-typedoc"
		description="Генерация страниц Starlight из TypeScript с помощью TypeDoc."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-blog"
		title="starlight-blog"
		description="Добавление блога на сайт документации."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-openapi"
		title="starlight-openapi"
		description="Создание страниц документации на основе спецификаций OpenAPI/Swagger."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-obsidian"
		title="starlight-obsidian"
		description="Публикация хранилищ Obsidian на сайте Starlight."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-image-zoom"
		title="starlight-image-zoom"
		description="Добавление возможности масштабирования к изображениям вашей документации."
	/>
	<LinkCard
		href="https://github.com/lorenzolewis/starlight-utils"
		title="starlight-utils"
		description="Расширение Starlight с помощью набора распространённых утилит."
	/>
	<LinkCard
		href="https://github.com/trueberryless/starlight-view-modes"
		title="starlight-view-modes"
		description="Добавление различных режимов просмотра на ваш сайт документации."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-versions"
		title="starlight-versions"
		description="Отображение версий для страниц документации Starlight."
	/>
	<LinkCard
		href="https://inox-tools.fryuni.dev/star-warp"
		title="star-warp"
		description="Поиск на вашем веб-сайте напрямую из панели поиска браузера."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-heading-badges"
		title="starlight-heading-badges"
		description="Добавление значков в заголовки Markdown и MDX."
	/>
	<LinkCard
		href="https://github.com/Fevol/starlight-site-graph"
		title="starlight-site-graph"
		description="Добавление интерактивного графика сайта в боковую панель."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-sidebar-topics"
		title="starlight-sidebar-topics"
		description="Разделение документации на разделы с собственными боковыми панелями."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-cooler-credit"
		title="starlight-cooler-credit"
		description="Добавление блока благодарностей Starlight или Astro в нижней части оглавления."
	/>
	<LinkCard
		href="https://github.com/dragomano/starlight-giscus"
		title="starlight-giscus"
		description="Добавление комментариев Giscus для вашей документации."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-videos"
		title="starlight-videos"
		description="Создание более информативной документации с помощью видео-руководств и курсов."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-kbd"
		title="starlight-kbd"
		description="Удобное документирование горячих клавиш."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-auto-sidebar"
		title="starlight-auto-sidebar"
		description="Настройка автоматически создаваемых групп в боковой панели."
	/>
	<LinkCard
		href="https://github.com/delucis/starlight-llms-txt"
		title="starlight-llms-txt"
		description="Добавление файла llms.txt на сайт документации (основано на llmstxt.org)."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-toc-overview-customizer"
		title="starlight-toc-overview-customizer"
		description="Настройка оглавления в Starlight с изменяемым заголовком раздела «Обзор»."
	/>
	<LinkCard
		href="https://delucis.github.io/starlight-markdown-blocks/"
		title="starlight-markdown-blocks"
		description="Расширение синтаксиса Markdown-вставок в Starlight с помощью пользовательских типов блоков."
	/>
	<LinkCard
		href="https://github.com/WindMillCode/starlight-fullview-mode"
		title="starlight-fullview-mode"
		description="Сворачивание боковых панелей и разворачивание контента на весь экран."
	/>
	<LinkCard
		href="https://github.com/frostybee/starlight-scroll-to-top"
		title="starlight-scroll-to-top"
		description="Добавление кнопки прокрутки страницы вверх к вашему сайту документации."
	/>
	<LinkCard
		href="https://github.com/frostybee/starlight-codeblock-fullscreen"
		title="starlight-codeblock-fullscreen"
		description="Добавление функционала полноэкранного режима для блоков кода Expressive Code в вашей документации."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-auto-drafts"
		title="starlight-auto-drafts"
		description="Изменение поведения черновиков по умолчанию и автоматическое скрытие ссылок на черновики в боковой панели в продакшене."
	/>
	<LinkCard
		href="https://github.com/corsfix/starlight-contextual-menu"
		title="starlight-contextual-menu"
		description="Добавление контекстного меню для вашей документации Starlight."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-changelogs"
		title="starlight-changelogs"
		description="Отображение журналов изменений вместе с документацией вашего проекта."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-github-alerts"
		title="starlight-github-alerts"
		description="Отображение предупреждений GitHub в виде боковых заметок Starlight."
	/>
	<LinkCard
		href="https://github.com/dlcastillop/starlight-page-actions"
		title="starlight-page-actions"
		description="Добавление кнопок действий для страниц в вашу документацию."
	/>
	<LinkCard
		href="https://github.com/typesense/starlight-docsearch-typesense"
		title="starlight-docsearch-typesense"
		description="Альтернатива официальному плагину Algolia DocSearch, работающая на Typesense."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-sidebar-swipe/"
		title="starlight-sidebar-swipe"
		description="Делаем левую боковую панель свайпаемой на мобильных устройствах, как в Discord Mobile."
	/>
	<LinkCard
		href="https://github.com/Rettend/starlight-plugin-icons"
		title="starlight-plugin-icons"
		description="Добавление иконок в Astro Starlight: боковая панель, блоки кода, дерево файлов."
	/>
	<LinkCard
		href="https://github.com/dlcastillop/starlight-ui-tweaks"
		title="starlight-ui-tweaks"
		description="Расширяет основные компоненты интерфейса: добавляет пользовательские ссылки навигации, рекламу, маркетинговые футеры и более чистый переключатель темы."
	/>
	<LinkCard
		href="https://frostybee.github.io/starlight-tags/"
		title="starlight-tags"
		description="Добавьте теги на страницы Starlight для удобной организации и поиска контента."
	/>
	<LinkCard
		href="https://github.com/dionysuzx/starlight-copy-button"
		title="starlight-copy-button"
		description="Копируйте Markdown всей страницы документации с помощью изящной кнопки в заголовке."
	/>
	<LinkCard
		href="https://frostybee.github.io/starlight-telescope/"
		title="starlight-telescope"
		description="Быстро переходите к любой странице вашей документации Starlight благодаря нечёткому поиску и навигации, ориентированной на управление с клавиатуры."
	/>
	<LinkCard
		href="https://frostybee.github.io/starlight-announcement/"
		title="starlight-announcement"
		description="Добавьте в свою документацию Starlight улучшенные баннеры объявлений с возможностью закрытия, различными вариантами оформления, планированием показов и таргетингом на конкретные страницы."
	/>
</CardGrid>

## Инструменты и интеграции от сообщества

import { CardGrid, LinkCard } from '@astrojs/starlight/components';

Эти инструменты и интеграции сообщества можно использовать для добавления функций на ваш сайт Starlight.

<CardGrid>
	<LinkCard
		href="https://www.feelback.dev/blog/new-astro-starlight-integration/"
		title="FeelBack"
		description="Добавление системы обратной связи с пользователями на страницы вашей документации."
	/>
	<LinkCard
		href="https://github.com/val-town/notion-to-astro"
		title="notion-to-astro"
		description="Преобразование экспорта Notion в документы Astro Starlight."
	/>
	<LinkCard
		href="https://github.com/mattjennings/astro-live-code"
		title="astro-live-code"
		description="Отображение блоков кода MDX в виде интерактивных компонентов."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-i18n"
		title="starlight-i18n"
		description="Расширение Visual Studio Code для перевода страниц Starlight."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-package-managers"
		title="starlight-package-managers"
		description="Быстрое отображение команд, связанных с npm, для нескольких менеджеров пакетов."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-showcases"
		title="starlight-showcases"
		description="Набор компонентов Starlight для создания страниц-витрин."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/generator-starlight-plugin"
		title="@hideoo/starlight-plugin"
		description="Генератор для быстрого создания плагинов Starlight."
	/>
	<LinkCard
		href="https://github.com/Linkerin/starlight-to-pdf"
		title="starlight-to-pdf"
		description="Инструмент командной строки для конвертации сайтов Starlight в PDF-файлы."
	/>
	<LinkCard
		href="https://github.com/joesaby/astro-plantuml"
		title="astro-plantuml"
		description="Рендеринг содержимого PlantUML в блоках кода Markdown."
	/>
	<LinkCard
		href="https://github.com/joesaby/astro-mermaid"
		title="astro-mermaid"
		description="Рендеринг Mermaid-контента на стороне клиента в блоках кода Markdown."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/astro-d2"
		title="astro-d2"
		description="Преобразование блоков кода D2 Markdown в диаграммы."
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-links"
		title="starlight-links"
		description="Предоставление IntelliSense для ссылок в контенте Starlight Markdown и MDX с помощью расширения Visual Studio Code."
	/>
	<LinkCard
		href="https://docs.contentisland.net/templates/starlight/"
		title="contentisland-cli"
		description="Подключение и синхронизация проекта Starlight с Headless CMS Content Island для редактирования и управления документацией."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-sidebar-topics-dropdown"
		title="starlight-sidebar-topics-dropdown"
		description="Разделение страницы с документами на несколько подстраниц и переключение между ними с помощью выпадающего меню в боковой панели."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-save-file-component"
		title="starlight-save-file-component"
		description="Быстрое добавление на сайт Starlight ссылки для скачивания файла или другого ресурса."
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-contributor-list"
		title="starlight-contributor-list"
		description="Отображение списка всех контрибьюторов вашего проекта."
	/>
</CardGrid>


================================================
FILE: docs/src/content/docs/ru/resources/showcase.mdx
================================================
---
title: Витрина Starlight
description: Откройте для себя сайты, созданные с помощью Starlight!
sidebar:
  label: Витрина сайтов
---

:::tip[Добавьте свой собственный сайт!]
Вы создали сайт с помощью Starlight?
[Откройте PR](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md#showcase), добавив ссылку на эту страницу!
:::

## Сайты

import ShowcaseSites from '~/components/showcase-sites.astro';

Starlight уже используется в производстве. Вот некоторые из сайтов в Интернете:

<ShowcaseSites />

Посмотреть все [публичные репозитории проектов, использующих Starlight, на GitHub](https://github.com/withastro/starlight/network/dependents).


================================================
FILE: docs/src/content/docs/ru/resources/themes.mdx
================================================
---
title: Темы
description: Оформите документацию с помощью темы от сообщества для Starlight
tableOfContents: false
sidebar:
  order: 2
head:
  - tag: style
    content: |
      body { --sl-content-width: 66.75rem; }
---

import ThemeGrid from '~/components/theme-grid.astro';

Тема — это плагин Starlight, который изменяет внешний вид сайта с помощью [пользовательского CSS](/ru/guides/css-and-tailwind/), [переопределения компонентов](/ru/guides/overriding-components/), или других новых возможностей.

## Темы от сообщества

Установите тему, созданную сообществом, чтобы быстро настроить внешний вид и стиль вашего сайта.

Ознакомьтесь со списком всех тем ниже или попробуйте их интерактивно на [демо-сайте Starlight Themes](https://starlight-themes.netlify.app/).

<ThemeGrid
	labels={{
		/** Accessible label for the theme toggle. */
		legend: 'Превью',
		/** Accessible label for the dark color scheme variant. */
		dark: 'Тёмные',
		/** Accessible label for the light color scheme variant. */
		light: 'Светлые',
	}}
	themes={[
		{
			title: 'Starlight Rapide',
			description:
				'Тема Starlight, вдохновлённая темой Visual Studio Code Vitesse.',
			href: 'https://starlight-theme-rapide.vercel.app/',
			previews: { light: 'rapide-light.png', dark: 'rapide-dark.png' },
		},
		{
			title: 'Starlight Obsidian',
			description:
				'Тема Starlight, вдохновлённая стилем сайтов Obsidian Publish.',
			href: 'https://fevol.github.io/starlight-theme-obsidian/',
			previews: { light: 'obsidian-light.png', dark: 'obsidian-dark.png' },
		},
		{
			title: 'Catppuccin for Starlight',
			description: 'Успокаивающая пастельная тема для Starlight.',
			href: 'https://starlight.catppuccin.com/',
			previews: { light: 'catppuccin-light.png', dark: 'catppuccin-dark.png' },
		},
		{
			title: 'Ion',
			description: 'Элегантная, современная тема для Starlight.',
			href: 'https://louisescher.github.io/starlight-ion-theme/',
			previews: { light: 'ion-light.png', dark: 'ion-dark.png' },
		},
		{
			title: 'Starlight Black',
			description: 'Тема Starlight, вдохновлённая документацией shadcn.',
			href: 'https://starlight-theme-black.vercel.app/',
			previews: { light: 'black-light.png', dark: 'black-dark.png' },
		},
		{
			title: 'Starlight Flexoki',
			description:
				'Тёплая и дружелюбная тема, основанная на цветовой палитре Flexoki.',
			href: 'https://delucis.github.io/starlight-theme-flexoki/',
			previews: { light: 'flexoki-light.png', dark: 'flexoki-dark.png' },
		},
		{
			title: 'Starlight Nova',
			description: 'Красивая и современная тема для Starlight.',
			href: 'https://starlight-theme-nova.pages.dev/',
			previews: { light: 'nova-light.png', dark: 'nova-dark.png' },
		},
		{
			title: 'Starlight Next.js',
			description: 'Тема Starlight, вдохновлённая документацией Next.js.',
			href: 'https://starlight-theme-next.trueberryless.org/',
			previews: { light: 'nextjs-light.png', dark: 'nextjs-dark.png' },
		},
		{
			title: 'Starlight Galaxy',
			description:
				'Тема Astro Starlight, разработанная для публикации документации и образовательного контента.',
			href: 'https://frostybee.github.io/starlight-theme-galaxy/',
			previews: { light: 'galaxy-light.png', dark: 'galaxy-dark.png' },
		},
		{
			title: 'Starlight Page',
			description:
				'Интуитивно понятная, современная тема Starlight с плавными анимациями появления.',
			href: 'https://pelagornis-page.netlify.app/',
			previews: { light: 'page-light.png', dark: 'page-dark.png' },
		},
		{
			title: 'Starlight Gruvbox',
			description: 'Ретро-тема в стиле Gruvbox для Starlight',
			href: 'https://starlight-theme-gruvbox.otterlord.dev/',
			previews: { light: 'gruvbox-light.png', dark: 'gruvbox-dark.png' },
		},
		{
			title: 'Starlight Six',
			description:
				'Чистая и современная тема для Astro.js Starlight от Six Technology',
			href: 'https://six-tech.github.io/Six.StarlightTheme/',
			previews: { light: 'six-light.png', dark: 'six-dark.png' },
		},
		{
			title: 'Starlight Vintage',
			description:
				'Данная тема во многом вдохновлена неустаревающим дизайном оригинальной документации Astro.',
			href: 'https://starlight-theme-vintage.netlify.app/',
			previews: { light: 'vintage-light.png', dark: 'vintage-dark.png' },
		},
		{
			title: 'Starlight Rosé Pine',
			description: 'Сохо-атмосфера для Starlight.',
			href: 'https://starlight-theme-rose-pine.trueberryless.org/',
			previews: { light: 'rose-pine-light.png', dark: 'rose-pine-dark.png' },
		},
	]}
/>

:::tip[Добавьте собственную работу!]
Вы создали тему для Starlight?
[Откройте PR](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md#themes), добавляющий вашу тему на эту страницу!
:::


================================================
FILE: docs/src/content/docs/tr/404.md
================================================
---
title: Sayfa Bulunamadı
template: splash
editUrl: false
lastUpdated: false
hero:
  title: '404'
  tagline: <strong>Houston, bi' problem var.</strong> Bu sayfayı bulamadık.<br>URL'i kontrol et ya da arama çubuğunu kullanmayı dene.
  actions:
    - text: Ana Sayfaya Git
      icon: right-arrow
      link: /tr/
      variant: primary
---


================================================
FILE: docs/src/content/docs/tr/environmental-impact.md
================================================
---
title: Doğa Dostu Dokümanlar
description: Starlight'ın daha çevreci dokümantasyon sitesi oluşturmanda nasıl yardımcı olacağını ve karbon ayakizini nasıl düşüreceğini öğren.
---

Web endüstrisinin iklime etkisinin [%2][sf] ila [%4 arasında küresel karbon emisyonu][bbc]'na sahip olduğu tahmin ediliyor; kabaca havayolları endüstrisindeki emisyon oranında.
Bir websitesinin ekolojik etkisini hesaplamada çok fazla karmaşık etken var, ancak bu rehber dokümantasyon sitenizin çevresel ayakizini düşürmek için birkaç ipucu içerir.

İyi haber şu ki, Starlight'ı seçmek mükemmel bir başlangıç.
Bu site, Carbon Calculator web sitesine göre sayfa başına ziyarette 0.01 gr CO₂ üretimiyle [test edilmiş web sayfaları arasında %99 daha çevreci][sl-carbon].

## Sayfa Büyüklüğü

Bir web sayfası ne kadar veri transfer ederse, ihtiyaç duyacağı enerji o kadar yüksek olur.
Nisan 2023'te [HTTP Archive'daki veri][http]'ye göre orta büyüklükte web sayfası, kullanıcıdan 2,000 KB'tan daha fazla veri indirmeye ihtiyaç duydu.

Starlight, sayfaları mümkün olan en küçük boyutta oluşturur.
Örneğin, ilk ziyarette kullanıcı 50 KB'tan daha az sıkıştırılmış veriyi indirecektir - sadece HTTP Archive medyan değerinin %2.5'i kadar.
İyi bir ön belleğe alma stratejisi ile takip eden gezinmelerde 10 KB kadar küçük veri indirir.

### Görseller

Starlight iyi bir temel sunmasına rağmen, dokümantasyon sayfalarına eklediğiniz görseller sayfa büyüklüğünü hızlıca artırabilir.
Starlight, Astro'nun [optimize edilmiş varlık desteği][assets] yardımıyla Markdown ve MDX dosyalarındaki yerel görselleri optimize etmek için kullanır.

### Arayüz Bileşenleri

React ya da Vue gibi arayüz kütüphaneleri ile oluşturulmuş bileşenler, sayfaya büyük boyutta Javascript ekleyebilir.
[Astro Adaları][islands] ile oluşturulmuş bileşenlerin **varsayılan olarak sıfır tarayıcı-tarafı Javascript** yüklemesi nedeniyle Starlight, Astro üzerine kurulmuştur.

### Ön Bellekleme

Ön bellekleme, halihazırda yüklenmiş verilerin tekrar kullanımı ve tarayıcının ne kadar süre bu veriyi tutacağını kontrol etmek için kullanılır.
İyi bir ön bellekleme stratejisi; kullanıcının yeni içeriği değiştikten sonra mümkün olan en kısa sürede almasını sağlar, fakat buna ek olarak içerik değişmediğinde tekrar tekrar aynı içeriği yüklemesini önler.

[`Cache-Control` HTTP header][cache], ön belleklemeyi yapılandırmanın sık kullanılan bir yoludur.
Starlight kullanarak, `/_astro/` dizini içindeki her şey için uzun ön bellekleme süresi ayarlayabilirsiniz.
Bu dizin CSS, Javascript ve diğer paketlenmiş dosyaları içerir ve güvenle sonsuza dek ön belleğe alınarak gereksiz indirmeleri azaltır:

```
Cache-Control: public, max-age=604800, immutable
```

Ön belleklemenin nasıl yapılandırılacağı web sunucunuza bağlıdır. Örneğin; Vercel önbellekleme stratejisini herhangi bir yapılandırmaya gerek kalmadan uygularken, Netlify'da `public/_headers` altına [Netlify için özel header'lar][ntl-headers] ile ayarlayabilirsiniz:

```
/_astro/*
  Cache-Control: public
  Cache-Control: max-age=604800
  Cache-Control: immutable
```

[cache]: https://csswizardry.com/2019/03/cache-control-for-civilians/
[ntl-headers]: https://docs.netlify.com/routing/headers/

## Güç tüketimi

Bir web sitesinin nasıl oluşturulduğu, web sitesinin kullanıcı cihazında ne kadar güç tüketeceğini etkiler.
En az Javascript kullanarak, Starlight kullanıcının telefon, tablet ve bilgisayarında yükleme ve sayfayı çizme sürecinde ihtiyaç duyulan enerjiyi düşürür.

Analitik takip scriptleri ya da gömülü video gibi ağır Javascript içeriklerini eklerken, bu özelliklerin sayfanızın güç tüketimini artıracağını aklınızda tutun.
Analitik takip script'ine ihtiyacınız varsa, [Cabin][cabin], [Fathom][fathom], ya da [Plausible][plausible] gibi daha hafif seçenekleri göz önünde bulundurun.
Youtube ve Vimeo gibi gömülü videolar [kullanıcı etkileşimi ile videoyu yükleme][lazy-video]. yöntemiyle geliştirilebilir.
[`astro-embed`][embed] gibi paketler ortak hizmetler için yardımcı olabilir.

:::tip[Bunu biliyor musun?]
Javascript'in ayrıştırılması ve derlenmesi tarayıcıların yapması gereken en maliyetli görevlerden biri.
Aynı boyutta JPEG görsel çizimi ile kıyaslandığında, [JavaScript 30 kez daha uzun işleme süresi alabilir][cost-of-js].
:::

[cabin]: https://withcabin.com/
[fathom]: https://usefathom.com/
[plausible]: https://plausible.io/
[lazy-video]: https://web.dev/iframe-lazy-loading/
[embed]: https://www.npmjs.com/package/astro-embed
[cost-of-js]: https://medium.com/dev-channel/the-cost-of-javascript-84009f51e99e

## Barındırma

Web sayfasının nerede barındırıldığı, dokümantasyon sitenizin ne kadar çevre dostu olduğu konusunda büyük etkisi vardır.
Veri merkezleri ve sunucu çiftlikleri büyük ekolojik etkiye sahip olabilir, yüksek elektrik tüketimi ve büyük oranda su kullanımı dahil.

Yenilenebilir enerji kullanan barındırma opsiyonunu seçmek, sitenizin daha az karbon emisyonuna neden olacağı anlamına gelir. [Green Web Directory][gwb] size bu konuda barındırma şirketleri bulmanıza yardımcı olacak bir araçtır.

[gwb]: https://www.thegreenwebfoundation.org/directory/

## Karşılaştırmalar

Diğer dokümantasyon çerçeveleri ile nasıl kıyaslandığını merak ediyor musun?
[Website Carbon Calculator][wcc] ile yapılan testlerle, farklı araçlarla oluşturulmuş benzer sayfaları karşılaştırın.

| Çerçeve                     | sayfa başına ziyarette CO₂ |
| --------------------------- | -------------------------- |
| [Starlight][sl-carbon]      | 0.01gr                     |
| [VitePress][vp-carbon]      | 0.05gr                     |
| [Docus][dc-carbon]          | 0.05gr                     |
| [Sphinx][sx-carbon]         | 0.07gr                     |
| [MkDocs][mk-carbon]         | 0.10gr                     |
| [Nextra][nx-carbon]         | 0.11gr                     |
| [docsify][dy-carbon]        | 0.11gr                     |
| [Docusaurus][ds-carbon]     | 0.24gr                     |
| [Read the Docs][rtd-carbon] | 0.24gr                     |
| [GitBook][gb-carbon]        | 0.71gr                     |

<small>14 Mayıs 2023 tarihli veriler. Güncel bilgileri görmek için linke tıkla.</small>

[sl-carbon]: https://www.websitecarbon.com/website/starlight-astro-build-getting-started/
[vp-carbon]: https://www.websitecarbon.com/website/vitepress-dev-guide-what-is-vitepress/
[dc-carbon]: https://www.websitecarbon.com/website/docus-dev-introduction-getting-started/
[sx-carbon]: https://www.websitecarbon.com/website/sphinx-doc-org-en-master-usage-quickstart-html/
[mk-carbon]: https://www.websitecarbon.com/website/mkdocs-org-getting-started/
[nx-carbon]: https://www.websitecarbon.com/website/nextra-site-docs-docs-theme-start/
[dy-carbon]: https://www.websitecarbon.com/website/docsify-js-org/
[ds-carbon]: https://www.websitecarbon.com/website/docusaurus-io-docs/
[rtd-carbon]: https://www.websitecarbon.com/website/docs-readthedocs-io-en-stable-index-html/
[gb-carbon]: https://www.websitecarbon.com/website/docs-gitbook-com/

## Diğer Kaynaklar

### Araçlar

- [Website Carbon Calculator][wcc]
- [GreenFrame](https://greenframe.io/)
- [Ecograder](https://ecograder.com/)
- [WebPageTest Carbon Control](https://www.webpagetest.org/carbon-control/)
- [Ecoping](https://ecoping.earth/)

### Makaleler ve Konuşmalar

- [“Building a greener web”](https://youtu.be/EfPoOt7T5lg), Michelle Barker'ın konuşması
- [“Sustainable Web Development Strategies Within An Organization”](https://www.smashingmagazine.com/2022/10/sustainable-web-development-strategies-organization/), Michelle Barker'ın makalesi
- [“A sustainable web for everyone”](https://2021.stateofthebrowser.com/speakers/tom-greenwood/), Tom Greenwood'un konuşması
- [“How Web Content Can Affect Power Usage”](https://webkit.org/blog/8970/how-web-content-can-affect-power-usage/), Benjamin Poulain and Simon Fraser'ın makalesi

[sf]: https://www.sciencefocus.com/science/what-is-the-carbon-footprint-of-the-internet/
[bbc]: https://www.bbc.com/future/article/20200305-why-your-internet-habits-are-not-as-clean-as-you-think
[http]: https://httparchive.org/reports/state-of-the-web
[assets]: https://docs.astro.build/en/guides/assets/
[islands]: https://docs.astro.build/en/concepts/islands/
[wcc]: https://www.websitecarbon.com/


================================================
FILE: docs/src/content/docs/tr/getting-started.mdx
================================================
---
title: Başlarken
description: Sıradaki dokümantasyon siteni Astro'nun Starlight'ı ile nasıl oluşturacağını öğren.
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

Starlight, [Astro](https://astro.build) çerçevesi üstüne kurulmuş çok özellikli bir dokümantasyon temasıdır.
Bu rehber, yeni projeye başlamanda yardımcı olacak.
Mevcut Astro projesine Starlight eklemek için [elle kurulum talimatlarını](/tr/manual-setup/) incele.

## Hızlı Başlangıç

### Yeni Proje Oluşturma

Aşağıdaki komutu terminalinde çalıştırarak yeni bir Astro + Starlight projesi oluştur:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight
```

</TabItem>
</Tabs>

Bu, siten için yapılandırmalar ve tüm gerekli dosyalarla birlikte yeni bir [proje dizini](/tr/guides/project-structure/) oluşturacaktır.

:::tip[Çalışan haline göz at]
Starlight'ı tarayıcında dene:
[StackBlitz'deki taslağı aç](https://stackblitz.com/github/withastro/starlight/tree/main/examples/basics).
:::

### Geliştirme sunucusunu başlat

[Astro’nun geliştirme sunucusu](https://docs.astro.build/en/reference/cli-reference/#astro-dev) lokalinizde çalışırken, çalışmanızı önizlemeye ve otomatik olarak tarayıcınızın değişiklik yaptığınızda yenilenmesine olanak tanır.

Geliştirme sunucusunu başlatmak için aşağıdaki komutu proje dizininizde çalıştırın:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm run dev
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dev
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dev
```

</TabItem>
</Tabs>

Bu, terminalinizde lokal önizleme bağlantılı bir mesaj gösterecektir.
Sitenizi tarayıcıda görüntülemek için bu bağlantıyı açın.

### İçerik Ekle

Starlight, yeni bir içerik eklemen ya da var olan dosyalarını getirmen için hazır!

`src/content/docs/` dizini içerisinde yeni Markdown dosyaları oluşturarak yeni sayfalar ekleyin.

Dosya bazlı gezinim ve MDX ile Markdoc dosya desteği hakkında daha fazlası için [“Sayfalar”](/tr/guides/pages/) rehberini okuyun.

### Sonraki Adımlar

- **Yapılandır:** [“Starlight'ı özelleştirmek”](/tr/guides/customization/) rehberinde ortak ayarlar hakkında öğren.
- **Gezinme:** [“Kenar Çubuğu Gezinimi”](/tr/guides/sidebar/) rehberi ile kenar çubuğunu ayarla.
- **Bileşenler:** [“Bileşenler”](/tr/components/using-components/) rehberinde hazır yapılmış kartlar, tablar ve daha fazlasını keşfet.
- **Yayına al:** Astro dokümantayonu içerisindeki [“Siteni yayına al”](https://docs.astro.build/en/guides/deploy/) rehberi ile çalışmanı yayınla.

## Starlight'ı Güncelleme

:::tip
Starlight, beta sürümünde olduğundan dolayı sıklıkla güncelleme ve geliştirmeler yapılacak.
Starlight'ı güncel tuttuğuna emin ol!
:::

Starlight bir Astro entegrasyonudur. Bunu ve diğer Astro paketlerini, terminalinde aşağıdaki komutu çalıştırarak güncelleyebilirsin:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npx @astrojs/upgrade
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dlx @astrojs/upgrade
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dlx @astrojs/upgrade
```

</TabItem>
</Tabs>

[Starlight Değişim Günlüğü](https://github.com/withastro/starlight/blob/main/packages/starlight/CHANGELOG.md)'nde her yayın içindeki değişikliklerin tümünü listeleyebilirsin.

## Starlight'ta Sorun Giderme

Starlight [Proje Yapılandırması](/tr/reference/configuration/) ve [Benzersiz Sayfa Ön-bölüm Yapılandırması](/tr/reference/frontmatter/) bilgileri, bu sitenin referanslar bölümünde mevcuttur. Bu sayfalardan, Starlight siteni doğru yapılandırdığından ve sitenin düzgün çalıştığından emin olmak için kullanabilirsin.

İçerik eklemede ve Starlight siteni özelleştirmene yardımcı olmak için kenar çubuğundaki rehber listesine göz at.
Aradığın cevap dokümantasyonda yoksa, tüm Astro dokümantasyonu için lütfen [Astro Dokümantasyonu](https://docs.astro.build)'nu ziyaret et. Starlight teması altında Astro'nun genel olarak nasıl çalıştığıyla sorun yanıtlanmış olabilir.

Ayrıca, [GitHub üzerindeki Starlight sorunları](https://github.com/withastro/starlight/issues)'nı kontrol edebilir, aktif ve dost canlısı topluluğumuzdan [Astro Discord](https://astro.build/chat/) üzerinden yardım isteyebilirsin! Sorularını `#support` forumunda "starlight" etiketi ile sorabilir, ya da özel `#starlight` kanalımızı mevcut geliştirmeler ve daha fazlası için ziyaret edebilirsin!


================================================
FILE: docs/src/content/docs/tr/index.mdx
================================================
---
title: Starlight 🌟 Astro ile dokümantasyon sitesi oluştur
head:
  - tag: title
    content: Starlight 🌟 Astro ile dokümantasyon sitesi oluştur
description: Starlight, Astro ile güzel ve yüksek performanslı dokümantasyon siteleri oluşturmanıza yardımcı olur.
template: splash
editUrl: false
lastUpdated: false
hero:
  title: Starlight ile dokümanlarınız şıkır şıkır olsun
  tagline: Yıldız gibi dokümantasyon sitesi oluşturmanız için gereken her şey. Hızlı, erişilebilir ve kullanımı kolay.
  image:
    file: ~/assets/hero-star.webp
  actions:
    - text: Başla
      icon: right-arrow
      link: /tr/getting-started/
    - text: Github'da Görüntüle
      icon: external
      variant: minimal
      link: https://github.com/withastro/starlight
---

import { CardGrid, Card } from '@astrojs/starlight/components';
import AboutAstro from '~/components/about-astro.astro';
import TestimonialGrid from '~/components/testimonial-grid.astro';
import Testimonial from '~/components/testimonial.astro';

<CardGrid stagger>
	<Card title="Memnun eden dokümantasyon" icon="open-book">
		İçerir: site navigasyonu, arama, uluslararasılaştırma, arama motoru
		optimizasyonu, okuması kolay tipografi, kod vurgulama, koyu mod and daha
		fazlası.
	</Card>
	<Card title="Astro ile çalışır" icon="rocket">
		Astro'nun tüm gücünü ve performasını sonuna kadar kullanın. Starlight'ı
		favori Astro entegrasyon ve kütüphanelerinizle genişletin.
	</Card>
	<Card title="Markdown, Markdoc, ve MDX" icon="document">
		Favori işaretleme dilinizi getirin. Starlight size Typescript'in tip
		güvenliliğiyle birlikte kurulu ön-bölüm doğrumalasını sunar.
	</Card>
	<Card title="Kendi arayüz bileşenlerini getir" icon="puzzle">
		Starlight bütün bir dokümantasyon çözümüdür ve çerçeve-bağımsız olarak
		gelir. React, Vue, Svelte ve daha fazlası ile genişletin.
	</Card>
</CardGrid>

<TestimonialGrid title="İnsanlar ne diyor">
  <Testimonial
    name="Rachel"
    handle="rachelnabors"
    cite="https://twitter.com/astrodotbuild/status/1724934718745915558"
  >
  Astro ekibi dokümantasyonun nasıl yapılacağını GELİŞTİRDİ ve kullanıma hazır olarak Starlight projesiyle edinebilirsiniz.
  </Testimonial>
  <Testimonial
    name="Flavio"
    handle="flaviocopes"
    cite="https://twitter.com/flaviocopes/status/1738237658717905108"
  >
  Astro'nun resmi başlangıç kiti Starlight, dokümantasyon sitesi oluşturmak için gerçekten muhteşem bir araç.
  </Testimonial>
  <Testimonial
    name="Tomek"
    handle="sulco"
    cite="https://twitter.com/sulco/status/1735610348730802342"
  >
  Starlight bizim mükemmel geliştirici deneyimine başlangıç örneğimiz: hız, kolaylık ve detaylara karşı titizlik ilham verici. Teknik ve görünümü hallediyor, böylece siz içeriğinize odaklanabiliyorsunuz 👏
  
	StackBlitz ekibi tümüyle seviyor!
  </Testimonial>
  <Testimonial
    name="Roberto"
    handle="RmeetsH"
    cite="https://twitter.com/RmeetsH/status/1735783992018760090"
  >
  Starlight benim için oyun-değiştirici oldu, içerik oluşturmaya odaklanmama müsade ediyor.
  Sezgisel tasarımı sadece iş akışımı kolaylaştırmıyor, ayrıca açık kaynak geliştiricileri için oryantasyon süresini kısaltıyor.
  </Testimonial>
  <Testimonial
    name="Joel"
    handle="jhooks"
    cite="https://twitter.com/jhooks/status/1727405160547418405"
  >
	Course Builder dokümantasyonu için Starlight ile biraz vakit geçirdim ve harika geçti. Çokça iyi dokunuşlar ve detaylara boğulmadan Markdown ile yazmaya odaklanabiliyorum.
  </Testimonial>
  <Testimonial
    name="Rick"
    handle="rick_viscomi"
    cite="https://twitter.com/rick_viscomi/status/1665867447910510593"
  >
	Starlight ile uğraşmaya başladım. Söylemeliyim ki kullanıma hazır halde gelen performansından etkilendim.

    💯💯💯💯

  </Testimonial>
  <Testimonial
    name="Nicolas"
    handle="beaussan"
    cite="https://twitter.com/beaussan/status/1735625189583466893"
  >
	Starlight dokümantasyona başlamanın en iyi yolu. Astro'nun hızı ve gücünün arasında ve Starlight'tan gelen kalıp, mükemmel çift.
	Bir süredir benim başlangıcım ve hala seviyorum!

  </Testimonial>
  <Testimonial
    name="Sylwia"
    handle="SylwiaVargas"
    cite="https://x.com/SylwiaVargas/status/1726556825741578286"
  >
	Starlight'ı son işimde kullandım ve bayıldım. Harika bileşenler, sezgisel tasarım, ve süper-hevesli topluluk (ne zaman biri bir şeye ihtiyaç duyarsa ya yakın zamanda ihtiyacı yerine getirirler ya da iş görecek yolu paylaşırlar). Çok keyifli bir deneyim.
  </Testimonial>
  <Testimonial
    name="Lou Cyx"
    handle="loucyx"
    cite="https://elk.zone/m.webtoo.ls/@loucyx@mastodon.social/111587380021362284"
  >
	Starlight sayesinde monorepo sitemdeki dokümantasyon her zamankinden daha iyi görünüyor. Astro'nun tüm gücünü kaybetmeden kullanmak aşırı kolay. Starlight üzerinde çalıştığınız için teşekkür ederim!
  </Testimonial>
  <Testimonial
    name="BowTiedWebReaper"
    handle="BowTiedWebReapr"
    cite="https://twitter.com/BowTiedWebReapr/status/1735633399501697517"
  >
	Starlight dokümantasyon için benim başlangıç aracım. Varolan Astro ürün web siteme dokümantasyon eklemeyi çok kolaylaştırdı, başka bir araç olsaydı alt alan adına ihtiyaç duyardım.
  </Testimonial>
  <Testimonial
    name="Jeff"
    handle="J_Everhart383"
    cite="https://twitter.com/J_Everhart383/status/1691900590048292908"
  >
	WPEngine Atlas Platform dokümantasyonunu yeniden oluşturuyordum. İnanın bana Starlight A+ dokümantasyon platformu oluştumrak için ihtiyacınız olan her şeye sahip 🙌
  </Testimonial>
  <Testimonial
    name="Chloe"
    handle="solelychloe"
    cite="https://twitter.com/solelychloe/status/1695115277602628082"
  >
    Starlight'a bir şans verin!

    	Birkaç sitem için kullandım ve o muhteşem.

  </Testimonial>
</TestimonialGrid>

<AboutAstro title="Size getirildi">
Astro, hız için tasarlanmış hepsi bir arada web çerçevesidir.
Herhangi bir yerden içeriğinizi çekin ve her yere yükleyin, hepsi favori arayüz komponentleriniz ve kütüphanelerinizle güçlendirildi.

[Astro hakkında daha fazlasını öğren](https://astro.build/)

</AboutAstro>


================================================
FILE: docs/src/content/docs/tr/resources/community-content.mdx
================================================
---
title: Topluluk İçeriği
description: Size Starlight ile site yapma ve öğrenmenizde yardım etmesi için topluluk üretimi rehber, makale ve videoları keşfedin!
---

:::tip[Seninkini ekle!]
Starlight ile ilgili içerik oluşturdun mu?
Bu sayfaya bağlantı eklemek için PR açın!
:::

import { CardGrid, LinkCard } from '@astrojs/starlight/components';

## Makaleler ve Görüşler

Starlight hakkında daha fazlasını öğrenmek ve diğer insanları deneyimlerini içeren makale ve gönderiler ait koleksiyon burada:

<CardGrid>
	<LinkCard
		href="https://devm.io/open-source/starlight-astro"
		title="Starlight ile Statik Site Oluşturma"
		description="“Bileşenleri tasarlarken hiçbir fikir çok büyük ya da çok küçük değildir” — Starlight Lideri Chris Swithinbank ile röportaj"
	/>
	<LinkCard
		href="https://frontendatscale.com/blog/hybrid-frontend-architecture/"
		title="Astro ve Starlight ile Hibrit Ön Uç Mimarisi"
		description="Maxi Ferreira ile Ben Holmes; Starlight, TinaCMS ve yetkilendirmeli interaktif API oyunalanı ile dokümantasyon sitesi oluşturuyor."
	/>
	<LinkCard
		href="https://www.olets.dev/posts/comparing-docs-site-builders-vuepress-vs-starlight/"
		title="Dokümantasyon site oluşturucularını karşılaştırmak: VuePress ve Starlight"
		description="Bu iki çerçeve nasıl ölçülür?"
	/>
</CardGrid>

## Tarifler ve Rehberler

Tarifler tipik olarak kısa, okuyucuya belirli bir görevi tamamlayan çalışan örneğini sunan nasıl yapılır rehberi odaklıdır. Tarifler yeni özellik eklemek ya da Starlight projesine takip eden adım adım açıklamalar ile davranış eklemenin mükemmel bir yoludur! Diğer rehber içerik alanı ile ilişkili konseptleri açıklayabilir, görselleri kullanmak ya da MDX ile çalışmak gibi.

Starlight kullanıcı tarafından sağlanan topluluk üretimi içerikleri keşfedin:

<CardGrid>
	<LinkCard
		href="https://www.webpro.nl/scraps/versioned-docs-with-starlight-and-vercel"
		title="Starlight ve Vercel ile Versiyonlanmış dokümantasyon"
		description="Bir projenin her ana versiyonu için ayrı dokümantasyon versiyonlarının uygulanmasına yönelik bir rehber"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-heading-links"
		title="Starlight başlıklarına bağlantılar ekleyin"
		description="Belgelerinizin belirli bölümlerine giden bağlantıları paylaşmak için rehype eklentisi kullanma rehberi"
	/>
	<LinkCard
		href="https://blog.otterlord.dev/posts/starlight-sponsors/"
		title="Starlight sitenize sponsor ekleyin"
		description="Belgelerinizin kenar çubuğuna özel sponsorlar bileşenini uygulamaya yönelik bir rehber"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-og-images"
		title="Starlight'a Open Graph görselleri ekleme"
		description="Sayfalarınız için sosyal görseller ve ilgili meta etiketleri oluşturma rehberi"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-third-party-icon-sets"
		title="Starlight'ta üçüncü taraf ikon setlerini kullanın"
		description="Starlight için mevcut ikonların seçimini genişletmek amacıyla unplugin-icons kullanma rehberi"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-custom-html-head"
		title="Starlight sayfalarının HTML başlığını düzenleyin"
		description="Web analizi, yazı tipleri ve komut dosyaları gibi ortak başlık içeriğini nasıl ekleyeceğinizi öğrenin"
	/>
	<LinkCard
		href="https://dev.to/mrrobot/publishing-documentation-with-astro-starlight-691"
		title="Astro Starlight ile Belgelerin Yayınlanması"
		description="Starlight dokümantasyonunu kullanmaya başlama"
	/>
	<LinkCard
		href="https://events-3bg.pages.dev/jotter/starlight/guide/"
		title="Görünüm Geçişlerini Etkinleştir"
		description="Bag of Tricks'in görünüm geçiş desteğiyle SPA benzeri görünüm ve hissi elde edin"
	/>
</CardGrid>

## Video İçerikleri

Canlı yayınlar ve eğitim içerikleri de dahil olmak üzere Starlight içeriğine sahip videoları ve kanalları keşfedin.

import YouTubeGrid from '~/components/youtube-grid.astro';

### Astro Videoları

<YouTubeGrid
	videos={[
		{
			href: 'https://www.youtube.com/watch?v=5u0Ds7wzUeI',
			title: "Astro'dan Starlight",
			description: 'Resmi Starlight lansman videosunu izleyin',
		},
		{
			href: 'https://www.youtube.com/shorts/zjOWezSzd18',
			title: '🌟 1 DAKİKA ALTINDA HAZIR',
			description:
				"Ben'in bir dakikadan kısa sürede yeni bir Starlight sitesi açmasını izleyin!",
		},
	]}
/>

### Topluluk Videoları ve Yayınları

<YouTubeGrid
	videos={[
		{
			href: 'https://www.youtube.com/watch?v=sF6UcV3moZg',
			title: 'Starlight ve Astro ile dokümanlar oluşturma',
			description:
				"CodingCat.dev ile Chris ve Alex'in Code'da Starlight'a girişini izleyin",
		},
		{
			href: 'https://www.youtube.com/watch?v=sWkkHbwDeQc',
			title: 'Astro Starlight',
			description: "Bir dakikadan kısa sürede Starlight'a giriş.",
		},
		{
			href: 'https://www.youtube.com/watch?v=-Ki-1E5gNCk',
			title:
				'Astro Starlight Belgelendirme Şablonu (özel uygulama belgeleri oluşturun!)',
			description:
				'Yaklaşık 5 dakika içinde yeni bir Starlight sitesini çalışır duruma getirin',
		},
		{
			href: 'https://www.youtube.com/watch?v=12o7WxjAxjM',
			title: "Starlight belgelerini proxy'lerle Next.js projesine dahil etme",
			description:
				"Starlight'ı Next.js web sitesinde bir alt dizin projesi olarak ayarlama",
		},
		{
			href: 'https://www.youtube.com/watch?v=5pq80drDrNs',
			title:
				"Bu Harika Araçla Shadcn'in Dokümanlarını 30 Dakikada Yeniden Oluşturdum",
			description:
				"Bu videoda Starlight'ı bu kadar harika yapan şeyin ne olduğunu ve bir sonraki projenizde neden onu denemek isteyebileceğinizi ele alacağım.",
		},
	]}
/>


================================================
FILE: docs/src/content/docs/tr/resources/showcase.mdx
================================================
---
title: Starlight Vitrini
description: Starlight ile hazırlanmış siteleri keşfet!
sidebar:
  label: Site Vitrini
---

:::tip[Seninkini ekle!]
Starlight ile site yaptın mı?
Bu sayfaya bağlantı eklemek için [PR açın](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md#showcase)!
:::

## Siteler

import ShowcaseSites from '~/components/showcase-sites.astro';

Starlight halihazırda canlıda kullanılıyor. Web'deki bazı siteler şunlar:

<ShowcaseSites />

[Github üzerinde Starlight kullanan herkese açık proje repolarının](https://github.com/withastro/starlight/network/dependents) tümüne bakın.


================================================
FILE: docs/src/content/docs/uk/404.md
================================================
---
title: Не знайдено
template: splash
editUrl: false
lastUpdated: false
hero:
  title: '404'
  tagline: <strong>Г'юстоне, у нас проблема.</strong> Ми не змогли знайти цю сторінку.<br>Перевірте URL або спробуйте скористатися пошуком.
  actions:
    - text: Додому
      icon: right-arrow
      link: /uk/
      variant: primary
---


================================================
FILE: docs/src/content/docs/uk/getting-started.mdx
================================================
---
title: Вступ
description: Дізнайтеся, як стати до створення свого наступного документаційного сайту зі Starlight від Astro.
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

Starlight ─ це повнофункціональна документаційна схема, побудована на основа фреймворку [Astro](https://astro.build).
Цей ґайд допоможе вам розпочати роботу над новим проєктом.
Щоби додати Starlight до наявного проєкту Astro, дивіться [інструкції з ручного встановлення](/uk/manual-setup/).

## Прудкий старт

### Створіть новий проєкт

Створіть новий проєкт Astro + Starlight, виконавши наступну команду в вашому терміналі:

<Tabs>
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight
```

</TabItem>
</Tabs>

Це створить нову [директорію проєкту](/uk/guides/project-structure/) з усіма необхідними файлами й конфіґурацією для вашого сайту.

:::tip[Побачте це в дії]
Випробуйте Starlight у вашому браузері:
[відкрити шаблон на StackBlitz](https://stackblitz.com/github/withastro/starlight/tree/main/examples/basics).
:::

### Запустіть розробницький сервер

Коли працюєте локально, [розробницький сервер Astro](https://docs.astro.build/en/reference/cli-reference/#astro-dev) дозволяє попередньо переглянути вашу роботу та автоматично оновлює браузер, щойно ви вносите зміни.

Щоби запустити розробницький сервер, виконайте таку команду в теці вашого проєкту:

<Tabs>
<TabItem label="npm">

```sh
npm run dev
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dev
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dev
```

</TabItem>
</Tabs>

У термінал видрукується URL локального сервера.
Відкрийте цю ланку, щоби переглянути сайт.

### Додайте контент

Starlight підготовлено, тепер ви можете додавати новий контент або долучати наявні файли!

#### Формати файлів

Starlight підтримує створення контенту у форматах Markdown і MDX без жодних додаткових налаштувань.
Ви можете додати підтримку Markdoc, встановивши експериментальну [інтеґрацію Astro Markdoc](https://docs.astro.build/guides/integrations-guide/markdoc/).

#### Додайте сторінки

Додавайте нові сторінки на ваш сайт, створюючи файли `.md` та `.mdx` у теці `src/content/docs/`.
Використовуйте підтеки, щоб орґанізовувати файли та створювати множинні сеґменти шляху.

Наприклад, оттака структура файлів зґенерує сторінки за адресами `example.com/hello-world` і `example.com/guides/faq`:

import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src/
  - content/
    - docs/
      - guides/
        - faq.md
      - hello-world.md

</FileTree>

#### Безпека типів у преамбулі (frontmatter)

У Starlight усі сторінки поділяють спільний налаштовуваний [набір властивостей преамбули](/uk/reference/frontmatter/), якими визначається вигляд сторінки:

```md
---
title: Привіт, світ!
description: Це сторінка на моїм сайті, що він працює на Starlight!
---
```

Якщо ви забудете щось важливе, Starlight сповістить вас про це.

### Наступні кроки

- **Конфіґурація:** Дізнайтеся про поширені параметри в ґайді [“Налаштовування Starlight”](/uk/guides/customization/).
- **Навіґація:** Спорудить бічну панель у розділі [“Навіґація бічною панеллю”](/uk/guides/sidebar/).
- **Компоненти:** Відкрийте вбудовані картки, вкладки та багато іншого в [“Компонентах”](/uk/components/using-components/).
- **Розгортування:** Опублікуйте власну працю за допомогою посібника [“Розгорніть свій сайт”](https://docs.astro.build/guides/deploy/) в документації Astro.

## Оновлення Starlight

:::tip
Оскільки Starlight поки на стадії beta, очікуйте частих оновлень.
Не забувайте регулярно оновлювати Starlight!
:::

Starlight є інтеґрацією Astro, отже ви можете оновити його так само, як і решту пакетів Astro, ─ виконавши в терміналі команду:

<Tabs>
<TabItem label="npm">

```sh
npx @astrojs/upgrade
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dlx @astrojs/upgrade
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dlx @astrojs/upgrade
```

</TabItem>
</Tabs>

Повний список змін до кожного релізу дивіться в [списку змін Starlight](https://github.com/withastro/starlight/blob/main/packages/starlight/CHANGELOG.md).

## Зневадження Starlight

Використовуйте довідкові сторінки [конфіґурація проєкту](/uk/reference/configuration/) та [індивідуальні налаштуванні преамбули сторінки](/uk/reference/frontmatter/), щоб упевнитися, що ваш сайт налаштований і функціонує належним чином.
Перегляньте ґайди на бічній панелі, щоби дізнатися, як додавати контент і налаштовувати сайт Starlight.

Якщо ви не можете знайти відповідь у цій документації, будь ласка, перегляньте [повну документацію Astro](https://docs.astro.build/).
Ваше питання можна вирішити, зрозумівши, як працює Астро загалом, під капотом Starlight.

Ви також можете перевірити відомі [проблеми Starlight на GitHub](https://github.com/withastro/starlight/issues), а також звернутися по допомогу на [Discord-сервері Astro](https://astro.build/chat/) до нашої активної, дружньої спільноти! Ставте запитання в гілці `#support` із теґом "starlight" або відвідайте спеціальну гілку `#starlight`, щоб обговорити поточну розробку та багато іншого!


================================================
FILE: docs/src/content/docs/uk/index.mdx
================================================
---
title: Starlight 🌟 Створюйте документацію з Astro
head:
  - tag: title
    content: Starlight 🌟 Створюйте документацію з Astro
description: Starlight допомагає створювати якісну й високоефективну документацію за допомогою Astro.
template: splash
editUrl: false
lastUpdated: false
banner:
  content: |
    Оновлюєтесь до Astro 5?
    <a href="https://github.com/withastro/starlight/releases/tag/%40astrojs/starlight%400.30.0">
      Дізнайтеся, як оновити
    </a>
hero:
  title: Осяйте вашу документацію зі Starlight
  tagline: Усе, що треба для створення блискучого сайту з документацією. Швидко, доступно та без зайвих складнощів.
  image:
    file: ~/assets/hero-star.webp
  actions:
    - text: Розпочати
      icon: right-arrow
      link: /uk/getting-started/
    - text: Переглянути на GitHub
      icon: external
      variant: minimal
      link: https://github.com/withastro/starlight
---

import { CardGrid, Card } from '@astrojs/starlight/components';
import AboutAstro from '~/components/about-astro.astro';
import TestimonialGrid from '~/components/testimonial-grid.astro';
import Testimonial from '~/components/testimonial.astro';

<CardGrid stagger>
	<Card title="Документація, яка вражає" icon="open-book">
		Включає в себе: навігацію сайтом, пошук, інтернаціоналізацію, SEO, чітку
		типографіку, підсвітку коду, темний режим і багато іншого.
	</Card>
	<Card title="Працює на Astro" icon="rocket">
		Отримайте усю міць і швидкість Astro. Розширте можливості Starlight за
		допомогою ваших улюблених інтеграцій та бібліотек для Astro.
	</Card>
	<Card title="Markdown, Markdoc і MDX" icon="document">
		Використовуйте свою улюблену мову розмітки. Starlight має вбудовану
		валідацію фронтматера і типобезпечність TypeScript.
	</Card>
	<Card title="Використовуйте вже створені власні UI-компоненти" icon="puzzle">
		Starlight - це фреймворк-незалежне рішення повного циклу для створення
		документації. Воно легко поєднується з React, Vue, Svelte, Solid тощо.
	</Card>
</CardGrid>

<TestimonialGrid title="Що кажуть люди">
  <Testimonial
    name="Rachel"
    handle="rachelnabors"
    cite="https://twitter.com/astrodotbuild/status/1724934718745915558"
  >
    Команда Astro УДОСКОНАЛИЛА процес створення документації, і ви можете отримати все це завдяки їх проєкту Starlight.
  </Testimonial>
  <Testimonial
    name="Flavio"
    handle="flaviocopes"
    cite="https://twitter.com/flaviocopes/status/1738237658717905108"
  >
    Astro Starlight - це дійсно неймовірний інструмент для створення веб-сайту з документацією.
  </Testimonial>
  <Testimonial
    name="Tomek"
    handle="sulco"
    cite="https://twitter.com/sulco/status/1735610348730802342"
  >
    Starlight - найкращий приклад чудового DX: швидкість, зручність та
    увага до деталей надихає. Вона бере на себе технології та зовнішній вигляд,
    щоб ви могли зосередитися на вмісті 👏

    Команда StackBlitz абсолютно в захваті від неї!

  </Testimonial>
  <Testimonial
    name="Roberto"
    handle="RmeetsH"
    cite="https://twitter.com/RmeetsH/status/1735783992018760090"
  >
    Starlight змінила для мене правила гри, дозволивши зосередитися на створенні контенту.

    Її інтуїтивно зрозумілий дизайн не лише спрощує мій робочий процес, але й скорочує час впровадження для розробників відкритого коду.

  </Testimonial>
  <Testimonial
    name="Joel"
    handle="jhooks"
    cite="https://twitter.com/jhooks/status/1727405160547418405"
  >
	  Провів ще трохи часу зі Starlight створюючи документацію для Course Builder, і це був чудовий досвід. Багато приємних дрібниць, і головне що можна зосередитися на написанні в Markdown, а не на налаштуванні сайту.
  </Testimonial>
  <Testimonial
    name="Rick"
    handle="rick_viscomi"
    cite="https://twitter.com/rick_viscomi/status/1665867447910510593"
  >
    Вирішив погратися зі Starlight. Маю зазначити, що я дуже вражений продуктивністю зі старту.

    💯💯💯💯

  </Testimonial>
  <Testimonial
    name="Nicolas"
    handle="beaussan"
    cite="https://twitter.com/beaussan/status/1735625189583466893"
  >
    Starlight — найкращий спосіб почати створювати документацію: 
    потужність і швидкість Astro разом із інструментами Starlight — 
    це ідеальне поєднання.

    Це мій улюблений інструмент вже давно, і я продовжую захоплюватися ним!

  </Testimonial>
  <Testimonial
    name="Sylwia"
    handle="SylwiaVargas"
    cite="https://x.com/SylwiaVargas/status/1726556825741578286"
  >
    Я використовувала Starlight на попередній роботі й була у захваті. Чудові компоненти, інтуїтивний 
    дизайн і надзвичайно чуйна спільнота (коли комусь щось було потрібно, 
    вони швидко додавали це або пропонували альтернативне рішення). Дуже приємний досвід.
  </Testimonial>
  <Testimonial
    name="Lou Cyx"
    handle="loucyx"
    cite="https://elk.zone/m.webtoo.ls/@loucyx@mastodon.social/111587380021362284"
  >
    Документація мого сайту-монорепозиторію виглядає краще, ніж будь-коли, завдяки Starlight. Її надзвичайно легко використовувати, не втрачаючи всю потужність Astro. Дякую за вашу роботу над цим!
  </Testimonial>
  <Testimonial
    name="BowTiedWebReaper"
    handle="BowTiedWebReapr"
    cite="https://twitter.com/BowTiedWebReapr/status/1735633399501697517"
  >
    Starlight — мій улюблений інструмент для документації. Завдяки йому я легко додав документацію до свого існуючого сайту на Astro, при цьому не довелося створювати окремий піддомен, як з іншими подібними інструментами.
  </Testimonial>
  <Testimonial
    name="Jeff"
    handle="J_Everhart383"
    cite="https://twitter.com/J_Everhart383/status/1691900590048292908"
  >
    Я перебудовую документацію платформи WPEngine Atlas. Повірте, Starlight має все необхідне, щоб створити платформу з документацією найвищого рівня 🙌
  </Testimonial>
  <Testimonial
    name="Chloe"
    handle="solelychloe"
    cite="https://twitter.com/solelychloe/status/1695115277602628082"
  >
    Спробуйте Starlight!

    Я використовую його для кількох своїх сайтів, і вона чудова.

  </Testimonial>
</TestimonialGrid>

<AboutAstro title="Подано">
Astro ─ це універсальний веб-фреймворк налаштований на швидкість.
Беріть контент хоч звідки та розгортайте його будь-де, використовуючи ваші улюблені UI-компоненти і бібліотеки.

[Дізнатися більше про Astro](https://astro.build/)

</AboutAstro>


================================================
FILE: docs/src/content/docs/uk/manual-setup.mdx
================================================
---
title: Ручне налаштування
description: Дізнайтеся, як налаштувати Starlight вручну для додавання його в існуючий проект Astro.
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

Найшвидший спосіб створити новий сайт Starlight - це скористатися командою `create astro` як показано у [Вступі](/uk/getting-started/#створіть-новий-проєкт).
Якщо ви хочете додати Starlight до існуючого проекту Astro, цей посібник пояснить як.

## Налаштування Starlight

Щоб слідувати цьому посібнику, вам знадобиться існуючий проєкт Astro.

### Додайте інтеґрацію Starlight

Starlight є [інтеґрацією Astro](https://docs.astro.build/en/guides/integrations-guide/). Додайте її до свого сайту, виконавши команду `astro add` у кореневій директорії вашого проєкту:

<Tabs syncKey="pkg">
	<TabItem label="npm">```sh npx astro add starlight ```</TabItem>
	<TabItem label="pnpm">```sh pnpm astro add starlight ```</TabItem>
	<TabItem label="Yarn">```sh yarn astro add starlight ```</TabItem>
</Tabs>

Це встановить необхідні залежності та додасть Starlight до масиву integrations у вашому конфіґураційному файлі Astro.

### Налаштуйте інтеґрацію

Інтеґрація Starlight налаштовується у файлі `astro.config.mjs`.

Додайте `title`, щоб почати:

```js ins={8}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'Мій чудовий сайт документації',
		}),
	],
});
```

Знайдіть усі доступні параметри в [документації з налаштування Starlight](/uk/reference/configuration/).

### Налаштуйте колекції контенту

Starlight побудований поверх [колекцій вмісту](https://docs.astro.build/en/guides/content-collections/) в Astro, які налаштовуються в файлі `src/content/config.ts`.

Створіть або оновіть файл конфіґурації вмісту, додавши колекцію `docs`, яка використовує `docsSchema` від Starlight:

```js ins={3,6}
// src/content/config.ts
import { defineCollection } from 'astro:content';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
	docs: defineCollection({ schema: docsSchema() }),
};
```

### Додайте вміст

Starlight тепер налаштовано, і час додати трохи вмісту!

Створіть директорію `src/content/docs/` і почніть з додавання файлу `index.md`.
Це буде домашня сторінка вашого нового сайту:

```md
---
# src/content/docs/index.md
title: Моя документація
description: Дізнайтеся більше про мій проєкт на цьому сайті документації, створеному за допомогою Starlight.
---

Ласкаво просимо до мого проєкту!
```

Starlight використовує маршрутизацію на основі файлів, що означає, що кожен файл Markdown, MDX або Markdoc у `src/content/docs/` стане сторінкою на вашому сайті. Метадані Frontmatter (поля `title` і `description` в наведеному вище прикладі) можуть змінити спосіб відображення кожної сторінки.
Перегляньте всі доступні параметри в [документації frontmatter](/uk/reference/frontmatter/).

## Поради щодо існуючих сайтів

Якщо у вас вже є існуючий проект Astro, ви можете використовувати Starlight для швидкого додавання розділу документації на ваш сайт.

### Використання Starlight з підшляхами

Щоб додати всі сторінки Starlight в підшлях, розмістіть весь свій вміст в підкаталозі `src/content/docs/`.

Наприклад, якщо Starlight сторінки повинні всі починатися з `/guides/`, додайте свій вміст в `src/content/docs/guides/` каталог:

import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src/
  - content/
    - docs/
      - **guides/**
        - guide.md
        - index.md
  - pages/
- astro.config.mjs

</FileTree>

У майбутньому ми плануємо краще підтримувати цей випадок, щоб уникнути необхідності в додатковій вкладеній директорії в `src/content/docs/`.

### Використання Starlight з SSR

Щоб увімкнути SSR, дотримуйтесь посібника [“Адаптери для рендерингу на вимогу”](https://docs.astro.build/en/guides/server-side-rendering/) в документації Astro, щоб додати серверний адаптер до вашого проєкту Starlight.

Сторінки документації, згенеровані Starlight, попередньо рендеряться за замовчуванням незалежно від режиму виводу вашого проєкту. Щоб вимкнути попередній рендеринг ваших сторінок Starlight, встановіть [параметр конфіґурації `prerender`](/uk/reference/configuration/#prerender) у значення `false`.


================================================
FILE: docs/src/content/docs/zh-cn/404.md
================================================
---
title: 页面未找到
template: splash
editUrl: false
lastUpdated: false
hero:
  title: '404'
  tagline: <strong>休斯顿,我们遇到了一个问题。</strong>我们找不到该页面。<br>请检查 URL 或尝试使用搜索栏。
  actions:
    - text: 返回首页
      icon: right-arrow
      link: /zh-cn/
      variant: primary
---


================================================
FILE: docs/src/content/docs/zh-cn/components/asides.mdx
================================================
---
title: 旁白
description: 了解如何在 Starlight 中使用旁白,从而在页面的主要内容旁边显示次要信息。
---

import { Aside } from '@astrojs/starlight/components';

要在页面的主要内容旁边显示次要信息,请使用 `<Aside>` 组件。

import Preview from '~/components/component-preview.astro';

<Preview>

<Aside slot="preview">
    在 `<Aside>` 中包含非必要的补充信息。
</Aside>

</Preview>

## 导入

```tsx
import { Aside } from '@astrojs/starlight/components';
```

## 用法

使用 `<Aside>` 组件以显示旁白(也称为“警告”或“标注”)。

`<Aside>` 有一个可选的 [`type`](#type) 属性,它控制着旁白的颜色、图标和默认标题。

<Preview>

````mdx
import { Aside } from '@astrojs/starlight/components';

<Aside>一些在旁白中的内容。</Aside>

<Aside type="caution">一些警示内容。</Aside>

<Aside type="tip">

旁白中还支持其他内容。

```js
// 例如,代码片段。
```

</Aside>

<Aside type="danger">不要将你的密码告诉任何人。</Aside>
````

<Fragment slot="markdoc">

````markdoc
{% aside %}
一些在旁白中的内容。
{% /aside %}

{% aside type="caution" %}
一些警示内容。
{% /aside %}

{% aside type="tip" %}
旁白中还支持其他内容。

```js
// 例如,代码片段。
```
{% /aside %}

{% aside type="danger" %}
不要将你的密码告诉任何人。
{% /aside %}
````

</Fragment>

<Fragment slot="preview">

    <Aside>一些在旁白中的内容。</Aside>

    <Aside type="caution">一些警示内容。</Aside>

    <Aside type="tip">

    旁白中还支持其他内容。

    ```js
    // 例如,代码片段。
    ```

    </Aside>

    <Aside type="danger">不要将你的密码告诉任何人。</Aside>

</Fragment>

</Preview>

Starlight 还提供了用于在 Markdown 和 MDX 中渲染旁白的自定义语法,以此作为 `<Aside>` 组件的替代方案。
有关自定义语法的详细信息,请参阅 [“在 Markdown 中创作内容”](/zh-cn/guides/authoring-content/#旁白) 指南。

### 使用自定义标题

使用 [`title`](#title) 属性覆盖默认的旁白标题。

<Preview>

```mdx 'title="当心!"'
import { Aside } from '@astrojs/starlight/components';

<Aside type="caution" title="当心!">
	*带有* 自定义标题的警告。
</Aside>
```

<Fragment slot="markdoc">

```markdoc 'title="当心!"'
{% aside type="caution" title="当心!" %}
*带有* 自定义标题的警告。
{% /aside %}
```

</Fragment>

<Aside slot="preview" type="caution" title="当心!">
	*带有* 自定义标题的警告。
</Aside>

</Preview>

## `<Aside>` 的属性

**实现:** [`Aside.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Aside.astro)

`<Aside>` 组件接受以下属性:

### `type`

**类型:** `'note' | 'tip' | 'caution' | 'danger'`  
**默认值:** `'note'`

要显示的旁白类型:

- `note` 旁白(默认)为蓝色,并带有一个信息的图标。
- `tip` 旁白为紫色,并带有一个火箭的图标。
- `caution` 旁白为黄色,并带有一个三角警示图标。
- `danger` 旁白为红色。并带有一个八边形警示图标。

### `title`

**类型:** `string`

要显示的旁白的标题。
如果未设置 `title`,则将使用当前旁白的 `type` 作为默认标题。


================================================
FILE: docs/src/content/docs/zh-cn/components/badges.mdx
================================================
---
title: 徽章
description: 了解如何在 Starlight 中使用徽章来显示额外的信息。
---

import { Badge } from '@astrojs/starlight/components';

要显示小段信息,例如状态或类别,请使用 `<Badge>` 组件。

import Preview from '~/components/component-preview.astro';

<Preview>

<Badge slot="preview" text="新" />

</Preview>

## 导入

```tsx
import { Badge } from '@astrojs/starlight/components';
```

## 用法

使用 `<Badge>` 组件显示徽章,并将要显示的内容传递给 `<Badge>` 组件的 [`text`](#text) 属性。

默认情况下,徽章将使用你网站主题的强调色。
要使用徽章内置的某一种颜色,请将 [`variant`](#variant) 属性设置为支持的值之一。

<Preview>

```mdx
import { Badge } from '@astrojs/starlight/components';

- <Badge text="注释" variant="note" />
- <Badge text="成功" variant="success" />
- <Badge text="提示" variant="tip" />
- <Badge text="注意" variant="caution" />
- <Badge text="危险" variant="danger" />
```

<Fragment slot="markdoc">

```markdoc
- {% badge text="注释" variant="note" /%}
- {% badge text="成功" variant="success" /%}
- {% badge text="提示" variant="tip" /%}
- {% badge text="注意" variant="caution" /%}
- {% badge text="危险" variant="danger" /%}
```

</Fragment>

<Fragment slot="preview">
	- <Badge text="注释" variant="note" />
	- <Badge text="成功" variant="success" />
	- <Badge text="提示" variant="tip" />
	- <Badge text="注意" variant="caution" />
	- <Badge text="危险" variant="danger" />
</Fragment>

</Preview>

### 使用不同的尺寸

使用 [`size`](#size) 属性来控制徽章文本的大小。

<Preview>

```mdx /size="\w+"/
import { Badge } from '@astrojs/starlight/components';

- <Badge text="新" size="small" />
- <Badge text="更新更强" size="medium" />
- <Badge text="更新更强更逼格" size="large" />
```

<Fragment slot="markdoc">

```markdoc /size="\w+"/
- {% badge text="新" size="small" /%}
- {% badge text="更新更强" size="medium" /%}
- {% badge text="更新更强更逼格" size="large" /%}
```

</Fragment>

<Fragment slot="preview">
	- <Badge text="新" size="small" />
	- <Badge text="更新更强" size="medium" />
	- <Badge text="更新更强更逼格" size="large" />
</Fragment>

</Preview>

### 自定义徽章

通过使用任何其他 `<span>` 属性(例如带有自定义 CSS 的 `class` 或 `style`)来自定义徽章。

<Preview>

```mdx "style={{ fontStyle: 'italic' }}"
import { Badge } from '@astrojs/starlight/components';

<Badge text="自定义" variant="success" style={{ fontStyle: 'italic' }} />
```

<Fragment slot="markdoc">

```markdoc 'style="font-style: italic;"'
{% badge text="自定义" variant="success" style="font-style: italic;" /%}
```

</Fragment>

<Badge
	slot="preview"
	text="自定义"
	variant="success"
	style={{ fontStyle: 'italic' }}
/>

</Preview>

## `<Badge>` 的属性

**实现:** [`Badge.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Badge.astro)

`<Badge>` 组件接受以下属性,以及所有 [其他的 `<span>` 属性](https://developer.mozilla.org/zh-CN/docs/Web/HTML/Global_attributes):

### `text`

**必要属性**  
**类型:** `string`

要在徽章中显示的文本内容。

### `variant`

**类型:** `'note' | 'danger' | 'success' | 'caution' | 'tip' | 'default'`  
**默认值:** `'default'`

要使用的徽章颜色变体:`note`(蓝色)、`tip`(紫色)、`danger`(红色)、`caution`(橙色)、`success`(绿色)或 `defaul`(主题强调色)。

### `size`

**类型:** `'small' | 'medium' | 'large'`

定义要显示的徽章的大小。


================================================
FILE: docs/src/content/docs/zh-cn/components/card-grids.mdx
================================================
---
title: 卡片网格
description: 了解如何在 Starlight 中将多张卡片包裹在网格中。
sidebar:
  order: 4
---

import { Card, CardGrid, LinkCard } from '@astrojs/starlight/components';

要将多个 [`<Card>`](/zh-cn/components/cards/) 或 [`<LinkCard>`](/zh-cn/components/link-cards/) 组件包装在网格中,请使用 `<CardGrid>` 组件。

import Preview from '~/components/component-preview.astro';

<Preview>

<CardGrid slot="preview">
	<Card title="星星" icon="star">
		天狼星,织女星,参宿四
	</Card>
	<Card title="卫星" icon="moon">
		木卫一,木卫二,木卫三
	</Card>
</CardGrid>

</Preview>

## 导入

```tsx
import { CardGrid } from '@astrojs/starlight/components';
```

## 用法

### 分组卡片

当有足够大的空间时,可以使用 `<CardGrid>` 组件对卡片进行分组,并排显示多个 [`<Card>`](/zh-cn/components/cards/) 组件。

<Preview>

```mdx {3,10}
import { Card, CardGrid } from '@astrojs/starlight/components';

<CardGrid>
	<Card title="试试这个" icon="open-book">
		一些你想着重展示的有趣内容。
	</Card>
	<Card title="其他功能" icon="information">
		更多你想分享的信息。
	</Card>
</CardGrid>
```

<Fragment slot="markdoc">

```markdoc {1,9}
{% cardgrid %}
{% card title="试试这个" icon="open-book" %}
一些你想着重展示的有趣内容。
{% /card %}

{% card title="其他功能" icon="information" %}
更多你想分享的信息。
{% /card %}
{% /cardgrid %}
```

</Fragment>

<CardGrid slot="preview">
	<Card title="试试这个" icon="open-book">
		一些你想着重展示的有趣内容。
	</Card>
	<Card title="其他功能" icon="information">
		更多你想分享的信息。
	</Card>
</CardGrid>

</Preview>

### 分组链接卡片

当有足够大的空间时,可以使用 `<CardGrid>` 组件对链接卡片进行分组,并排显示多个 [`<LinkCard>`](/zh-cn/components/link-cards/) 组件。

<Preview>

```mdx {3,6}
import { LinkCard, CardGrid } from '@astrojs/starlight/components';

<CardGrid>
	<LinkCard title="Markdown 创作" href="/zh-cn/guides/authoring-content/" />
	<LinkCard title="组件" href="/zh-cn/components/using-components/" />
</CardGrid>
```

<Fragment slot="markdoc">

```markdoc {1,5}
{% cardgrid %}
{% linkcard title="Markdown 创作" href="/zh-cn/guides/authoring-content/" /%}

{% linkcard title="组件" href="/zh-cn/components/using-components/" /%}
{% /cardgrid %}
```

</Fragment>

<CardGrid slot="preview">
	<LinkCard title="Markdown 创作" href="/zh-cn/guides/authoring-content/" />
	<LinkCard title="组件" href="/zh-cn/components/using-components/" />
</CardGrid>

</Preview>

### 交错卡片

通过向 `<CardGrid>` 组件添加 [`stagger`](#stagger) 属性,使网格的第二列卡片向着垂直方向移动,从而增添视觉趣味。

该属性在主页上非常有用,可用于展示项目的核心功能。

<Preview>

```mdx "stagger"
import { Card, CardGrid } from '@astrojs/starlight/components';

<CardGrid stagger>
	<Card title="试试这个" icon="open-book">
		一些你想着重展示的有趣内容。
	</Card>
	<Card title="其他功能" icon="information">
		更多你想分享的信息。
	</Card>
</CardGrid>
```

<Fragment slot="markdoc">

```markdoc "stagger=true"
{% cardgrid stagger=true %}
{% card title="试试这个" icon="open-book" %}
一些你想着重展示的有趣内容。
{% /card %}

{% card title="其他功能" icon="information" %}
更多你想分享的信息。
{% /card %}
{% /cardgrid %}
```

</Fragment>

<CardGrid slot="preview" stagger>
	<Card title="试试这个" icon="open-book">
		一些你想着重展示的有趣内容。
	</Card>
	<Card title="其他功能" icon="information">
		更多你想分享的信息。
	</Card>
</CardGrid>

</Preview>

## `<CardGrid>` 的属性

**实现:** [`CardGrid.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/CardGrid.astro)

`<CardGrid>` 组件接受以下属性:

### `stagger`

**类型:** `boolean`

定义是否在网格中交错卡片。


================================================
FILE: docs/src/content/docs/zh-cn/components/cards.mdx
================================================
---
title: 卡片
description: 了解如何在 Starlight 中使用卡片来显示框中的内容。
sidebar:
  order: 2
---

import { Card } from '@astrojs/starlight/components';

要在框中显示与 Starlight 样式匹配的内容,请使用 `<Card>` 组件。

import Preview from '~/components/component-preview.astro';

<Preview>

<Card slot="preview" title="卫星" icon="moon">
	木卫一,木卫二,木卫三
</Card>

</Preview>

## 导入

```tsx
import { Card } from '@astrojs/starlight/components';
```

## 用法

使用 `<Card>` 组件来显示卡片,并为其提供一个 [`title`](#title)。

<Preview>

```mdx
import { Card } from '@astrojs/starlight/components';

<Card title="试试这个">一些你想着重展示的有趣内容。</Card>
```

<Fragment slot="markdoc">

```markdoc
{% card title="试试这个" %}
一些你想着重展示的有趣内容。
{% /card %}
```

</Fragment>

<Card slot="preview" title="试试这个">
	一些你想着重展示的有趣内容。
</Card>

</Preview>

### 为卡片添加图标

要在卡片中包含一个图标,请把 [`icon`](#icon) 属性设置为 [Starlight 的内置图标名称之一](/zh-cn/reference/icons/#所有图标)。

<Preview>

```mdx 'icon="star"'
import { Card } from '@astrojs/starlight/components';

<Card title="星星" icon="star">
	天狼星,织女星,参宿四
</Card>
```

<Fragment slot="markdoc">

```markdoc 'icon="star"'
{% card title="星星" icon="star" %}
天狼星,织女星,参宿四
{% /card %}
```

</Fragment>

<Card slot="preview" title="星星" icon="star">
	天狼星,织女星,参宿四
</Card>

</Preview>

### 分组卡片

当有足够大的空间时,可以使用 [`<CardGrid>`](/zh-cn/components/card-grids/) 组件将多个卡片分组,并排显示多个卡片。
有关示例,请参阅 [“分组卡片”](/zh-cn/components/card-grids/#分组卡片) 指南。

## `<Card>` 的属性

**实现:** [`Card.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Card.astro)

`<Card>` 组件接受以下属性:

### `title`

**必要属性**  
**类型:** `string`

要显示的卡片标题。

### `icon`

**类型:** `string`

将 `icon` 属性设置为 [Starlight 的内置图标名称之一](/zh-cn/reference/icons/#所有图标),能够使卡片包含一个图标。


================================================
FILE: docs/src/content/docs/zh-cn/components/code.mdx
================================================
---
title: 代码
description: 了解如何在没有 Markdown 代码块的情况下,在 Starlight 中显示语法高亮的代码。
---

import { Code } from '@astrojs/starlight/components';

`<Code>` 组件可以渲染出语法高亮的代码。
当无法使用 [Markdown 代码块](/zh-cn/guides/authoring-content/#代码块) 时,它非常有用,例如,渲染来自文件、数据库或 API 等外部源的数据。

import Preview from '~/components/component-preview.astro';

<Preview>

<Code
	slot="preview"
	code={`## 欢迎

来自 **宇宙** 的问候!`}
lang="md"
title="example.md"
ins={3}
/>

</Preview>

## 导入

```tsx
import { Code } from '@astrojs/starlight/components';
```

## 用法

使用 `<Code>` 组件的渲染能将代码语法高亮,例如在展示从外部源获取的代码时。

有关如何使用 `<Code>` 组件和可用属性的完整列表信息,请参阅 [Expressive Code “代码组件” 文档](https://expressive-code.com/key-features/code-component/)。

<Preview>

```mdx
import { Code } from '@astrojs/starlight/components';

export const exampleCode = `console.log('这可能来自文件或 CMS!');`;
export const fileName = 'example.js';
export const highlights = ['文件', 'CMS'];

<Code code={exampleCode} lang="js" title={fileName} mark={highlights} />
```

<Fragment slot="markdoc">

```markdoc
{% code
   code="console.log('这可能来自文件或 CMS!');"
   lang="js"
   title="example.js"
   meta="'文件' 'CMS'" /%}
```

</Fragment>

export const exampleCode = `console.log('这可能来自文件或 CMS!');`;
export const fileName = 'example.js';
export const highlights = ['文件', 'CMS'];

<Code
	slot="preview"
	code={exampleCode}
	lang="js"
	title={fileName}
	mark={highlights}
/>

</Preview>

### 显示导入的代码

在 MDX 文件和 Astro 组件中,使用 [Vite 的 `?raw` 导入后缀](https://cn.vite.dev/guide/assets#importing-asset-as-string) 将任何代码文件作为字符串导入。
然后,你可以将此导入的字符串传递给 `<Code>` 组件,以将其包含在你的页面上。

<Preview>

```mdx "?raw"
# src/content/docs/example.mdx

import { Code } from '@astrojs/starlight/components';
import importedCode from '/tsconfig.json?raw';

<Code code={importedCode} lang="json" title="tsconfig.json" />
```

import importedCode from '../../../../../../examples/basics/tsconfig.json?raw';

<Code slot="preview" code={importedCode} lang="json" title="tsconfig.json" />

</Preview>

## `<Code>` 的属性

**实现:** [`Code.astro`](https://github.com/expressive-code/expressive-code/blob/main/packages/astro-expressive-code/components/Code.astro)

`<Code>` 组件接受 [Expressive Code “Code Component” 文档](https://expressive-code.com/key-features/code-component/#available-props) 中记录的所有 props。


================================================
FILE: docs/src/content/docs/zh-cn/components/file-tree.mdx
================================================
---
title: 文件树
description: 了解如何在 Starlight 中显示带有文件图标和可折叠子目录的目录结构。
---

import { FileTree } from '@astrojs/starlight/components';

要显示带有文件图标和可折叠子目录的目录结构,请使用 `<FileTree>` 组件。

import Preview from '~/components/component-preview.astro';

<Preview>

<FileTree slot="preview">

- astro.config.mjs 一个 **重要** 文件
- package.json
- README.md
- src
  - components
    - **Header.astro**
  - …
- pages/

</FileTree>

</Preview>

## 导入

```tsx
import { FileTree } from '@astrojs/starlight/components';
```

## 用法

使用 `<FileTree>` 组件可以显示带有文件图标和可折叠子目录的文件树。

使用 `<FileTree>` 内的 [无序 Markdown 列表](https://www.markdownguide.org/basic-syntax/#unordered-lists) 来指定文件和目录的结构。
使用嵌套列表可以创建子目录,或在列表项末尾添加 `/` 以将其渲染为没有特定内容的目录。

<Preview>

```mdx
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- astro.config.mjs
- package.json
- src
  - components
    - Header.astro
    - Title.astro
  - pages/

</FileTree>
```

<Fragment slot="markdoc">

```markdoc
{% filetree %}
- astro.config.mjs
- package.json
- src
  - components
    - Header.astro
    - Title.astro
  - pages/
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- astro.config.mjs
- package.json
- src
  - components
    - Header.astro
    - Title.astro
  - pages/

</FileTree>

</Preview>

### 高亮显示条目

通过将文件或目录的名称加粗,来使文件或目录从中脱颖而出,例如 `**README.md**`。

<Preview>

```mdx {7}
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src
  - components
    - **Header.astro**
    - Title.astro

</FileTree>
```

<Fragment slot="markdoc">

```markdoc {4}
{% filetree %}
- src
  - components
    - **Header.astro**
    - Title.astro
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- src
  - components
    - **Header.astro**
    - Title.astro

</FileTree>

</Preview>

### 添加注释

通过在名称后添加更多文本来向文件或目录添加注释。
注释中支持内联 Markdown 格式,例如粗体和斜体。

<Preview>

```mdx {7}
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src
  - components
    - Header.astro 一个 **重要** 文件
    - Title.astro

</FileTree>
```

<Fragment slot="markdoc">

```markdoc {4}
{% filetree %}
- src
  - components
    - Header.astro 一个 **重要** 文件
    - Title.astro
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- src
  - components
    - Header.astro 一个 **重要** 文件
    - Title.astro

</FileTree>

</Preview>

### 添加占位符

将 `...` 或 `…` 作为名称来添加占位符文件和目录。
这可用于向读者指示文件夹应包含更多项目,而无需明确指定所有项目。

<Preview>

```mdx {8}
import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src
  - components
    - Header.astro
    - …

</FileTree>
```

<Fragment slot="markdoc">

```markdoc {5}
{% filetree %}
- src
  - components
    - Header.astro
    - …
{% /filetree %}
```

</Fragment>

<FileTree slot="preview">

- src
  - components
    - Header.astro
    - …

</FileTree>

</Preview>

## `<FileTree>` 的属性

**实现:** [`FileTree.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/FileTree.astro)

`<FileTree>` 组件不接受任何 props。


================================================
FILE: docs/src/content/docs/zh-cn/components/icons.mdx
================================================
---
title: 图标
description: 了解如何在 Starlight 中显示图标。
---

import { Icon } from '@astrojs/starlight/components';

要显示 Starlight [内置图标集](/zh-cn/reference/icons/#所有图标) 中的图标,请使用 `<Icon>` 组件。

import Preview from '~/components/component-preview.astro';

<Preview>

<Icon
	slot="preview"
	name="open-book"
	color="var(--sl-color-text-accent)"
	size="4rem"
/>

</Preview>

## 导入

```tsx
import { Icon } from '@astrojs/starlight/components';
```

## 用法

使用 `<Icon>` 组件来显示图标。
图标需要将 [`name`](#name) 设置为 [Starlight 的内置图标之一](/zh-cn/reference/icons/#所有图标),并且可以选择是否包含 [`label`](#label) 来为屏幕阅读器提供上下文。

<Preview>

```mdx
import { Icon } from '@astrojs/starlight/components';

<Icon name="star" />
<Icon name="starlight" label="Starlight 的 logo" />
```

<Fragment slot="markdoc">

```markdoc
{% icon name="star" /%}
{% icon name="starlight" label="Starlight 的 logo" /%}
```

</Fragment>

<Fragment slot="preview">
	<Icon name="star" />
	<Icon name="starlight" label="Starlight 的 logo" />
</Fragment>

</Preview>

### 自定义图标

[`size`](#size) 和 [`color`](#color) 属性可使用 CSS 单位和颜色值来调整图标的外观。
[`class`](#class) 属性可用于向图标添加自定义 CSS 类。

<Preview>

```mdx
import { Icon } from '@astrojs/starlight/components';

<Icon name="star" color="goldenrod" size="2rem" />
<Icon name="rocket" color="var(--sl-color-text-accent)" />
```

<Fragment slot="markdoc">

```markdoc
{% icon name="star" color="goldenrod" size="2rem" /%}
{% icon name="rocket" color="var(--sl-color-text-accent)" /%}
```

</Fragment>

<Fragment slot="preview">
	<Icon name="star" color="goldenrod" size="2rem" />
	<Icon name="rocket" color="var(--sl-color-text-accent)" />
</Fragment>

</Preview>

## `<Icon>` 的属性

**实现:** [`Icon.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Icon.astro)

`<Icon>` 组件接受以下属性:

### `name`

**必要属性**  
**类型:** [`StarlightIcon`](/zh-cn/reference/icons/#starlighticon-类型)

要显示的图标名称设置为 [Starlight 的内置图标之一](/zh-cn/reference/icons/#所有图标)。

### `label`

**类型:** `string`

一个可选标签,用于为无障碍技术(例如屏幕阅读器)提供上下文。

当未设置 `label` 时,该图标将在无障碍下完全隐藏。
在这种情况下,请确保在没有图标的情况下,上下文仍然可以理解。
例如,仅具有图标的链接 **必须** 包含 `label` 属性才能易于识读,但如果链接已经包含了文本,并且图标纯粹是装饰性的,那么省略 `label` 也许更有意义。

### `size`

**类型:** `string`

图标的大小使用 CSS 单位。

### `color`

**类型:** `string`

使用 CSS 颜色值的图标颜色。

### `class`

**类型:** `string`

要添加到图标的自定义 CSS 类。


================================================
FILE: docs/src/content/docs/zh-cn/components/link-buttons.mdx
================================================
---
title: 链接按钮
description: 了解如何在 Starlight 中创建链接按钮,以在视觉上获得独特的号召性用语链接。
---

import { LinkButton } from '@astrojs/starlight/components';

要在视觉上展示不同的号召性用语链接,请使用 `<LinkBut​​ton>` 组件。

import Preview from '~/components/component-preview.astro';

<Preview>

<LinkButton slot="preview" href="/zh-cn/getting-started/">
	阅读文档
</LinkButton>

</Preview>

## 导入

```tsx
import { LinkButton } from '@astrojs/starlight/components';
```

## 用法

使用 `<LinkBut​​ton>` 组件,以在视觉上展示独特的号召性用语链接。
链接按钮可用于将用户引导至紧密关联或可操作的部分,并且通常在登陆页面上使用。

`<LinkButton>` 需要 [`href`](#href) 属性。
可选部分有,使用 [`variant`](#variant) 属性来自定义链接按钮的外观,该属性可以设置为 `primary`(默认值)、`secondary` 或 `minimal`。

<Preview>

```mdx
import { LinkButton } from '@astrojs/starlight/components';

<LinkButton href="/zh-cn/getting-started/">开始使用</LinkButton>
<LinkButton href="/zh-cn/reference/configuration/" variant="secondary">
	配置参考
</LinkButton>
```

<Fragment slot="markdoc">

```markdoc
{% linkbutton href="/zh-cn/getting-started/" %}开始使用{% /linkbutton %}

{% linkbutton href="/zh-cn/reference/configuration/" variant="secondary" %}
配置参考
{% /linkbutton %}
```

</Fragment>

<Fragment slot="preview">
	<LinkButton href="/zh-cn/getting-started/">开始使用</LinkButton>
	<LinkButton href="/zh-cn/reference/configuration/" variant="secondary">
		配置参考
	</LinkButton>
</Fragment>

</Preview>

### 向链接按钮添加图标

使用设置为 [Starlight 内置图标之一](/zh-cn/reference/icons/#所有图标) 名称的 [`icon`](#icon) 属性,以在链接按钮中包含图标。

可通过设置 [`iconPlacement`](#iconplacement) 属性为 `start`(默认为 `end`)来将图标放置在文本之前。

<Preview>

```mdx {6-7}
import { LinkButton } from '@astrojs/starlight/components';

<LinkButton
	href="https://docs.astro.build"
	variant="secondary"
	icon="external"
	iconPlacement="start"
>
	有关内容:Astro
</LinkButton>
```

<Fragment slot="markdoc">

```markdoc {4-5}
{% linkbutton
   href="https://docs.astro.build"
	 variant="secondary"
	 icon="external"
	 iconPlacement="start" %}
有关内容:Astro
{% /linkbutton %}
```

</Fragment>

<LinkButton
	slot="preview"
	href="https://docs.astro.build"
	variant="secondary"
	icon="external"
	iconPlacement="start"
>
	有关内容:Astro
</LinkButton>

</Preview>

## `<LinkButton>` 的属性

**实现:** [`LinkButton.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/LinkButton.astro)

`<LinkBut​​ton>` 组件接受以下属性以及任何 [其他 `<a>` 属性](https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/a):

### `href`

**必要属性**  
**类型:** `string`

链接按钮指向的 URL。

### `variant`

**类型:** `'primary' | 'secondary' | 'minimal'`  
**默认值:** `'primary'`

链接按钮的外观。
将链接设置为 `primary` 用于显示主题强调色的号召性用语链接;设置为 `secondary` 用于显示不太显眼的链接;设置为 `minimal` 用于显示最低优先级的链接。

### `icon`

**类型:** `string`

链接按钮可以包含一个 `icon` 属性,该属性应设置为 [Starlight 的内置图标之一](/zh-cn/reference/icons/#所有图标) 的名称。

### `iconPlacement`

**类型:** `'start' | 'end'`  
**默认值:** `'end'`

决定了图标相对于链接按钮文本的位置。


================================================
FILE: docs/src/content/docs/zh-cn/components/link-cards.mdx
================================================
---
title: 链接卡片
description: 了解如何在 Starlight 中将链接突出显示为卡片。
sidebar:
  order: 3
---

import { LinkCard } from '@astrojs/starlight/components';

要突出显示不同页面的链接,请使用 `<LinkCard>` 组件。

import Preview from '~/components/component-preview.astro';

<Preview>

<LinkCard
	slot="preview"
	title="自定义 Starlight"
	description="学习如何通过自定义样式、字体等使你的 Starlight 网站变得与众不同。"
	href="/zh-cn/guides/customization/"
/>

</Preview>

## 导入

```tsx
import { LinkCard } from '@astrojs/starlight/components';
```

## 用法

使用 `<LinkCard>` 组件来突出显示链接。
每个 `<LinkCard>` 都需要一个 [`title`](#title) 和一个 [`href`](#href) 属性。

<Preview>

```mdx
import { LinkCard } from '@astrojs/starlight/components';

<LinkCard title="Markdown 创作" href="/zh-cn/guides/authoring-content/" />
```

<Fragment slot="markdoc">

```markdoc
{% linkcard title="Markdown 创作" href="/zh-cn/guides/authoring-content/" /%}
```

</Fragment>

<LinkCard
	slot="preview"
	title="Markdown 创作"
	href="/zh-cn/guides/authoring-content/"
/>

</Preview>

### 添加链接描述

使用 [`description`](#description) 属性向链接卡片添加一个简短的描述。

<Preview>

```mdx {6}
import { LinkCard } from '@astrojs/starlight/components';

<LinkCard
	title="国际化"
	href="/zh-cn/guides/i18n/"
	description="配置 Starlight 以支持多种语言。"
/>
```

<Fragment slot="markdoc">

```markdoc {4}
{% linkcard
   title="国际化"
	 href="/zh-cn/guides/i18n/"
	 description="配置 Starlight 以支持多种语言。" /%}
```

</Fragment>

<LinkCard
	slot="preview"
	title="国际化"
	href="/zh-cn/guides/i18n/"
	description="配置 Starlight 以支持多种语言。"
/>

</Preview>

### 分组链接卡片

当有足够大的空间时,可以使用 [`<CardGrid>`](/zh-cn/components/card-grids/) 组件对链接卡片进行分组,来并排显示多个链接卡片。
有关示例,请参阅 [“分组链接卡片”](/zh-cn/components/card-grids/#分组链接卡片) 指南。

## `<LinkCard>` 的属性

**实现:** [`LinkCard.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/LinkCard.astro)

`<LinkCard>` 组件接受以下属性,以及其他所有的 [`<a>` 元素属性](https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/a):

### `title`

**必要属性**  
**类型:** `string`

要显示的链接卡片的标题。

### `href`

**必要属性**  
**类型:** `string`

与卡片交互时所链接到的 URL。

### `description`

**类型:** `string`

一个可选描述,显示在标题的下方。


================================================
FILE: docs/src/content/docs/zh-cn/components/steps.mdx
================================================
---
title: 步骤
description: 了解如何设计任务编号列表的样式,以在 Starlight 中创建分步指南。
---

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

要设置任务编号列表的样式以创建分步指南,请使用 `<Steps>` 组件。

import Preview from '~/components/component-preview.astro';

<Preview>

<Steps slot="preview">

1. 创建一个新的 Starlight 项目:

   <Tabs syncKey="pkg">

   <TabItem label="npm">

   ```sh
   npm create astro@latest -- --template starlight
   ```

   </TabItem>

   <TabItem label="pnpm">

   ```sh
   pnpm create astro --template starlight
   ```

   </TabItem>

   <TabItem label="Yarn">

   ```sh
   yarn create astro --template starlight
   ```

   </TabItem>

   </Tabs>

2. 编写你的第一个文档页面。

</Steps>

</Preview>

## 导入

```tsx
import { Steps } from '@astrojs/starlight/components';
```

## 用法

使用 `<Steps>` 组件来设置任务编号列表的样式。
这对于需要清楚地显示出有关每个步骤的、更复杂的分步指南来说,非常有用。

用 `<Steps>` 将标准的 Markdown 有序列表包裹起来。
所有常用的 Markdown 语法都适用于 `<Steps>`。

<Preview>

````mdx
import { Steps } from '@astrojs/starlight/components';

<Steps>

1. 将组件导入到 MDX 文件中:

   ```js
   import { Steps } from '@astrojs/starlight/components';
   ```

2. 用 `<Steps>` 将你的有序列表包裹起来。

</Steps>
````

<Fragment slot="markdoc">

````markdoc
{% steps %}

1. 将组件导入到 MDX 文件中:

   ```js
   import { Steps } from '@astrojs/starlight/components';
   ```

2. 用 `<Steps>` 将你的有序列表包裹起来。

{% /steps %}
````

</Fragment>

<Steps slot="preview">

1. 将组件导入到 MDX 文件中:

   ```js
   import { Steps } from '@astrojs/starlight/components';
   ```

2. 用 `<Steps>` 将你的有序列表包裹起来。

</Steps>

</Preview>

## `<Steps>` 的属性

**实现:** [`Steps.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Steps.astro)

`<Steps>` 组件不接受任何 props。


================================================
FILE: docs/src/content/docs/zh-cn/components/tabs.mdx
================================================
---
title: 选项卡
description: 了解如何在 Starlight 中创建选项卡式的界面以对等效信息进行分组。
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

要创建选项卡式界面,请使用 `<Tabs>` 和 `<TabItem>` 组件。
选项卡对于给等效信息进行分组非常有用,用户只需查看多个选项之一即可。

import Preview from '~/components/component-preview.astro';

<Preview>

<Tabs slot="preview">
	<TabItem label="恒星">天狼星,织女星,参宿四</TabItem>
	<TabItem label="卫星">木卫一,木卫二,木卫三</TabItem>
</Tabs>

</Preview>

## 导入

```tsx
import { Tabs, TabItem } from '@astrojs/starlight/components';
```

## 用法

使用 `<Tabs>` 和 `<TabItem>` 组件以显示选项卡式的界面。
每个 `<TabItem>` 必须有一个 [`label`](#label) 来展示给用户。

<Preview>

```mdx
import { Tabs, TabItem } from '@astrojs/starlight/components';

<Tabs>
	<TabItem label="恒星">天狼星,织女星,参宿四</TabItem>
	<TabItem label="卫星">木卫一,木卫二,木卫三</TabItem>
</Tabs>
```

<Fragment slot="markdoc">

```markdoc
{% tabs %}
{% tabitem label="恒星" %}
天狼星,织女星,参宿四
{% /tabitem %}

{% tabitem label="卫星" %}
木卫一,木卫二,木卫三
{% /tabitem %}
{% /tabs %}
```

</Fragment>

<Tabs slot="preview">
	<TabItem label="恒星">天狼星,织女星,参宿四</TabItem>
	<TabItem label="卫星">木卫一,木卫二,木卫三</TabItem>
</Tabs>

</Preview>

### 同步选项卡

通过添加 [`syncKey`](#synckey) 属性来保持多个选项卡组之间的同步。

页面上具有相同 `syncKey` 值的所有 `<Tabs>` 将显示相同的活动标签。
这允许你的读者只需选择一次(例如选择他们的操作系统或包管理器),就可以看到他们的选择在页面导航中保持一致。

要同步相关选项卡,请向每个 `<Tabs>` 组件添加相同的 `syncKey` 属性,并确保它们都使用相同的 `<TabItem>` labels 属性:

<Preview>

```mdx 'syncKey="星座"'
import { Tabs, TabItem } from '@astrojs/starlight/components';

_一些恒星:_

<Tabs syncKey="星座">
	<TabItem label="猎户座">参宿五,参宿七,参宿四</TabItem>
	<TabItem label="双子座">北河三,北河二 A,北河二 B</TabItem>
</Tabs>

_一些系外行星:_

<Tabs syncKey="星座">
	<TabItem label="猎户座">HD 34445 b,格利泽 179b,Wasp-82 b</TabItem>
	<TabItem label="双子座">北河三 b,HAT-P-24b,HD 50554 b</TabItem>
</Tabs>
```

<Fragment slot="markdoc">

```markdoc 'syncKey="星座"'
_一些恒星:_

{% tabs syncKey="星座" %}
{% tabitem label="猎户座" %}
参宿五,参宿七,参宿四
{% /tabitem %}

{% tabitem label="双子座" %}
北河三,北河二 A,北河二 B
{% /tabitem %}
{% /tabs %}

_一些系外行星:_

{% tabs syncKey="星座" %}
{% tabitem label="猎户座" %}
HD 34445 b,格利泽 179b,Wasp-82 b
{% /tabitem %}

{% tabitem label="双子座" %}
北河三 b,HAT-P-24b,HD 50554 b
{% /tabitem %}
{% /tabs %}
```

</Fragment>

<Fragment slot="preview">

_一些恒星:_

<Tabs syncKey="星座">
	<TabItem label="猎户座">参宿五,参宿七,参宿四</TabItem>
	<TabItem label="双子座">北河三,北河二 A,北河二 B</TabItem>
</Tabs>

_一些系外行星:_

<Tabs syncKey="星座">
	<TabItem label="猎户座">HD 34445 b,格利泽 179b,Wasp-82 b</TabItem>
	<TabItem label="双子座">北河三 b,HAT-P-24b,HD 50554 b</TabItem>
</Tabs>

</Fragment>

</Preview>

### 为选项卡添加图标

在选项卡组件中,添加 [`icon`](#icon) 属性并将其设置为 [Starlight 内置图标之一](/zh-cn/reference/icons/#所有图标) 来为选项卡添加图标。

<Preview>

```mdx /icon="\w+"/
import { Tabs, TabItem } from '@astrojs/starlight/components';

<Tabs>
	<TabItem label="恒星" icon="star">
		天狼星,织女星,参宿四
	</TabItem>
	<TabItem label="卫星" icon="moon">
		木卫一,木卫二,木卫三
	</TabItem>
</Tabs>
```

<Fragment slot="markdoc">

```markdoc /icon="\w+"/
{% tabs %}
{% tabitem label="恒星" icon="star" %}
天狼星,织女星,参宿四
{% /tabitem %}

{% tabitem label="卫星" icon="moon" %}
木卫一,木卫二,木卫三
{% /tabitem %}
{% /tabs %}
```

</Fragment>

<Tabs slot="preview">
	<TabItem label="恒星" icon="star">
		天狼星,织女星,参宿四
	</TabItem>
	<TabItem label="卫星" icon="moon">
		木卫一,木卫二,木卫三
	</TabItem>
</Tabs>

</Preview>

## `<Tabs>` 的属性

**实现:** [`Tabs.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/Tabs.astro)

`<Tabs>` 组件将多个 `<TabItem>` 组件组合在一起并接受以下属性:

### `syncKey`

**类型:** `string`

一个用于使多个选项卡组在多个页面之间保持同步的键。

## `<TabItem>` 的属性

**实现:** [`TabItem.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/user-components/TabItem.astro)

一组选项卡(tabs)由选项卡项(tab items)组成,每个选项卡项都具有以下属性:

### `label`

**必要属性**  
**类型:** `string`

选项卡项必须包含一个 `label` 属性,该属性决定了将在选项卡项中显示的文本。

### `icon`

**类型:** `string`

每个选项卡项都可以包含一个 `icon` 属性,该属性设置为 [Starlight 的内置图标之一](/zh-cn/reference/icons/#所有图标) 的名称,以在标签旁边显示图标。


================================================
FILE: docs/src/content/docs/zh-cn/components/using-components.mdx
================================================
---
title: 使用组件
description: 通过 Starlight 使用 MDX 和 Markdoc 中的组件
sidebar:
  order: 1
---

组件能让你更轻松、更连贯地复用部分 UI 或者样式。
示例可能包括链接卡片或嵌入 YouTube。
Starlight 支持使用 [MDX](https://mdxjs.com/) 和 [Markdoc](https://markdoc.dev/) 文件中的组件,并提供了一些常用组件供你使用。

[在 Astro 文档中了解有关构建组件的更多信息](https://docs.astro.build/zh-cn/basics/astro-components/)。

## 在 MDX 中使用组件

你可以通过将组件导入 MDX 文件然后将其渲染为 JSX 标签来使用该组件。
这些组件看起来像 HTML 标签,但是以 `import` 语句中的大写字母开头,并与之名称相匹配:

```mdx
---
# src/content/docs/example.mdx
title: 欢迎来到我的文档
---

import { Icon } from '@astrojs/starlight/components';
import CustomCard from '../../components/CustomCard.astro';

<Icon name="open-book" />

<CustomCard>组件还可以包含 **嵌套内容**。</CustomCard>
```

由于 Starlight 由 Astro 提供支持,因此你可以在 MDX 文件中添加由 [受支持的 UI 框架(React、Preact、Svelte、Vue、Solid 和 Alpine)](https://docs.astro.build/zh-cn/guides/framework-components/) 构建的组件。
在 Astro 文档中了解有关 [在 MDX 中使用组件](https://docs.astro.build/zh-cn/guides/integrations-guide/mdx/#在-mdx-中使用组件) 的更多信息。

## 在 Markdoc 中使用组件

跟随我们的 [Markdoc 设置指南](/zh-cn/guides/authoring-content/#markdoc) 来添加支持以在 Markdoc 中创作内容。

使用 Starlight 的 Markdoc 预设,你可以将 Starlight 的内置组件与 Markdoc 的 `{% %}` 标签语法结合使用。
与 MDX 不同的是,Markdoc 中的组件不需要导入。
以下示例为,在 Markdoc 文件中渲染 Starlight 的 [卡片组件](/zh-cn/components/cards/):

```markdoc
---
# src/content/docs/example.mdoc
title: 欢迎来到我的文档
---

{% card title="星星" icon="star" %}
天狼星, 织女星, 参宿四
{% /card %}
```

有关如何使用 Markdoc 文件中的组件的更多信息,请参阅 [Astro Markdoc 集成文档](https://docs.astro.build/zh-cn/guides/integrations-guide/markdoc/#渲染组件)。

## 内置组件

Starlight 为常见文档用例提供内置组件。
这些组件可从 MDX 文件中的 `@astrojs/starlight/components` 包以及 Markdoc 文件中的 [Starlight Markdoc 预设](/zh-cn/guides/authoring-content/#markdoc) 中获取。

请参阅侧边栏以获取可用组件的列表以及使用方式。

## 和 Starlight 样式的兼容性

Starlight 将默认样式应用于 Markdown 内容,例如,在元素之间添加边距。
如果这些样式与你的组件外观存在冲突,请在组件上设置 `not-content` 类来禁用它们。

```astro 'class="not-content"'
---
// src/components/Example.astro
---

<div class="not-content">
	<p>不受 Starlight 默认内容样式的影响。</p>
</div>
```

## 组件 props

使用 `astro/types` 中的 [`ComponentProps`](https://docs.astro.build/zh-cn/guides/typescript/#componentprops-类型) 类型来引用组件接受的 `Props`,即使它们不是由组件本身导出的。
这在包装或扩展现有组件时非常有用。

以下示例为,使用 `ComponentProps` 获取 Starlight 内置 `Badge` 组件接受的 props 类型:

```astro
---
// src/components/Example.astro
import type { ComponentProps } from 'astro/types';
import { Badge } from '@astrojs/starlight/components';

type BadgeProps = ComponentProps<typeof Badge>;
---
```


================================================
FILE: docs/src/content/docs/zh-cn/environmental-impact.md
================================================
---
title: 环保文档
description: 了解 Starlight 如何帮助你构建更环保的文档站点并减少碳足迹。
---

网络行业对气候影响的估计范围从[2%][sf]到[全球碳排放量的4%][bbc],大致相当于航空业的排放量。
计算网站生态影响的因素很多,但本指南包含了一些减少文档站点环境足迹的技巧。

好消息是,选择 Starlight 是一个很好的开始。
根据网站碳计算器的数据,本站点[比 98% 的网页更环保][sl-carbon],每个页面访问产生 0.01g 的 CO₂。

## 页面大小

网页传输的数据越多,它所需的能源资源就越多。
根据[来自 HTTP 存档的数据][http],2023 年 4 月,中位数网页需要用户下载超过 2,000 KB。

Starlight 构建的页面尽可能轻量。
例如,在第一次访问时,用户将下载少于 50 KB 的压缩数据,仅为 HTTP 存档中位数的 2.5%。
通过良好的缓存策略,后续导航可以下载少至 10 KB。

### 图片

虽然 Starlight 提供了一个很好的基线,但是你添加到文档页面的图片可能会快速增加页面的大小。
Starlight 使用 Astro 的 [优化的资源支持][assets] 来优化 Markdown 和 MDX 文件中的本地图片。

### UI 组件

使用 React 或 Vue 等 UI 框架构建的组件可以轻松地向页面添加大量 JavaScript。
因为 Starlight 是基于 Astro 构建的,所以这样的组件默认情况下不会加载**任何客户端 JavaScript**,这要归功于 [Astro 岛屿][islands]。

### 缓存

缓存用于控制浏览器存储和重用已下载数据的时间。
良好的缓存策略确保用户在内容更改时尽快获得新内容,但也避免了在内容未更改时反复下载相同的内容。

最常见的配置缓存的方法是使用 [`Cache-Control` HTTP headers][cache]。
使用 Starlight 时,你可以为 `/_astro/` 目录中的所有内容设置长时间缓存。
该目录包含可以安全永久缓存的 CSS、JavaScript 和其他捆绑的资源,从而减少不必要的下载:

```
Cache-Control: public, max-age=604800, immutable
```

如何配置缓存取决于你的 Web 主机。例如,Vercel 会自动为你应用这种缓存策略,而 Netlify 可以通过在项目中添加 `public/_headers` 文件来[为 Netlify 设置自定义 headers][ntl-headers]:

```
/_astro/*
  Cache-Control: public
  Cache-Control: max-age=604800
  Cache-Control: immutable
```

[cache]: https://csswizardry.com/2019/03/cache-control-for-civilians/
[ntl-headers]: https://docs.netlify.com/routing/headers/

## 功耗

网页的制作方式会影响其在用户设备上的运行功率。
通过使用最少的 JavaScript,Starlight 减少了用户手机、平板电脑或电脑加载和呈现网页所需的处理能力。

当添加诸如分析跟踪脚本或 JavaScript 重型内容(如视频嵌入)之类的功能时,请注意这些功能会增加页面的功耗。
如果你需要分析,请考虑选择像 [Cabin][cabin]、[Fathom][fathom] 或 [Plausible][plausible] 这样的轻量级选项。
等待[用户交互时加载视频][lazy-video]可以改善 YouTube 和 Vimeo 视频等嵌入。
[`astro-embed`][embed] 等包可以帮助常见的服务。

:::tip[你知道吗?]
解析和编译 JavaScript 是浏览器必须执行的最昂贵的任务之一。
与渲染相同大小的 JPEG 图像相比,[JavaScript 处理所需的时间可能超过 JPEG 的 30 倍][cost-of-js]。
:::

[cabin]: https://withcabin.com/
[fathom]: https://usefathom.com/
[plausible]: https://plausible.io/
[lazy-video]: https://web.dev/iframe-lazy-loading/
[embed]: https://www.npmjs.com/package/astro-embed
[cost-of-js]: https://medium.com/dev-channel/the-cost-of-javascript-84009f51e99e

## 托管

网页托管在哪里会对你的文档站点的环保程度产生很大的影响。
数据中心和服务器农场可能会对环境产生很大的影响,包括高耗电量和大量使用水资源。

选择使用可再生能源的主机将意味着你的站点的碳排放量更低。[绿色网络目录][gwb]是一个可以帮助你找到主机公司的工具。

[gwb]: https://www.thegreenwebfoundation.org/directory/

## 比较

好奇和其他文档框架相比如何?
下面使用 [Website Carbon Calculator][wcc] 的测试比较了使用不同工具构建的类似页面。

| 框架                        | 每页访问量产生的 CO₂ | 评级 |
| --------------------------- | -------------------- | :--: |
| [Starlight][sl-carbon]      | 0.01g                |  A+  |
| [Read the Docs][rtd-carbon] | 0.07g                |  A+  |
| [Sphinx][sx-carbon]         | 0.07g                |  A+  |
| [VitePress][vp-carbon]      | 0.07g                |  A+  |
| [Docus][dc-carbon]          | 0.10g                |  A   |
| [docsify][dy-carbon]        | 0.11g                |  A   |
| [mdBook][md-carbon]         | 0.13g                |  A   |
| [MkDocs][mk-carbon]         | 0.15g                |  A   |
| [Fumadocs][fs-carbon]       | 0.16g                |  A   |
| [Nextra][nx-carbon]         | 0.16g                |  A   |
| [Docusaurus][ds-carbon]     | 0.25g                |  B   |
| [Mintlify][mt-carbon]       | 0.99g                |  F   |
| [GitBook][gb-carbon]        | 1.19g                |  F   |

<small>数据收集于 2025 年 4 月 12 日。点击链接查看最新数据。</small>

[sl-carbon]: https://www.websitecarbon.com/website/starlight-astro-build-getting-started/
[vp-carbon]: https://www.websitecarbon.com/website/vitepress-dev-guide-what-is-vitepress/
[dc-carbon]: https://www.websitecarbon.com/website/docus-dev-introduction-getting-started/
[sx-carbon]: https://www.websitecarbon.com/website/sphinx-doc-org-en-master-usage-quickstart-html/
[mk-carbon]: https://www.websitecarbon.com/website/mkdocs-org-getting-started/
[md-carbon]: https://www.websitecarbon.com/website/rust-lang-github-io-mdbook/
[nx-carbon]: https://www.websitecarbon.com/website/nextra-site-docs-docs-theme-start/
[fs-carbon]: https://www.websitecarbon.com/website/fumadocs-vercel-app-docs-ui/
[dy-carbon]: https://www.websitecarbon.com/website/docsify-js-org/
[ds-carbon]: https://www.websitecarbon.com/website/docusaurus-io-docs/
[rtd-carbon]: https://www.websitecarbon.com/website/docs-readthedocs-io-en-stable-index-html/
[gb-carbon]: https://www.websitecarbon.com/website/docs-gitbook-com/
[mt-carbon]: https://www.websitecarbon.com/website/mintlify-com-docs-quickstart/

## 更多资源

### 工具

- [Website Carbon Calculator][wcc]
- [GreenFrame](https://greenframe.io/)
- [Ecograder](https://ecograder.com/)
- [WebPageTest Carbon Control](https://www.webpagetest.org/carbon-control/)
- [Ecoping](https://ecoping.earth/)

### 文章和演讲

- [“Building a greener web”](https://youtu.be/EfPoOt7T5lg),Michelle Barker 的演讲
- [“Sustainable Web Development Strategies Within An Organization”](https://www.smashingmagazine.com/2022/10/sustainable-web-development-strategies-organization/),Michelle Barker 的文章
- [“A sustainable web for everyone”](https://2021.stateofthebrowser.com/speakers/tom-greenwood/),Tom Greenwood 的演讲
- [“How Web Content Can Affect Power Usage”](https://webkit.org/blog/8970/how-web-content-can-affect-power-usage/),Benjamin Poulain 和 Simon Fraser 的文章

[sf]: https://www.sciencefocus.com/science/what-is-the-carbon-footprint-of-the-internet/
[bbc]: https://www.bbc.com/future/article/20200305-why-your-internet-habits-are-not-as-clean-as-you-think
[http]: https://httparchive.org/reports/state-of-the-web
[assets]: https://docs.astro.build/zh-cn/guides/images/
[islands]: https://docs.astro.build/zh-cn/concepts/islands/
[wcc]: https://www.websitecarbon.com/


================================================
FILE: docs/src/content/docs/zh-cn/getting-started.mdx
================================================
---
title: 开始使用
description: 了解如何使用 Astro 的 Starlight 开始构建下一个文档站点。
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

Starlight 是一个基于 [Astro](https://astro.build) 框架构建的全功能文档主题。
这个指南将帮助你开始一个新项目。
查看[手动配置](/zh-cn/manual-setup/)以将 Starlight 添加到现有的 Astro 项目中。

## 快速入门

### 创建一个新项目

在你的终端中运行以下命令来创建一个新的 Astro + Starlight 项目:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight
```

</TabItem>
</Tabs>

这将创建一个新的[项目目录](/zh-cn/guides/project-structure/),其中包含你网站所需的所有文件和配置。

:::tip[查看实际效果]
在浏览器中尝试 Starlight:
[在 StackBlitz 上打开模板](https://stackblitz.com/github/withastro/starlight/tree/main/examples/basics)。
:::

### 启动开发服务器

在本地工作时,[Astro 的开发服务器](https://docs.astro.build/zh-cn/reference/cli-reference/#astro-dev)使你能预览你的工作,并在你进行更改时自动刷新你的浏览器。

在你的项目目录中,运行以下命令来启动开发服务器:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm run dev
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dev
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dev
```

</TabItem>
</Tabs>

这将在你的终端上记录一个包含本地预览网址的消息。
打开这个网址开始浏览你的网站。

### 添加内容

Starlight 已经准备好让你添加新内容或导入你现有的文件!

通过在 `src/content/docs/` 目录中创建 Markdown 文件来为你的网站添加新页面。

在 [“页面”](/zh-cn/guides/pages/) 指南中了解有关基于文件的路由和对 MDX 和 Markdoc 文件的支持的更多信息。

### 下一步

- **配置:** 在[自定义 Starlight](/zh-cn/guides/customization/)中了解常见选项。
- **导航:** 使用[侧边栏导航](/zh-cn/guides/sidebar/)指南设置你的侧边栏。
- **组件:** 在[组件](/zh-cn/components/using-components/)指南中发现内置的卡片、标签页等更多内容。
- **部署:** 使用 Astro 文档中的[部署你的 Astro 站点](https://docs.astro.build/zh-cn/guides/deploy/)指南发布你的站点。

## 更新 Starlight

:::tip[提示]
由于 Starlight 是 beta 软件,所以会经常更新和改进。

请务必定期更新 Starlight!
:::

Starlight 是一个 Astro 集成。你可以通过在终端中运行以下命令来更新它和其他 Astro 软件包:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npx @astrojs/upgrade
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm dlx @astrojs/upgrade
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn dlx @astrojs/upgrade
```

</TabItem>
</Tabs>

查阅 [Starlight 更新日志](https://github.com/withastro/starlight/blob/main/packages/starlight/CHANGELOG.md)中每个版本的变更列表。

## Starlight 故障排除

本站点的参考部分提供了 Starlight [项目配置](/zh-cn/reference/configuration/)和[单个页面 frontmatter 配置](/zh-cn/reference/frontmatter/)信息。使用这些页面来确保你的 Starlight 网站已正确配置和运行。
请参阅侧边栏中的指南列表,以获取有关添加内容和自定义 Starlight 网站的帮助。

如果你在这些文档中找不到答案,请访问[完整的 Astro 文档](https://docs.astro.build/zh-cn/) 以获取完整的 Astro 文档。
你的问题可能是通过了解 Starlight 主题下 Astro 的工作原理来解决的。

你也可以检查任何已知的 [GitHub 上的 Starlight issues](https://github.com/withastro/starlight/issues),并在 [Astro Discord](https://astro.build/chat/) 上从我们活跃的、友好的社区中获得帮助!在我们的 `#support` 论坛中发布带有 “starlight” 标签的问题,或者访问我们专门的 `#starlight` 频道来讨论当前的开发和更多内容!


================================================
FILE: docs/src/content/docs/zh-cn/guides/authoring-content.mdx
================================================
---
title: 在 Markdown 中创作内容
description: Starlight 支持的 Markdown 语法概述
---

Starlight 支持在 `.md` 文件中使用完整的 [Markdown](https://daringfireball.net/projects/markdown/) 语法,以及使用 [YAML](https://dev.to/paulasantamaria/introduction-to-yaml-125f) 定义metadata 元数据,例如标题和描述。

如果使用这些文件格式,请务必检查 [MDX 文档](https://mdxjs.com/docs/what-is-mdx/#markdown) 或 [Markdoc 文档](https://markdoc.dev/docs/syntax),因为 Markdown 的支持和用法可能会有所不同。

## Frontmatter

你可以通过设置 frontmatter 中的值来自定义 Starlight 里每个页面。
Frontmatter 是你的文件顶部在 `---` 中间的部分。

```md title="src/content/docs/example.md"
---
title: 我的页面标题
---

页面内容在第二个 `---` 后面。
```

每个页面都必须包含一个 `title`。
查看 [frontmatter 参考](/zh-cn/reference/frontmatter/) 了解所有可用字段以及如何添加自定义字段。

## 内联样式

文本可以是**粗体**,_斜体_,或~~删除线~~。

```md
文本可以是**粗体**,_斜体_,或~~删除线~~。
```

你可以 [链接到另一个页面](/zh-cn/getting-started/)。

```md
你可以 [链接到另一个页面](/zh-cn/getting-started/)。
```

你可以使用反引号高亮 `内联代码`。

```md
你可以使用反引号高亮 `内联代码`。
```

## 图片

Starlight 中的图片使用 [Astro 的内置优化资源支持](https://docs.astro.build/zh-cn/guides/images/)。

Markdown 和 MDX 支持用于显示图片的 Markdown 语法,其中包括屏幕阅读器和辅助技术的 alt-text。

![一个星球和星星的插图,上面写着“astro”](https://raw.githubusercontent.com/withastro/docs/main/public/default-og-image.png)

```md
![一个星球和星星的插图,上面写着“astro”](https://raw.githubusercontent.com/withastro/docs/main/public/default-og-image.png)
```

对于在项目中本地存储的图片,也支持图片的相对路径。

```md
// src/content/docs/page-1.md

![A rocketship in space](../../assets/images/rocket.svg)
```

## 标题

你可以使用标题来组织内容。Markdown 中的标题由行首的 `#` 数量来表示。

### 如何在 Starlight 中组织页面内容

Starlight 配置为自动使用页面标题作为一级标题,并将在每个页面的目录中包含一个“概述”标题。我们建议每个页面都从常规段落文本内容开始,并从 `<h2>` 开始使用页面标题:

```md
---
title: Markdown 指南
description: 如何在 Starlight 中使用 Markdown
---

本页面描述了如何在 Starlight 中使用 Markdown。

## 内联样式

## 标题
```

### 自动生成标题锚点链接

使用 Markdown 中的标题将自动为你提供锚点链接,以便你可以直接链接到页面的某些部分:

```md
---
title: 我的页面内容
description: 如何使用 Starlight 内置的锚点链接
---

## 介绍

我可以链接到同一页下面的[结论](#结论)。

## 结论

`https://my-site.com/page1/#introduction` 直接导航到我的介绍。
```

二级标题 (`<h2>`) 和 三级标题 (`<h3>`) 将自动出现在页面目录中。

在 [Astro 文档](https://docs.astro.build/zh-cn/guides/markdown-content/#标题-id)中了解 Astro 是如何处理标题 `id` 的。

## 旁白

旁白(也称为“警告”或“标注”)对于在页面的主要内容旁边显示辅助信息很有用。

Starlight 提供了一个自定义的 Markdown 语法来渲染旁白。旁白块使用一对三个冒号 `:::` 来包裹你的内容,并且可以是 `note`,`tip`,`caution` 或 `danger` 类型。

你可以在旁白中嵌套任何其他 Markdown 内容类型,但旁白最适合用于简短而简洁的内容块。

### Note 旁白

:::note
Starlight 是一个使用 [Astro](https://astro.build/) 构建的文档网站工具包。 你可以使用此命令开始:

```sh
npm create astro@latest -- --template starlight
```

:::

````md
:::note
Starlight 是一个使用 [Astro](https://astro.build/) 构建的文档网站工具包。 你可以使用此命令开始:

```sh
npm create astro@latest -- --template starlight
```

:::
````

### 自定义旁白标题

你可以在旁白类型后面的方括号中指定旁白的自定义标题,例如 `:::tip[你知道吗?]`。

:::tip[你知道吗?]
Astro 帮助你使用 [“群岛架构”](https://docs.astro.build/zh-cn/concepts/islands/) 构建更快的网站。
:::

```md
:::tip[你知道吗?]
Astro 帮助你使用 [“群岛架构”](https://docs.astro.build/zh-cn/concepts/islands/) 构建更快的网站。
:::
```

### 更多旁白类型

Caution 和 danger 旁白有助于吸引用户注意可能绊倒他们的细节。 如果你发现自己经常使用这些,这也可能表明你正在记录的内容可以从重新设计中受益。

:::caution
如果你不确定是否想要一个很棒的文档网站,请在使用 [Starlight](/zh-cn/) 之前三思。
:::

:::danger
借助有用的 Starlight 功能,你的用户可能会提高工作效率,并发现你的产品更易于使用。

- 清晰的导航
- 用户可配置的颜色主题
- [i18n 支持](/zh-cn/guides/i18n/)

:::

```md
:::caution
如果你不确定是否想要一个很棒的文档网站,请在使用 [Starlight](/zh-cn/) 之前三思。
:::

:::danger
借助有用的 Starlight 功能,你的用户可能会提高工作效率,并发现你的产品更易于使用。

- 清晰的导航
- 用户可配置的颜色主题
- [i18n 支持](/zh-cn/guides/i18n/)

:::
```

## 块引用

> 这是块引用,通常在引用其他人或文档时使用。
>
> 块引用以每行开头的 `>` 表示。

```md
> 这是块引用,通常在引用其他人或文档时使用。
>
> 块引用以每行开头的 `>` 表示。
```

## 代码块

代码块由三个反引号 <code>```</code> 开始和结束。你可以在开头的反引号后指定代码块的编程语言。

```js
// 带有语法高亮的 JavaScript 代码。
var fun = function lang(l) {
	dateformat.i18n = require('./lang/' + l);
	return true;
};
```

````md
```js
// 带有语法高亮的 JavaScript 代码。
var fun = function lang(l) {
	dateformat.i18n = require('./lang/' + l);
	return true;
};
```
````

### Expressive Code 功能

Starlight 使用 [Expressive Code](https://expressive-code.com/) 来扩展代码块的格式化功能。
Expressive Code 的文本标记和窗口外框插件是默认启用的。
可以使用 Starlight 的 [`expressiveCode` 配置选项](/zh-cn/reference/configuration/#expressivecode) 来配置代码块的渲染。

#### 文本标记

你可以通过在代码块的起始行上使用 [Expressive Code 文本标记 (text markers)](https://expressive-code.com/key-features/text-markers/) 在代码块里突出显示特定行或代码块的一部分。
使用大括号 (`{ }`) 来突出显示整行,使用引号来突出显示文本字符串。

有三种突出显示样式:中性用于突出显示代码,绿色用于表示插入的代码,红色用于表示删除的代码。
字符串和整行都可以使用默认的标记,也可以与 `ins=` 和 `del=` 结合使用产生所需的突出显示效果。

Expressive Code 提供了几种自定义你的代码示例视觉外观的选项。
其中许多可以组合使用,以获得极具说明性的代码示例。
请探索 [Expressive Code 文档](https://expressive-code.com/key-features/text-markers/#configuration) 以了解众多可用的设置项。
下面显示了一些最常见的示例:

- [使用 `{ }` 标记标出整行和行范围](https://expressive-code.com/key-features/text-markers/#marking-full-lines--line-ranges):

  ```js {2-3}
  function demo() {
  	// 这一行 (#2) 以及下一行被高亮显示
  	return '这是本代码段的第 3 行';
  }
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```js {2-3}
  function demo() {
  	// 这一行 (#2) 以及下一行被高亮显示
  	return '这是本代码段的第 3 行';
  }
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````md
  ```js {% meta="{2-3}" %}
  function demo() {
  	// 这一行 (#2) 以及下一行被高亮显示
  	return '这是本代码段的第 3 行';
  }
  ```
  ````

  </TabItem>

  </Tabs>

- [使用 `" "` 标记或正则表达式标出文本字符串](https://expressive-code.com/key-features/text-markers/#marking-individual-text-inside-lines):

  ```js "单个词组" /甚.*表达式/
  // 单个词组也能被高亮显示
  function demo() {
  	return '甚至支持使用正则表达式';
  }
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```js "单个词组" /甚.*表达式/
  // 单个词组也能被高亮显示
  function demo() {
  	return '甚至支持使用正则表达式';
  }
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```js {% meta="'单个词组' /甚.*表达式/" %}
  // 单个词组也能被高亮显示
  function demo() {
  	return '甚至支持使用正则表达式';
  }
  ```
  ````

  </TabItem>

  </Tabs>

- [使用 `ins` 或 `del` 来标记行或文本为插入或删除](https://expressive-code.com/key-features/text-markers/#selecting-inline-marker-types-mark-ins-del):

  ```js "return true;" ins="插入" del="删除"
  function demo() {
  	console.log('这是插入以及删除类型的标记');
  	// 返回语句使用默认标记类型
  	return true;
  }
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```js "return true;" ins="插入" del="删除"
  function demo() {
  	console.log('这是插入以及删除类型的标记');
  	// 返回语句使用默认标记类型
  	return true;
  }
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```js {% meta="'return true;' ins='插入' del='删除'" %}
  function demo() {
  	console.log('这是插入以及删除类型的标记');
  	// 返回语句使用默认标记类型
  	return true;
  }
  ```
  ````

  </TabItem>

  </Tabs>

- [混合语法高亮和类 `diff` 语法](https://expressive-code.com/key-features/text-markers/#combining-syntax-highlighting-with-diff-like-syntax):

  ```diff lang="js"
    function thisIsJavaScript() {
      // 这整个代码块都会被作为 JavaScript 高亮
      // 而且我们还可以给它添加 diff 标记!
  -   console.log('旧的不去')
  +   console.log('新的不来')
    }
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```diff lang="js"
    function thisIsJavaScript() {
      // 这整个代码块都会被作为 JavaScript 高亮
      // 而且我们还可以给它添加 diff 标记!
  -   console.log('旧的不去')
  +   console.log('新的不来')
    }
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```diff {% meta="lang='js'" %}
    function thisIsJavaScript() {
      // 这整个代码块都会被作为 JavaScript 高亮
      // 而且我们还可以给它添加 diff 标记!
  -   console.log('旧的不去')
  +   console.log('新的不来')
    }
  ```
  ````

  </TabItem>

  </Tabs>

#### 边框和标题

代码块可以在类似窗口的框架中呈现。
默认情况下 shell 脚本语言(例如 `bash` 或 `sh`)会使用一个看起来像终端窗口的边框。
其他语言在提供了标题的情况下会在一个看起来像代码编辑器的边框中显示。

一个代码块的可选标题可以通过在代码块的开头反引号后面添加一个 `title="..."` 属性来设置,或者通过在代码的前几行中添加一个文件名注释来设置。

- [通过注释添加一个文件名标签](https://expressive-code.com/key-features/frames/#code-editor-frames)

  ```js
  // my-test-file.js
  console.log('Hello World!');
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```js
  // my-test-file.js
  console.log('Hello World!');
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````md
  ```js
  // my-test-file.js
  console.log('Hello World!');
  ```
  ````

  </TabItem>

  </Tabs>

- [给终端窗口添加一个标题](https://expressive-code.com/key-features/frames/#terminal-frames)

  ```bash title="安装依赖…"
  npm install
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```bash title="安装依赖…"
  npm install
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```bash {% title="安装依赖…" %}
  npm install
  ```
  ````

  </TabItem>

  </Tabs>

- [使用 `frame="none"` 禁用边框](https://expressive-code.com/key-features/frames/#overriding-frame-types)

  ```bash frame="none"
  echo "这个代码块即使使用了 bash 语言也不会被显示成终端窗口"
  ```

  <Tabs syncKey="content-type">

  <TabItem label="Markdown/MDX">

  ````md
  ```bash frame="none"
  echo "这个代码块即使使用了 bash 语言也不会被显示成终端窗口"
  ```
  ````

  </TabItem>

  <TabItem label="Markdoc">

  ````markdoc
  ```bash {% frame="none" %}
  echo "这个代码块即使使用了 bash 语言也不会被显示成终端窗口"
  ```
  ````

  </TabItem>

  </Tabs>

## 详细信息

详细信息(也称为“手风琴(accordion)”)用于隐藏不立即相关的内容。用户可以点击一个简短的摘要来展开并查看完整内容。

在你的 Markdown 内容中使用标准的 HTML [`<details>`](https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/details) 和 [`<summary>`](https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/summary) 元素来创建一个手风琴小组件。

你可以在 `<details>` 元素内嵌套任何其他 Markdown 语法。

<details>
<summary>何时何地可以最清楚地看到仙女座?</summary>

在 11 月份的夜空中,[仙女座](https://zh.wikipedia.org/wiki/仙女座) 在 `+90°` 到 `-40°` 的纬度范围内最为明显。

</details>

```md
<details>
<summary>何时何地可以最清楚地看到仙女座?</summary>

在 11 月份的夜空中,[仙女座](https://zh.wikipedia.org/wiki/仙女座) 在 `+90°` 到 `-40°` 的纬度范围内最为明显。

</details>
```

## 其它通用 Markdown 语法

Starlight 支持所有其他 Markdown 语法,例如列表和表格。 请参阅 [Markdown 指南的 Markdown 速查表](https://www.markdownguide.org/cheat-sheet/) 以快速了解所有 Markdown 语法元素。

## 高级 Markdown 和 MDX 配置

Starlight 使用 Astro 的 Markdown 和 MDX 渲染器,该渲染器构建在 remark 和 rehype 之上。 你可以通过在 Astro 配置文件中添加 `remarkPlugins` 或 `rehypePlugins` 来添加对自定义语法和行为的支持。 请参阅 Astro 文档中的 [“Markdown 插件”](https://docs.astro.build/zh-cn/guides/markdown-content/#markdown-插件) 以了解更多信息。

## Markdoc

Starlight 支持使用实验性 [Astro Markdoc 集成](https://docs.astro.build/zh-cn/guides/integrations-guide/markdoc/) 和 Starlight Markdoc 预设在 Markdoc 中创作内容。

### 使用 Markdoc 创建新项目

使用 Markdoc 的预配置 `create astro` 来启动一个新的 Starlight 项目:

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight/markdoc
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight/markdoc
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight/markdoc
```

</TabItem>
</Tabs>

### 添加 Markdoc 到现有项目

如果你已有一个 Starlight 网站并想要添加 Markdoc,请按照以下步骤操作。

<Steps>

1.  添加 Astro 的 Markdoc 集成:

    <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npx astro add markdoc
    ```

    </TabItem>

    <TabItem label="pnpm">

    ```sh
    pnpm astro add markdoc
    ```

    </TabItem>

    <TabItem label="Yarn">

    ```sh
    yarn astro add markdoc
    ```

    </TabItem>

    </Tabs>

2.  安装 Starlight Markdoc 预设:

    <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npm install @astrojs/starlight-markdoc
    ```

    </TabItem>

    <TabItem label="pnpm">

    ```sh
    pnpm add @astrojs/starlight-markdoc
    ```

    </TabItem>

    <TabItem label="Yarn">

    ```sh
    yarn add @astrojs/starlight-markdoc
    ```

    </TabItem>

    </Tabs>

3.  在 `markdoc.config.mjs` 创建一个 Markdoc 配置文件并使用 Starlight Markdoc 预设:

    ```js
    import { defineMarkdocConfig } from '@astrojs/markdoc/config';
    import starlightMarkdoc from '@astrojs/starlight-markdoc';

    export default defineMarkdocConfig({
    	extends: [starlightMarkdoc()],
    });
    ```

</Steps>

要了解有关 Markdoc 语法和功能的更多信息,请参阅 [Markdoc 文档](https://markdoc.dev/docs/syntax) 或 [Astro Markdoc 集成指南](https://docs.astro.build/zh-cn/guides/integrations-guide/markdoc/)。

### 配置 Markdoc 预设

`starlightMarkdoc()` 预设接受以下配置选项:

#### `headingLinks`

**类型:** `boolean`  
**默认值:** `true`

控制是否使用可点击的锚链接渲染标题。
等同于适用于 Markdown 和 MDX 文件的 [`markdown.headingLinks`](/zh-cn/reference/configuration/#markdown) 选项。

```js "headingLinks: false"
export default defineMarkdocConfig({
	// 禁用默认的标题锚点链接支持
	extends: [starlightMarkdoc({ headingLinks: false })],
});
```


================================================
FILE: docs/src/content/docs/zh-cn/guides/css-and-tailwind.mdx
================================================
---
title: CSS & 样式
description: 了解如何使用自定义 CSS 设置你的 Starlight 网站的样式或与 Tailwind CSS 集成。
---

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

你可以使用自定义 CSS 设置你的 Starlight 网站的样式或者使用 Starlight Tailwind 插件。

有一种快速的方法可以更改你的网站的默认样式,请查看 [社区主题](/zh-cn/resources/themes/)。

## 自定义 CSS 样式

通过提供额外的 CSS 文件来修改或扩展 Starlight 的默认样式,从而自定义应用于 Starlight 网站的样式。

<Steps>

1. 在 `src/` 目录下添加一个 CSS 文件。
   例如,你可以设置一个更宽的默认列宽和更大的页面标题文本大小:

   ```css
   /* src/styles/custom.css */
   :root {
   	--sl-content-width: 50rem;
   	--sl-text-5xl: 3.5rem;
   }
   ```

2. 在 `astro.config.mjs` 中的 `customCss` 数组中添加你的 CSS 文件的路径:

   ```diff lang="js"
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Docs With Custom CSS',
   			customCss: [
   +				// 你的自定义 CSS 文件的相对路径
   +				'./src/styles/custom.css',
   			],
   		}),
   	],
   });
   ```

</Steps>

你可以在[ GitHub 上的 `props.css` 文件](https://github.com/withastro/starlight/blob/main/packages/starlight/style/props.css) 中查看 Starlight 使用的所有 CSS 自定义属性,你可以设置这些属性来自定义你的网站。

## Tailwind CSS

Astro 项目中的 Tailwind CSS 支持由 [Astro Tailwind 集成](https://docs.astro.build/zh-cn/guides/integrations-guide/tailwind/) 提供。
Starlight 提供了一个补充的 Tailwind 插件,以帮助配置 Tailwind 以与 Starlight 的样式兼容。

Starlight Tailwind 插件应用了以下配置:

- 配置 Tailwind 的 `dark:` 变体以与 Starlight 的暗模式兼容。
- 在 Starlight 的 UI 中使用 Tailwind [主题颜色和字体](#使用-tailwind-设置-starlight-的样式)。
- 禁用 Tailwind 的 [Preflight](https://tailwindcss.com/docs/preflight) 重置样式,同时有选择地恢复 Preflight 的必要部分,以便使用 Tailwind 的边框实用程序类。

### 使用 Tailwind 创建新项目

使用 `create astro` 创建一个预配置了 Tailwind CSS 的新 Starlight 项目:

<Tabs syncKey="pkg">
<TabItem label="npm">

```sh
npm create astro@latest -- --template starlight/tailwind
```

</TabItem>
<TabItem label="pnpm">

```sh
pnpm create astro --template starlight/tailwind
```

</TabItem>
<TabItem label="Yarn">

```sh
yarn create astro --template starlight/tailwind
```

</TabItem>
</Tabs>

### 将 Tailwind 添加到现有项目中

如果你已经有了一个 Starlight 网站,并且想要添加 Tailwind CSS,请按照以下步骤操作。

<Steps>

1. 将 Astro 的 Tailwind 集成添加到项目中:

   <Tabs syncKey="pkg">

   <TabItem label="npm">

   ```sh
   npx astro add tailwind
   ```

   </TabItem>

   <TabItem label="pnpm">

   ```sh
   pnpm astro add tailwind
   ```

   </TabItem>

   <TabItem label="Yarn">

   ```sh
   yarn astro add tailwind
   ```

   </TabItem>

   </Tabs>

2. 安装 Starlight Tailwind 插件:

   <Tabs syncKey="pkg">

   <TabItem label="npm">

   ```sh
   npm install @astrojs/starlight-tailwind
   ```

   </TabItem>

   <TabItem label="pnpm">

   ```sh
   pnpm add @astrojs/starlight-tailwind
   ```

   </TabItem>

   <TabItem label="Yarn">

   ```sh
   yarn add @astrojs/starlight-tailwind
   ```

   </TabItem>

   </Tabs>

3. 创建一个 CSS 文件,用于 Tailwind 的基础样式,例如在 `src/tailwind.css` 中:

   ```css
   /* src/tailwind.css */
   @tailwind base;
   @tailwind components;
   @tailwind utilities;
   ```

4. 更新你的 Astro 配置文件,使用你的 Tailwind 基础样式并禁用默认的基础样式:

   ```js {11-12,16-17}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';
   import tailwind from '@astrojs/tailwind';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'Docs with Tailwind',
   			customCss: [
   				// 你的 Tailwind 基础样式的相对路径
   				'./src/tailwind.css',
   			],
   		}),
   		tailwind({
   			// 禁用默认的基础样式
   			applyBaseStyles: false,
   		}),
   	],
   });
   ```

5. 将 Starlight Tailwind 插件添加到 `tailwind.config.mjs`:

   ```js ins={2,7}
   // tailwind.config.mjs
   import starlightPlugin from '@astrojs/starlight-tailwind';

   /** @type {import('tailwindcss').Config} */
   export default {
   	content: ['./src/**/*.{astro,html,js,jsx,md,mdx,svelte,ts,tsx,vue}'],
   	plugins: [starlightPlugin()],
   };
   ```

</Steps>

### 使用 Tailwind 设置 Starlight 的样式

Starlight 将使用你的 [Tailwind 主题配置](https://tailwindcss.com/docs/theme)中的值来设置其 UI。

如果设置了以下选项,将覆盖 Starlight 的默认样式:

- `colors.accent` — 用于链接和当前项目高亮
- `colors.gray` — 用于背景颜色和边框
- `fontFamily.sans` — 用于 UI 和内容文本
- `fontFamily.mono` — 用于代码示例

```js {12,14,18,20}
// tailwind.config.mjs
import starlightPlugin from '@astrojs/starlight-tailwind';
import colors from 'tailwindcss/colors';

/** @type {import('tailwindcss').Config} */
export default {
	content: ['./src/**/*.{astro,html,js,jsx,md,mdx,svelte,ts,tsx,vue}'],
	theme: {
		extend: {
			colors: {
				// 你喜欢的强调色。Indigo 是最接近 Starlight 默认的。
				accent: colors.indigo,
				// 你喜欢的灰色。Zinc 是最接近 Starlight 默认的。
				gray: colors.zinc,
			},
			fontFamily: {
				// 你喜欢的文本字体。Starlight 默认使用系统字体堆栈。
				sans: ['"Atkinson Hyperlegible"'],
				// 你喜欢的代码字体。Starlight 默认使用系统等宽字体。
				mono: ['"IBM Plex Mono"'],
			},
		},
	},
	plugins: [starlightPlugin()],
};
```

## 主题

Starlight 的颜色主题可以通过覆盖其默认的自定义属性来控制。
这些变量在整个 UI 中使用,使用一系列灰色阴影用于文本和背景颜色,以及用于链接和突出显示导航中当前项目的强调色。

### 颜色主题编辑器

使用下面的滑块来修改 Starlight 的强调色和灰色调色板。暗色和亮色的预览区域将显示结果颜色,整个页面也会更新以预览你的更改。

使用“对比度级别”选项来指定要满足的 Web 内容无障碍功能指南的[颜色对比度标准](https://developer.mozilla.org/en-US/docs/Web/Accessibility/Understanding_WCAG/Perceivable/Color_contrast)。

当你对你的更改满意时,复制下面的 CSS 或 Tailwind 代码并在你的项目中使用。

import ThemeDesigner from '~/components/theme-designer.astro';

<ThemeDesigner
	labels={{
		presets: {
			label: '预设',
			ocean: '海洋',
			forest: '森林',
			oxide: '氧化',
			nebula: '星云',
			default: '默认',
			random: '随机',
		},
		contrast: {
			label: '对比度级别',
		},
		editor: {
			accentColor: '强调色',
			grayColor: '灰色',
			hue: '色调',
			chroma: '饱和度',
			pickColor: '选择颜色',
		},
		preview: {
			darkMode: '深色模式',
			lightMode: '浅色模式',
			bodyText: '正文以灰色阴影显示,与背景形成高对比度。',
			linkText: '链接是彩色的。',
			dimText: '有些文本(如目录)具有较低的对比度。',
			inlineCode: '内联代码具有独特的背景颜色。',
		},
	}}
>
	<Fragment slot="css-docs">
		将以下 CSS 添加到你的项目的[自定义 CSS
		文件](#自定义-css-样式)中,以将此主题应用到你的网站。
	</Fragment>
	<Fragment slot="tailwind-docs">
		下面的示例 [Tailwind 配置文件](#使用-tailwind-设置-starlight-的样式)
		包含生成的 `accent` 和 `gray` 调色板,以在 `theme.extend.colors`
		配置对象中使用。
	</Fragment>
</ThemeDesigner>


================================================
FILE: docs/src/content/docs/zh-cn/guides/customization.mdx
================================================
---
title: 自定义 Starlight
description: 学习如何通过自定义样式、字体等使你的 Starlight 网站变得与众不同。
---

import { Tabs, TabItem, FileTree, Steps } from '@astrojs/starlight/components';

Starlight 提供了合理的默认样式和功能,因此你可以快速开始,无需配置即可进行操作。
当你想要开始自定义 Starlight 网站的外观时,本指南可以帮助你。

## 添加你的 logo

将自定义 logo 添加到网站标题是将品牌形象添加到 Starlight 网站的快速方法。

<Steps>

1. 将你的 logo 图像文件添加到 `src/assets/` 目录:

   <FileTree>

   - src/
     - assets/
       - **my-logo.svg**
     - content/
   - astro.config.mjs

   </FileTree>

2. 在 `astro.config.mjs` 中,将 logo 的路径添加到 Starlight 的 [`logo.src`](/zh-cn/reference/configuration/#logo) 选项:

   ```diff lang="js"
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: '带有我的标志的页面',
   			logo: {
   +				src: './src/assets/my-logo.svg',
   			},
   		}),
   	],
   });
   ```

</Steps>

默认情况下,logo 将显示在网站的标题旁边。
如果你的 logo 图像已经包含了网站标题,你可以通过设置 `replacesTitle` 选项来在视觉上隐藏标题文本。
标题文本仍包含在屏幕阅读器中,以便标题保持可访问性。

```js {5}
starlight({
  title: '带有我的 logo 的页面',
  logo: {
    src: './src/assets/my-logo.svg',
    replacesTitle: true,
  },
}),
```

### 亮色和暗色 logo 变体

你可以在亮色和暗色模式下显示不同版本的 logo。

<Steps>

1. 将每个变体的图像文件添加到 `src/assets/`:

   <FileTree>

   - src/
     - assets/
       - **light-logo.svg**
       - **dark-logo.svg**
     - content/
   - astro.config.mjs

   </FileTree>

2. 在 `astro.config.mjs` 中,将 logo 变体的路径添加为 `light` 和 `dark` 选项,而不是 `src`:

   ```diff lang="js"
   starlight({
     title: '带有我的标志的页面',
     logo: {
   +    light: './src/assets/light-logo.svg',
   +    dark: './src/assets/dark-logo.svg',
     },
   }),
   ```

</Steps>

## 启用 sitemap

Starlight 内置了生成站点地图(sitemap)的支持。通过在 `astro.config.mjs` 中把 `site` 字段设置为你的 URL 来启用站点地图生成:

```js {4}
// astro.config.mjs
export default defineConfig({
	site: 'https://stargazers.club',
	integrations: [starlight({ title: 'Site with sitemap' })],
});
```

在 Astro 文档中,了解如何 [将站点地图链接添加到 `robots.txt`](https://docs.astro.build/zh-cn/guides/integrations-guide/sitemap/#robotstxt-中的站点地图链接)。

## 页面布局

默认情况下,Starlight 页面使用带有全局导航侧边栏和显示当前页面标题的目录的布局。

你可以通过在页面的正文中设置 [`template: splash`](/zh-cn/reference/frontmatter/#template) 来应用更宽的页面布局,而去除侧边栏。
这对于主页面特别有效,你可以在本站点的[主页](/zh-cn/)上看到它的效果。

```md {5}
---
# src/content/docs/index.md

title: 我的主页面
template: splash
---
```

## 目录

Starlight 在每个页面上显示目录,使读者更容易跳转到他们正在寻找的标题。你可以在 Starlight 集成中全局自定义目录或在 frontmatter 中逐个页面进行设置。

默认情况下,目录中包含 `<h2>` 和 `<h3>` 标题。使用全局 `tableOfContents` 中的 `minHeadingLevel` 和 `maxHeadingLevel` 选项更改要包含的标题级别。通过添加相应的 frontmatter 中的 `tableOfContents` 属性,在单个页面上覆盖这些默认值:

<Tabs syncKey="config-type">
  <TabItem label="Frontmatter">

```md {4-6}
---
# src/content/docs/example.md
title: 只在目录中包含 H2 的页面
tableOfContents:
  minHeadingLevel: 2
  maxHeadingLevel: 2
---
```

  </TabItem>
  <TabItem label="全局配置">

```js {7}
// astro.config.mjs

defineConfig({
	integrations: [
		starlight({
			title: '具有自定义目录配置的文档',
			tableOfContents: { minHeadingLevel: 2, maxHeadingLevel: 2 },
		}),
	],
});
```

  </TabItem>
</Tabs>

通过将 `tableOfContents` 选项设置为 `false` 来完全禁用目录:

<Tabs syncKey="config-type">
  <TabItem label="Frontmatter ">

```md {4}
---
# src/content/docs/example.md
title: 没有目录的页面
tableOfContents: false
---
```

  </TabItem>
  <TabItem label="全局配置">

```js {7}
// astro.config.mjs

defineConfig({
	integrations: [
		starlight({
			title: '全局禁用目录的页面',
			tableOfContents: false,
		}),
	],
});
```

  </TabItem>
</Tabs>

## 社交链接

Starlight 内置了对通过 Starlight 集成中的 [`social`](/zh-cn/reference/configuration/#social) 选项将链接添加到网站标题的社交媒体账户的支持。

`social`数组中的每个条目都必须是具有以下三个属性的对象:

- `icon`:Starlight [内置的图标](/zh-cn/reference/icons/)之一,例如 `"github"`。
- `label`:链接的可访问标签,例如 `"GitHub"`。
- `href`: 链接的 URL,例如 `"https://github.com/withastro/starlight"`。

以下示例添加了指向 Astro Discord 和 Starlight GitHub 仓库的链接:

```js {9-16}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: '带有社交链接的页面',
			social: [
				{ icon: 'discord', label: 'Discord', href: 'https://astro.build/chat' },
				{
					icon: 'github',
					label: 'GitHub',
					href: 'https://github.com/withastro/starlight',
				},
			],
		}),
	],
});
```

## 编辑链接

Starlight 可以在每个页面的页脚中显示“编辑此页”链接。这样读者就可以找到要编辑以改进你的文档的文件。特别是对于开源项目,这有助于鼓励社区的贡献。

要启用编辑链接,请将 Starlight 集成配置中的 [`editLink.baseUrl`](/zh-cn/reference/configuration/#editlink) 设置为用于编辑存储库的URL。`editLink.baseUrl` 的值将附加到当前页面的路径前面,形成完整的编辑链接。

常见的模式包括:

- GitHub:`https://github.com/USER_NAME/REPO_NAME/edit/BRANCH_NAME/`
- GitLab:`https://gitlab.com/USER_NAME/REPO_NAME/-/edit/BRANCH_NAME/`

如果你的 Starlight 项目不在存储库的根目录中,请在基本 URL 的末尾包含项目的路径。

下面的示例显示了为 Starlight 文档配置的编辑链接,这些文档位于 GitHub 上名为 `withastro/starlight` 的存储库的 `main` 分支的 `docs/` 子目录中:

```js {9-11}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: '带有编辑链接的页面',
			editLink: {
				baseUrl: 'https://github.com/withastro/starlight/edit/main/docs/',
			},
		}),
	],
});
```

## 自定义 404 页面

Starlight 网站默认显示一个简单的 404 页面。你可以通过向 `src/content/docs/` 目录添加 `404.md`(或 `404.mdx`)文件来自定义此页面:

<FileTree>

- src/
  - content/
    - docs/
      - **404.md**
      - index.md
- astro.config.mjs

</FileTree>

你可以在 404 页面中使用 Starlight 的所有页面布局和自定义技术。例如,默认的404页面在 frontmatter 中使用 [`splash`](#页面布局) 模板和 [`hero`](/zh-cn/reference/frontmatter/#hero) 组件:

```md {4,6-8}
---
# src/content/docs/404.md
title: '404'
template: splash
editUrl: false
hero:
  title: '404'
  tagline: 页面未找到。请检查URL或尝试使用搜索栏。
---
```

### 禁用默认 404 页面

如果你的项目需要完全自定义的 404 布局,你可以创建一个 `src/pages/404.astro` 路由,并设置 [`disable404Route`](/zh-cn/reference/configuration/#disable404route) 配置选项来禁用 Starlight 的默认路由:

```js {9}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: '带有自定义 404 页面的文档',
			disable404Route: true,
		}),
	],
});
```

## 自定义字体

默认情况下,Starlight 使用用户本地设备上可用的无衬线字体来显示所有文本。这样可以确保文档在加载时以每个用户熟悉的字体快速显示,而不需要额外的带宽下载大型字体文件。

如果你必须向 Starlight 网站添加自定义字体,你可以在自定义CSS文件中设置要使用的字体,或者使用任何其他 [Astro 样式技术](https://docs.astro.build/zh-cn/guides/styling/)。

### 设置字体

如果你已经拥有字体文件,请按照[本地设置指南](#设置本地字体文件)进行操作。如果要使用 Google Fonts,请按照 [Fontsource 设置指南](#设置-fontsource-字体)进行操作。

#### 设置本地字体文件

<Steps>

1. 将字体文件添加到 `src/fonts/` 目录中,并创建一个空的 `font-face.css` 文件:

   <FileTree>

   - src/
     - content/
     - fonts/
       - **CustomFont.woff2**
       - **font-face.css**
   - astro.config.mjs

   </FileTree>

2. 在 `src/fonts/font-face.css` 中为每个字体添加一个 [`@font-face` 声明](https://developer.mozilla.org/zh-CN/docs/Web/CSS/@font-face)。在 `url()` 函数中使用相对路径来引用字体文件:

   ```css
   /* src/fonts/font-face.css */

   @font-face {
   	font-family: 'Custom Font';
   	/* 使用相对路径来引用本地字体文件。 */
   	src: url('./CustomFont.woff2') format('woff2');
   	font-weight: normal;
   	font-style: normal;
   	font-display: swap;
   }
   ```

3. 将 `font-face.css` 文件的路径添加到 Starlight 的 `astro.config.mjs` 配置文件中的 `customCss` 数组中:

   ```diff lang="js"
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: '使用自定义字体的页面',
   			customCss: [
   +			// @font-face CSS文件的相对路径。
   +			'./src/fonts/font-face.css',
   			],
   		}),
   	],
   });
   ```

</Steps>

#### 设置 Fontsource 字体

[Fontsource](https://fontsource.org/) 项目简化了使用 Google Fonts 和其他开源字体的过程。它提供了可安装的 npm 模块,用于你想要使用的字体,并包含了可以添加到项目中的现成 CSS 文件。

<Steps>

1.  在 [Fontsource 目录](https://fontsource.org/)中找到你想要使用的字体。本示例将使用 [IBM Plex Serif](https://fontsource.org/fonts/ibm-plex-serif) 字体。

2.  安装所选字体的包。你可以通过在 Fontsource 字体页面上点击 “Install” 按钮来找到包名称。

         <Tabs syncKey="pkg">

    <TabItem label="npm">

    ```sh
    npm install @fontsource/ibm-plex-serif
    ```

           </TabItem>

        <TabItem label="pnpm">

    ```sh
    pnpm add @fontsource/ibm-plex-serif
    ```

           </TabItem>

        <TabItem label="Yarn">

    ```sh
    yarn add @fontsource/ibm-plex-serif
    ```

           </TabItem>

      </Tabs>

3.  将 Fontsource 的 CSS 文件添加到 Starlight 的 `astro.config.mjs` 配置文件中的 `customCss` 数组中:

    ```diff lang="js"
    // astro.config.mjs
    import { defineConfig } from 'astro/config';
    import starlight from '@astrojs/starlight';

    export default defineConfig({
    	integrations: [
    		starlight({
    			title: '使用自定义字体的文档',
    			customCss: [
    +				// 用于普通和半粗字重的 Fontsource 文件。
    +				'@fontsource/ibm-plex-serif/400.css',
    +				'@fontsource/ibm-plex-serif/600.css',
    			],
    		}),
    	],
    });
    ```

    Fontsource 为每个字体提供了多个 CSS 文件。请参阅 [Fontsource 文档](https://fontsource.org/docs/getting-started/install#4-weights-and-styles)以了解如何包含不同的字重和样式。

</Steps>

### 使用字体

要将设置好的字体应用于你的站点,请在[自定义 CSS 文件](/zh-cn/guides/css-and-tailwind/#自定义-css-样式)中使用所选字体的名称。例如,要在整个站点上覆盖 Starlight 的默认字体,请设置`--sl-font`自定义属性:

```css
/* src/styles/custom.css */

:root {
	--sl-font: 'IBM Plex Serif', serif;
}
```

如果你只想在主要内容上设置字体,而不在侧边栏上设置字体,请使用更具针对性的 CSS:

```css
/* src/styles/custom.css */

main {
	font-family: 'IBM Plex Serif', serif;
}
```

按照[自定义 CSS](/zh-cn/guides/css-and-tailwind/#自定义-css-样式)将样式添加到你的站点。


================================================
FILE: docs/src/content/docs/zh-cn/guides/i18n.mdx
================================================
---
title: 国际化 (i18n)
description: 学习如何配置你的 Starlight 网站支持多种语言。
---

import { FileTree, Steps } from '@astrojs/starlight/components';

Starlight 提供了内置的多语言支持,包括路由、回退内容和完整的从右到左(RTL)语言支持。

## 配置 i18n

<Steps>

1. 通过将 [`locales`](/zh-cn/reference/configuration/#locales) 和 [`defaultLocale`](/zh-cn/reference/configuration/#defaultlocale) 传递给 Starlight 集成,告诉 Starlight 你支持的语言:

   ```js {9-26}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: '我的文档',
   			// 为此网站设置英语为默认语言。
   			defaultLocale: 'en',
   			locales: {
   				// 英文文档在 `src/content/docs/en/` 中。
   				en: {
   					label: 'English',
   				},
   				// 简体中文文档在 `src/content/docs/zh-cn/` 中。
   				'zh-cn': {
   					label: '简体中文',
   					lang: 'zh-CN',
   				},
   				// 阿拉伯文档在 `src/content/docs/ar/` 中。
   				ar: {
   					label: 'العربية',
   					dir: 'rtl',
   				},
   			},
   		}),
   	],
   });
   ```

   你的 `defaultLocale` 将用于回退内容和 UI 标签,所以选择你最有可能开始编写内容的语言,或者已经有内容的语言。

2. 在 `src/content/docs/` 中为每种语言创建一个目录。
   例如,对于上面显示的配置,创建以下文件夹:

   <FileTree>

   - src/
     - content/
       - docs/
         - ar/
         - en/
         - zh-cn/

   </FileTree>

3. 现在你可以在你的语言目录中添加内容文件。使用相同的文件名来关联跨语言的页面,并利用 Starlight 的完整的 i18n 功能,包括回退内容、翻译通知等。

   举个例子,创建 `ar/index.md` 和 `en/index.md` 来分别表示阿拉伯语和英语的主页。

</Steps>

对于更高级的 i18n 场景,Starlight 也支持使用 [Astro 的 `i18n` 配置](https://docs.astro.build/zh-cn/guides/internationalization/#配置-i18n-路由)选项来配置国际化。

### 使用 `root` 语言

你可以使用“root”语言来提供没有任何 i18n 前缀的语言。例如,如果英语是你的 root 语言,那么英语页面的路径将是 `/about` 而不是 `/en/about`。

要设置 root 语言,请在你的 `locales` 配置中使用 `root` 键。如果 root 语言也是你的内容的默认语言,请删除 `defaultLocale` 或将其设置为 `'root'`。

```js {9,11-14}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: '我的文档',
			defaultLocale: 'root', // 可选
			locales: {
				root: {
					label: 'English',
					lang: 'en', // lang 是 root 语言必须的
				},
				'zh-cn': {
					label: '简体中文',
					lang: 'zh-CN',
				},
			},
		}),
	],
});
```

当使用 `root` 语言时,将页面直接放在 `src/content/docs/` 中,而不是在专用的语言文件夹中。例如,当使用上面的配置时,这里是英语和中文的主页文件:

<FileTree>

- src/
  - content/
    - docs/
      - **index.md**
      - zh-cn/
        - **index.md**

</FileTree>

#### 单语言网站

默认情况下,Starlight 是一个单语言(英语)网站。要在其他语言中创建单语言网站,请将其设置为 `locales` 配置中的 `root`:

```diff lang="js" {10-13}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'My Docs',
			locales: {
				root: {
					label: '简体中文',
					lang: 'zh-CN',
				},
			},
		}),
	],
});
```

这允许你在不启用其他多语言网站的国际化功能的情况下,覆盖 Starlight 的默认语言,例如语言选择器。

## 回退内容

Starlight 期望你在所有语言中创建等效的页面。例如,如果你有一个 `en/about.md` 文件,请为你支持的每种其他语言创建一个 `about.md`。这允许 Starlight 为尚未翻译的页面提供自动回退内容。

如果某种语言尚未提供翻译,Starlight 将为读者显示该页面的默认语言(通过 `defaultLocale` 设置)的内容。例如,如果你尚未创建关于你的法语版本,并且你的默认语言是英语,那么访问 `/fr/about` 的访问者将看到来自 `/en/about` 的英语内容,并显示该页面尚未翻译的通知。这有助于你在默认语言中添加内容,然后在翻译人员有时间时逐步翻译它。

## 翻译网站标题

默认情况下,Starlight 会为所有语言使用相同的站点标题。
如果你需要为每种语言自定义标题,你可以在 Starlight 的选项中将一个对象传递给 [`title`](/zh-cn/reference/configuration/#title-必填):

```diff lang="js"
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
-			title: 'My Docs',
+			title: {
+				en: 'My Docs',
+				'zh-CN': '我的文档',
+			},
			defaultLocale: 'en',
			locales: {
				en: { label: 'English' },
				'zh-cn': { label: '简体中文', lang: 'zh-CN' },
			},
		}),
	],
});
```

## 翻译 Starlight 的 UI

import LanguagesList from '~/components/languages-list.astro';
import UIStringsList from '~/components/ui-strings-list.astro';

除了托管翻译的内容文件之外,Starlight 还允许你翻译默认的 UI 字符串(例如,目录中的“本页”标题),以便你的读者可以完全使用所选的语言体验你的网站。

默认提供了<LanguagesList/>的翻译 UI 字符串,
同时我们欢迎[贡献添加更多默认语言](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md)。

你可以通过 `i18n` 数据集合提供你支持的其他语言的翻译 - 或覆盖我们的默认标签。

<Steps>

1. 如果尚未配置,请在 `src/content.config.ts` 中配置 `i18n` 数据集合:

   ```diff lang="js" ins=/, (i18nLoader|i18nSchema)/
   // src/content.config.ts
   import { defineCollection } from 'astro:content';
   import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
   import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';

   export const collections = {
   	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
   +	i18n: defineCollection({ loader: i18nLoader(), schema: i18nSchema() }),
   };
   ```

2. 为你想要提供 UI 翻译字符串的每种其他语言在 `src/content/i18n/` 中创建一个 JSON 文件。
   例如,这将为阿拉伯语和简体中文添加翻译文件:

   <FileTree>

   - src/
     - content/
       - i18n/
         - ar.json
         - zh-CN.json

   </FileTree>

3. 在 JSON 文件中添加你想要翻译的键的翻译。只翻译值,将键保留为英语(例如 `"search.label": "搜索"`)。

   这些是 Starlight 附带的现有字符串的英文默认值:

   <UIStringsList />

   Starlight 的代码块使用了 [Expressive Code](https://expressive-code.com/)。
   你可以在同一个 JSON 文件中使用 `expressiveCode` 键来设置它的 UI 字符串翻译。

   ```json
   {
   	"expressiveCode.copyButtonCopied": "Copied!",
   	"expressiveCode.copyButtonTooltip": "Copy to clipboard",
   	"expressiveCode.terminalWindowFallbackTitle": "Terminal window"
   }
   ```

   Starlight 的搜索模态框由 [Pagefind](https://pagefind.app/) 库提供支持。
   你可以在同一个 JSON 文件中使用 `pagefind` 键来设置它的 UI 字符串翻译。

   ```json
   {
   	"pagefind.clear_search": "Clear",
   	"pagefind.load_more": "Load more results",
   	"pagefind.search_label": "Search this site",
   	"pagefind.filters_label": "Filters",
   	"pagefind.zero_results": "No results for [SEARCH_TERM]",
   	"pagefind.many_results": "[COUNT] results for [SEARCH_TERM]",
   	"pagefind.one_result": "[COUNT] result for [SEARCH_TERM]",
   	"pagefind.alt_search": "No results for [SEARCH_TERM]. Showing results for [DIFFERENT_TERM] instead",
   	"pagefind.search_suggestion": "No results for [SEARCH_TERM]. Try one of the following searches:",
   	"pagefind.searching": "Searching for [SEARCH_TERM]..."
   }
   ```

 </Steps>

### 拓展翻译 schema

通过在 `i18nSchema()` 选项中设置 `extend` 可以向你网站的翻译字典中添加自定义键。
在下面的示例中添加了一个新的可选的 `custom.label` 键:

```diff lang="js"
// src/content.config.ts
import { defineCollection, z } from 'astro:content';
import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';

export const collections = {
	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
	i18n: defineCollection({
		loader: i18nLoader(),
		schema: i18nSchema({
+			extend: z.object({
+				'custom.label': z.string().optional(),
+			}),
		}),
	}),
};
```

在 Astro 文档的[“定义集合模式”](https://docs.astro.build/zh-cn/guides/content-collections/#定义集合模式schema)中了解有关内容集合 schema 的更多信息。

## 使用 UI 翻译

你可以使用由 [i18next](https://www.i18next.com/) 提供支持的统一 API 访问 Starlight 的 [内置 UI 字符串](/zh-cn/guides/i18n/#翻译-starlight-的-ui) 以及 [用户定义](/zh-cn/guides/i18n/#拓展翻译-schema) 和 [插件提供](/zh-cn/reference/plugins/#injecttranslations) 的 UI 字符串。
其中包括了对 [插值](https://www.i18next.com/translation-function/interpolation) 和 [多元化](https://www.i18next.com/translation-function/plurals) 等功能的支持。

在 Astro 组件中,此 API 作为 [全局 `Astro` 对象](https://docs.astro.build/zh-cn/reference/api-reference/#locals) 的一部分提供,即 `Astro.locals.t`:

```astro title="example.astro"
<p dir={Astro.locals.t.dir()}>
	{Astro.locals.t('404.text')}
</p>
```

你还可以在 [端点](https://docs.astro.build/zh-cn/guides/endpoints/) 中使用 API,其中的 `locals` 对象可作为 [端点上下文](https://docs.astro.build/zh-cn/reference/api-reference/#locals) 的一部分使用:

```ts title="src/pages/404.ts"
export const GET = (context) => {
	return new Response(context.locals.t('404.text'));
};
```

在 Starlight 插件的上下文中,你可以使用 [`useTranslations()`](/zh-cn/reference/plugins/#usetranslations) 助手函数来访问特定语言的此 API。
有关更多信息,请参阅 [插件参考](/zh-cn/reference/plugins/)。

### 渲染 UI 字符串

使用 `locals.t()` 函数以渲染 UI 字符串。
这是 i18next 的 `t()` 函数的一个实例,该函数将 UI 字符串键作为其第一个参数,并返回当前语言的相应翻译。

例如,给定一个包含以下内容的自定义翻译文件:

```json title="src/content/i18n/en.json"
{
	"link.astro": "Astro documentation",
	"link.astro.custom": "Astro documentation for {{feature}}"
}
```

第一个 UI 字符串可以通过将 `'link.astro'` 传递给 `t()` 函数来渲染:

```astro {3}
<!-- src/components/Example.astro -->
<a href="https://docs.astro.build/">
	{Astro.locals.t('link.astro')}
</a>
<!-- 渲染结果:<a href="...">Astro documentation</a> -->
```

第二个 UI 字符串对 `{{feature}}` 占位符使用了 i18next 的 [插值语法](https://www.i18next.com/translation-function/interpolation)。
`feature` 的值在被作为第二个参数传递给 `t()` 时,必须被设置在一个选项对象中:

```astro {3}
<!-- src/components/Example.astro -->
<a href="https://docs.astro.build/en/guides/astro-db/">
	{Astro.locals.t('link.astro.custom', { feature: 'Astro DB' })}
</a>
<!-- 渲染结果:<a href="...">Astro documentation for Astro DB</a> -->
```

有关如何使用 `t()` 函数进行插值、格式化等更多信息,请参阅 [i18next 文档](https://www.i18next.com/overview/api#t)。

### 高级 API

#### `t.all()`

`locals.t.all()` 函数可返回一个对象,返回的对象中包含当前区域设置下所有可用的 UI 字符串。

```astro
---
// src/components/Example.astro
const allStrings = Astro.locals.t.all();
//    ^
//    {
//      "skipLink.label": "Skip to content",
//      "search.label": "Search",
//      …
//    }
---
```

#### `t.exists()`

要检查某个区域设置是否存在某个翻译键,请使用 `locals.t.exists()` 函数,并将该翻译键作为第一个参数。
如需覆盖当前的区域设置,请传递第二个可选参数。

```astro
---
// src/components/Example.astro
const keyExistsInCurrentLocale = Astro.locals.t.exists('a.key');
//    ^ true
const keyExistsInFrench = Astro.locals.t.exists('another.key', { lng: 'fr' });
//    ^ false
---
```

有关详细信息,请参阅 [i18next 文档中的 `exists()` 参考](https://www.i18next.com/overview/api#exists)。

#### `t.dir()`

`locals.t.dir()` 函数可返回当前或特定语言环境的文本方向。

```astro
---
// src/components/Example.astro
const currentDirection = Astro.locals.t.dir();
//    ^
//    'ltr'
const arabicDirection = Astro.locals.t.dir('ar');
//    ^
//    'rtl'
---
```

有关详细信息,请参阅 [i18next 文档中的 `dir()` 参考](https://www.i18next.com/overview/api#dir)。

## 访问当前语言环境

你可以使用 [`Astro.currentLocale`](https://docs.astro.build/zh-cn/reference/api-reference/#currentlocale) 在 `.astro` 组件中读取当前的语言环境。

下面的示例读取当前语言环境,并使用它和 [`getRelativeLocaleUrl()`](https://docs.astro.build/zh-cn/reference/modules/astro-i18n/#getrelativelocaleurl) 助手函数以生成一个当前语言的关于页面的链接:

```astro
---
// src/components/AboutLink.astro
import { getRelativeLocaleUrl } from 'astro:i18n';
---

<a href={getRelativeLocaleUrl(Astro.currentLocale ?? 'en', 'about')}>About</a>
```


================================================
FILE: docs/src/content/docs/zh-cn/guides/overriding-components.mdx
================================================
---
title: 重写组件
description: 学习如何通过替换 Starlight 的内置组件来给你的文档站点 UI 添加自定义元素。
---

import { Steps } from '@astrojs/starlight/components';

Starlight 的默认 UI 和配置选项被设计成能灵活地适用于各种内容。大部分 Starlight 的默认外观可以通过 [CSS](/zh-cn/guides/css-and-tailwind/) 和 [配置选项](/zh-cn/guides/customization/) 进行自定义。

当你的需求超出了默认提供的功能时,Starlight 支持使用你自己的自定义组件来扩展或重写(完全替换)它的默认组件。

## 什么时候重写

重写 Starlight 的默认组件在以下情况下很有用:

- 你想要修改 Starlight 的一部分 UI 的样式,但是无法通过使用[自定义 CSS](/zh-cn/guides/css-and-tailwind/) 实现。
- 你想要修改 Starlight 的一部分 UI 的行为。
- 你想要在 Starlight 的现有 UI 旁边添加一些额外的 UI。

## 如何重写

<Steps>

1. 选择你想要重写的 Starlight 组件。
   你可以在[重写参考](/zh-cn/reference/overrides/)中找到完整的组件列表。

   :::tip
   不确定你需要重写哪个组件?使用 [交互式 Starlight 重写地图](https://starlight-overrides-map.netlify.app/) 来发现 Starlight UI 组件的名称。
   :::

   本示例将重写 Starlight 页面导航栏中的 [`SocialIcons`](/zh-cn/reference/overrides/#socialicons) 组件。

2. 创建一个 Astro 组件来替换 Starlight 组件。
   本示例渲染了一个联系方式链接。

   ```astro
   ---
   // src/components/EmailLink.astro

   const email = 'houston@example.com';
   ---

   <a href=`mailto:${email}`>E-mail Me</a>
   ```

3. 在 `astro.config.mjs` 的 [`components`](/zh-cn/reference/configuration/#components) 配置选项中告诉 Starlight 使用你的自定义组件:

   ```js {9-12}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'My Docs with Overrides',
   			components: {
   				// 重写默认的 `SocialIcons` 组件。
   				SocialIcons: './src/components/EmailLink.astro',
   			},
   		}),
   	],
   });
   ```

</Steps>

## 复用内置组件

你可以像使用自己的组件一样使用 Starlight 的默认 UI 组件:导入并在你自己的自定义组件中渲染它们。这样你就可以在你的设计中保留 Starlight 的基本 UI,同时在它们旁边添加额外的 UI。

下面的示例是一个自定义组件,它渲染了一个电子邮件链接以及默认的 `SocialIcons` 组件:

```astro {3,7}
---
// src/components/EmailLink.astro
import Default from '@astrojs/starlight/components/SocialIcons.astro';
---

<a href="mailto:houston@example.com">E-mail Me</a>
<Default><slot /></Default>
```

在自定义组件中渲染内置组件时,在默认组件中添加一个 [`<slot />`](https://docs.astro.build/zh-cn/basics/astro-components/#插槽)。这样可以确保如果组件传入了任何子元素,Astro 就知道在哪里渲染它们。

如果你要复用包含 [命名插槽](https://docs.astro.build/zh-cn/basics/astro-components/#命名插槽) 的 [`PageFrame`](/zh-cn/reference/overrides/#pageframe) 或 [`TwoColumnContent`](/zh-cn/reference/overrides/#twocolumncontent) 组件,你还需要 [传递](https://docs.astro.build/zh-cn/basics/astro-components/#传递插槽) 这些插槽。

下面的示例展示了一个自定义组件,它复用了 `TwoColumnContent` 组件,该组件需要传递一个额外的 `right-sidebar` 命名插槽:

```astro {8}
---
// src/components/CustomContent.astro
import Default from '@astrojs/starlight/components/TwoColumnContent.astro';
---

<Default>
	<slot />
	<slot name="right-sidebar" slot="right-sidebar" />
</Default>
```

## 使用页面数据

当重写 Starlight 组件时,你可以访问包含当前页面所有数据的全局 [`starlightRoute` 对象](/zh-cn/guides/route-data/)。
这使得你可以使用这些值来控制你的组件模板的渲染方式。

在下面的示例中,一个 [`PageTitle`](/zh-cn/reference/overrides/#pagetitle) 组件显示当前页面的标题,该标题在内容的前端元数据中设置:

```astro {4} "{title}"
---
// src/components/Title.astro

const { title } = Astro.locals.starlightRoute.entry.data;
---

<h1 id="_top">{title}</h1>

<style>
	h1 {
		font-family: 'Comic Sans';
	}
</style>
```

了解更多关于所有可用属性的信息,请参阅 [路由数据参考](/zh-cn/reference/route-data/)。

### 仅在特定页面上重写

组件重写在所有页面上生效。但是,你可以使用 `starlightRoute` 中的值来条件性渲染,决定何时显示你的自定义 UI,何时显示 Starlight 的默认 UI,甚至何时显示完全不同的内容。

在下面的示例中,一个重写 [`Footer`](/zh-cn/reference/overrides/#footer) 的组件只在首页上显示“Built with Starlight 🌟”,在其他页面上显示默认的页脚:

```astro
---
// src/components/ConditionalFooter.astro
import Default from '@astrojs/starlight/components/Footer.astro';

const isHomepage = Astro.locals.starlightRoute.id === '';
---

{
	isHomepage ? (
		<footer>Built with Starlight 🌟</footer>
	) : (
		<Default>
			<slot />
		</Default>
	)
}
```

了解更多关于条件渲染的内容,请参阅 [Astro 模板语法指南](https://docs.astro.build/zh-cn/basics/astro-syntax/#动态-html)。


================================================
FILE: docs/src/content/docs/zh-cn/guides/pages.mdx
================================================
---
title: 页面
description: 了解如何使用 Starlight 创建和管理文档站点页面。
sidebar:
  order: 1
tableOfContents:
  maxHeadingLevel: 4
---

Starlight 根据你的内容生成站点的 HTML 页面,并通过 Markdown frontmatter 提供灵活的选项。
此外,Starlight 项目可以完全使用 [Astro 强大的页面生成工具](https://docs.astro.build/zh-cn/basics/astro-pages/)。
本指南介绍了 Starlight 中的页面生成工作原理。

## 内容页面

### 文件格式

Starlight 支持在 Markdown 和 MDX 中创作内容,无需任何配置。
你可以按照 [“Markdoc” 指南](/zh-cn/guides/authoring-content/#markdoc) 添加对 Markdoc 的支持。

### 添加页面

通过在 `src/content/docs/` 中创建 `.md` 或 `.mdx` 文件来添加新页面。
使用子文件夹来组织文件并创建多个路径段。

举个例子,以下文件结构将在 `example.com/hello-world` 和 `example.com/reference/faq` 生成页面:

import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src/
  - content/
    - docs/
      - hello-world.md
      - reference/
        - faq.md

</FileTree>

### 类型安全的 frontmatter

所有的 Starlight 页面都共享一个可定制的 [通用 frontmatter 属性集](/zh-cn/reference/frontmatter/),用于控制页面的外观:

```md
---
title: Hello, World!
description: 这是我的 Starlight 网站中的一个页面
---
```

如果你忘记了一些重要的东西,Starlight 会提醒你。

## 自定义页面

对于高级用例,你可以通过创建 `src/pages/` 目录来添加自定义页面。
`src/pages/` 目录使用 [Astro 的基于文件的路由](https://docs.astro.build/zh-cn/basics/astro-pages/#基于文件的路由), 并支持 `.astro` 文件等其他页面格式。

这对于需要完全自定义布局或从其他数据源生成页面的情况非常有用。

举个例子,以下文件结构将在 `example.com/custom` 和 `example.com/archived` 生成页面:

<FileTree>

- src/
  - content/
    - docs/
      - hello-world.md
  - pages/
    - custom.astro
    - archived.html

</FileTree>

在 [Astro 文档中的“页面”指南](https://docs.astro.build/zh-cn/basics/astro-pages/) 中了解更多。

### 在自定义页面中使用 Starlight 的设计

要在自定义页面中使用 Starlight 布局,请使用 [`<StarlightPage />` 组件](#starlightpage-组件)包装页面内容。

如果你正在动态生成内容但仍想使用 Starlight 的设计,这会很有帮助。

要在标题中添加和 Starlight 的 Markdown 锚点链接样式一样的锚点链接,你可以在自定义页面中使用 [`<AnchorHeading>` 组件](#anchorheading-组件)。

```astro
---
// src/pages/custom-page/example.astro
import StarlightPage from '@astrojs/starlight/components/StarlightPage.astro';
import AnchorHeading from '@astrojs/starlight/components/AnchorHeading.astro';
import CustomComponent from './CustomComponent.astro';
---

<StarlightPage frontmatter={{ title: '我的自定义页面' }}>
	<p>这是一个有自定义组件的自定义页面:</p>
	<CustomComponent />

	<AnchorHeading level="2" id="learn-more">了解更多</AnchorHeading>
	<p>
		<a href="https://starlight.astro.build/">在 Starlight 文档中阅读更多</a>
	</p>
</StarlightPage>
```

#### `<StarlightPage>` 组件

`<StarlightPage />` 组件使用 Starlight 的布局和样式渲染完整页面内容。

```astro
---
import StarlightPage from '@astrojs/starlight/components/StarlightPage.astro';
---

<StarlightPage frontmatter={{ title: '我的自定义页面' }}>
	<!-- 自定义页面内容 -->
</StarlightPage>
```

`<StarlightPage />` 组件接受以下 props。

##### `frontmatter`

**必填**  
**类型:** `StarlightPageFrontmatter`

为此页面设置 [frontmatter 属性](/zh-cn/reference/frontmatter/),类似于 Markdown 页面中的 frontmatter。
[`title`](/zh-cn/reference/frontmatter/#title-必填) 属性是必填的,其他所有属性都是可选的。

以下是与 Markdown frontmatter 不同的属性:

- [`slug`](/zh-cn/reference/frontmatter/#slug) 属性不受支持,并且会根据自定义页面的 URL 自动设置。
- [`editUrl`](/zh-cn/reference/frontmatter/#editurl) 选项需要一个 URL 来显示编辑链接。
- 用于自定义页面如何在 [自动生成的链接组](/zh-cn/reference/configuration/#sidebar) 中显示的 [`sidebar`](/zh-cn/reference/frontmatter/#sidebar) frontmatter 属性不可用。使用 `<StarlightPage />` 组件的页面不是集合的一部分,不能添加到自动生成的侧边栏组中。
- [`draft`](/zh-cn/reference/frontmatter/#draft) 选项仅会显示页面为草稿的 [通知](/zh-cn/reference/overrides/#draftcontentnotice),但不会自动将其从生产版本中排除。

##### `sidebar`

**类型:**[`SidebarItem[]`](/zh-cn/reference/configuration/#sidebaritem)  
**默认值:** 根据 [全局 `sidebar` 配置](/zh-cn/reference/configuration/#sidebar) 生成的侧边栏

为此页面提供自定义站点导航侧边栏。
如果未设置,此页面将使用默认的全局侧边栏。

例如,以下页面使用指向主页的链接和一组指向各种其他自定义页面的链接覆盖了默认的侧边栏。

```astro {3-13}
<StarlightPage
	frontmatter={{ title: '猎户座' }}
	sidebar={[
		{ label: '首页', link: '/' },
		{
			label: '星座',
			items: [
				{ label: '仙女座', link: '/andromeda/' },
				{ label: '猎户座', link: '/orion/' },
				{ label: '射手座', link: '/sagittarius/', badge: 'Stub' },
			],
		},
	]}
>
	示例内容。
</StarlightPage>
```

了解更多有关自定义侧边栏的可用选项,请参阅[“侧边栏导航”](/zh-cn/guides/sidebar/)指南。

##### `hasSidebar`

**类型:** `boolean`  
**默认值:** 如果 [`frontmatter.template`](/zh-cn/reference/frontmatter/#template) 是 `'splash'`,为`false`,否则为 `true`

控制是否在此页面上显示侧边栏。

##### `headings`

**类型:** `{ depth: number; slug: string; text: string }[]`  
**默认值:** `[]`

提供此页面上所有标题的数组。
如果提供了,Starlight 将从这些标题生成页面目录。

##### `dir`

**类型:** `'ltr' | 'rtl'`  
**默认值:** 当前语言环境的书写方向

设置此页面内容的书写方向。

##### `lang`

**类型:** `string`  
**默认值:** 当前语言环境的语言

为此页面的内容设置 BCP-47 语言标签,例如 `en`、`zh-CN` 或 `pt-BR`。

##### `isFallback`

**类型:** `boolean`  
**默认值:** `false`

表示此页面是否使用了[回退内容](/zh-cn/guides/i18n/#回退内容),因为当前语言没有翻译。

#### `<AnchorHeading>` 组件

`<AnchorHeading />` 组件渲染一个 HTML 标题元素,并带有一个可点击的锚点链接,样式与 Starlight 的 Markdown 样式一样。

```astro
---
import AnchorHeading from '@astrojs/starlight/components/AnchorHeading.astro';
---

<AnchorHeading level="2" id="sub-heading">子标题</AnchorHeading>
```

它接受以下属性以及任何其他有效的[全局 HTML 属性](https://developer.mozilla.org/zh-CN/docs/Web/HTML/Global_attributes)。

##### `level`

**必填**  
**类型:** `1 | 2 | 3 | 4 | 5 | 6`

要渲染的标题级别。
例如,`level="1"` 将渲染一个 `<h1>` 元素。

##### `id`

**必填**  
**类型:** `string`

用于此标题的唯一 ID。
这将用作渲染标题的 `id` 属性,并且锚点图标将链接到它。


================================================
FILE: docs/src/content/docs/zh-cn/guides/project-structure.mdx
================================================
---
title: 项目结构
description: 了解如何组织 Starlight 项目中的文件。
---

本指南将向你展示 Starlight 项目的组织方式以及项目中的不同文件的作用。

Starlight 项目通常遵循与其他 Astro 项目相同的文件和目录结构。有关更多详细信息,请参阅 [Astro 的项目结构文档](https://docs.astro.build/zh-cn/basics/project-structure/)。

## 文件和目录

- `astro.config.mjs` — Astro 配置文件;包括 Starlight 集成和配置。
- `src/content.config.ts` — 内容集合配置文件;将 Starlight 的 frontmatter 模式添加到你的项目中。
- `src/content/docs/` — 内容文件。Starlight 将此目录中的每个 `.md`、`.mdx` 或 `.mdoc` 文件转换为站点上的一个页面。
- `src/content/i18n/` (可选) — 支持[国际化](/zh-cn/guides/i18n/)的翻译数据。
- `src/` — 项目的其他源代码和文档(组件、样式、图像等)。
- `public/` — 静态资源(字体、网站图标、PDF 等)不会被 Astro 处理。

## 示例项目内容

一个 Starlight 项目目录可能如下所示:

import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- public/
  - favicon.svg
- src/
  - assets/
    - logo.svg
    - screenshot.jpg
  - components/
    - CustomButton.astro
    - InteractiveWidget.jsx
  - content/
    - docs/
      - guides/
        - 01-getting-started.md
        - 02-advanced.md
      - index.mdx
  - content.config.ts
- astro.config.mjs
- package.json
- tsconfig.json

</FileTree>


================================================
FILE: docs/src/content/docs/zh-cn/guides/route-data.mdx
================================================
---
title: 路由数据
description: 了解 Starlight 的页面数据模型是如何用于渲染你的页面以及如何自定义它。
---

import { Steps } from '@astrojs/starlight/components';

当 Starlight 渲染文档中的页面时,它首先创建一个路由数据对象来表示该页面上的内容。
本指南解释了路由数据是如何生成的,如何使用它,以及如何自定义它来修改Starlight的默认行为。

有关可用属性的完整列表,请参阅 [“路由数据参考”](/zh-cn/reference/route-data/)。

## 什么是路由数据?

Starlight 路由数据是一个包含渲染单个页面所需的所有信息的对象。
它包括当前页面的信息以及从你的 Starlight 配置生成的数据。

## 使用路由数据

Starlight 的所有组件都使用路由数据来决定为每个页面渲染什么。
例如,[`siteTitle`](/zh-cn/reference/route-data/#sitetitle) 字符串用于显示网站标题,[`sidebar`](/zh-cn/reference/route-data/#sidebar) 数组用于渲染全局侧边栏导航。

你可以在 Astro 组件中通过 `Astro.locals.starlightRoute` 全局变量访问这些数据:

```astro title="example.astro" {2}
---
const { siteTitle } = Astro.locals.starlightRoute;
---

<p>此网站的页面标题是 “{siteTitle}”</p>
```

例如,在 [重写组件](/zh-cn/guides/overriding-components/) 以自定义显示内容时,这会很有用。

## 自定义路由数据

Starlight 的路由数据是开箱即用的,不需要任何配置。但是,对于高级用例,你可能需要自定义某些或所有页面的路由数据,以修改你的网站显示方式。

这与 [重写组件](/zh-cn/guides/overriding-components/) 的概念类似,但不是修改 Starlight 渲染数据的方式,而是修改 Starlight 渲染的数据。

### 什么时候自定义路由数据

当你希望以现有配置选项无法实现的方式修改 Starlight 处理数据的方式时,自定义路由数据会很有用。

例如,你可能想要过滤侧边栏项目或自定义特定页面的标题。
像这样的更改不需要修改 Starlight 的默认组件,只需要传递给这些组件的数据。

### 如何自定义路由数据

你可以使用一种特殊形式的 “中间件” 来自定义路由数据。
这是一个每次 Starlight 渲染页面时都会调用的函数,可以修改路由数据对象中的值。

<Steps>

1. 创建一个新文件,使用 Starlight 的 `defineRouteMiddleware()` 工具函数导出一个 `onRequest` 函数:

   ```ts
   // src/routeData.ts
   import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

   export const onRequest = defineRouteMiddleware(() => {});
   ```

2. 告诉 Starlight 你的路由数据中间件文件在 `astro.config.mjs` 中的位置:

   ```js ins={9}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: 'My delightful docs site',
   			routeMiddleware: './src/routeData.ts',
   		}),
   	],
   });
   ```

3. 更新你的 `onRequest` 函数来修改路由数据。

   你的中间件接收的第一个参数是 [Astro 的上下文对象](https://docs.astro.build/zh-cn/reference/api-reference/)。
   它包含关于当前页面渲染的完整信息,包括当前 URL 和 `locals`。

   在这个例子中,我们将在每页标题的末尾添加一个感叹号,使我们的文档更加精彩。

   ```ts
   // src/routeData.ts
   import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

   export const onRequest = defineRouteMiddleware((context) => {
   	// 获取此页面的内容集合条目。
   	const { entry } = context.locals.starlightRoute;
   	// 更新标题以添加感叹号。
   	entry.data.title = entry.data.title + '!';
   });
   ```

</Steps>

#### 多个路由中间件

Starlight 还支持提供多个中间件。
将 `routeMiddleware` 设置为路径数组,以添加多个中间件处理程序:

```js {9}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'My site with multiple middleware',
			routeMiddleware: ['./src/middleware-one.ts', './src/middleware-two.ts'],
		}),
	],
});
```

#### 等待稍后的路由中间件

为了在执行代码之前等待堆栈中稍后的中间件运行,你可以等待作为第二个参数传递给中间件函数的 `next()` 回调。这对于等待插件的中间件运行后再进行更改非常有用。

```ts "next" "await next();"
// src/routeData.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

export const onRequest = defineRouteMiddleware(async (context, next) => {
	// 等待后续中间件运行。
	await next();
	// 修改路由数据
	const { entry } = context.locals.starlightRoute;
	entry.data.title = entry.data.title + '!';
});
```


================================================
FILE: docs/src/content/docs/zh-cn/guides/sidebar.mdx
================================================
---
title: 侧边栏导航
description: 了解如何设置和自定义 Starlight 站点的侧边栏导航链接。
---

import { FileTree } from '@astrojs/starlight/components';
import SidebarPreview from '~/components/sidebar-preview.astro';

一个组织良好的侧边栏是良好文档的关键,因为它是用户浏览你的站点的主要方式之一。Starlight 提供了一整套选项来自定义侧边栏布局和内容。

## 默认侧边栏

默认情况查下,Starlight 会根据你的文档文件系统结构自动生成侧边栏,使用每个文件的 `title` 属性作为侧边栏条目。

例如,给定以下文件结构:

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - andromeda.md
        - orion.md
      - stars/
        - betelgeuse.md

</FileTree>

将会自动生成以下侧边栏:

<SidebarPreview
	config={[
		{
			label: 'constellations',
			items: [
				{ label: '仙女座', link: '' },
				{ label: '猎户座', link: '' },
			],
		},
		{
			label: 'stars',
			items: [{ label: '参宿四', link: '' }],
		},
	]}
/>

在 [自动生成的分组](#自动生成的分组) 章节了解更多关于自动生成侧边栏的内容。

## 添加链接和链接分组

要配置侧边栏链接和链接分组(在可折叠的标题中),请在 `astro.config.mjs` 中使用 [`starlight.sidebar`](/zh-cn/reference/configuration/#sidebar) 属性。

结合使用链接和链接分组,你可以创建各种侧边栏布局。

### 内部链接

使用带有 `slug` 属性的对象为 `src/content/docs/` 中的页面添加链接。
默认情况下,链接页面的标题会被作为标签。

例如,进行以下的配置:

```js "slug:"
starlight({
	sidebar: [
		{ slug: 'constellations/andromeda' },
		{ slug: 'constellations/orion' },
	],
});
```

并给定以下的文件结构:

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - andromeda.md
        - orion.md

</FileTree>

那么将会生成如下的侧边栏:

<SidebarPreview
	config={[
		{ label: '仙女座', link: '' },
		{ label: '猎户座', link: '' },
	]}
/>

而要想覆盖从链接页面的 frontmatter 所推断出来的值,你可以添加 `label`,[`translations`](#国际化),以及 [`attrs`](#自定义-html-属性) 属性。

想了解更多通过 frontmatter 控制侧边栏外观的内容,请参阅 [“在 frontmatter 中自定义自动生成的链接”](#在-frontmatter-中自定义自动生成的链接)。

#### 内部链接的简易写法

内部链接也可以通过只提供一个页面标题字符串来指定。

例如,以下的配置等同于上面使用 `slug` 的配置:

```js "slug:"
starlight({
	sidebar: ['constellations/andromeda', 'constellations/orion'],
});
```

### 其他链接

使用带有 `label` 和 `link` 属性的对象,添加指向外部或非文档页面的链接。

```js "label:" "link:"
starlight({
	sidebar: [
		// 指向网站中非文档页面的链接。
		{ label: '流星商店', link: '/shop/' },
		// 指向 NASA 网站的外部链接。
		{ label: 'NASA', link: 'https://www.nasa.gov/' },
	],
});
```

上面的配置生成以下侧边栏:

<SidebarPreview
	config={[
		{ label: '流星商店', link: '' },
		{ label: 'NASA', link: 'https://www.nasa.gov/' },
	]}
/>

### 分组

你可以通过在可折叠的标题下将相关链接组合在一起来为侧边栏添加结构。
分组可以包含链接和其他子组。

使用具有 `label` 和 `items` 属性的对象添加一个分组。
`label` 将用作分组的标题。
将链接或子组添加到 `items` 数组中。

```js /^\s*(label:|items:)/
starlight({
	sidebar: [
		// 一个名为 "星座" 的链接分组
		{
			label: '星座',
			items: [
				'constellations/carina',
				'constellations/centaurus',
				// 星座周期的嵌套链接分组。
				{
					label: '周期',
					items: [
						'constellations/andromeda',
						'constellations/orion',
						'constellations/ursa-minor',
					],
				},
			],
		},
	],
});
```

上面的配置生成以下侧边栏:

<SidebarPreview
	config={[
		{
			label: '星座',
			items: [
				{ label: '船底座', link: '' },
				{ label: '半人马座', link: '' },
				{
					label: '周期',
					items: [
						{ label: '仙女座', link: '' },
						{ label: '猎户座', link: '' },
						{ label: '小熊座', link: '' },
					],
				},
			],
		},
	]}
/>

### 自动生成的分组

Starlight 可以根据文档目录在侧边栏中自动生成一个分组。当你不想手动输入分组中的每个侧边栏项目时,这很有用。

默认情况下,页面按照文件 [`slug`](/zh-cn/reference/route-data/#slug) 的字母顺序排序。

使用具有 `label` 和 `autogenerate` 属性的对象添加自动生成的分组。`autogenerate` 的配置必须指定用于侧边栏条目的 `directory` 。例如,使用以下配置:

```js "label:" "autogenerate:"
starlight({
	sidebar: [
		{
			label: '星座',
			// 自动生成一个链接分组,用于 '星座' 目录。
			autogenerate: { directory: 'constellations' },
		},
	],
});
```

给定以下文件结构:

<FileTree>

- src/
  - content/
    - docs/
      - constellations/
        - carina.md
        - centaurus.md
        - seasonal/
          - andromeda.md

</FileTree>

将会自动生成以下侧边栏:

<SidebarPreview
	config={[
		{
			label: '星座',
			items: [
				{ label: '船底座', link: '' },
				{ label: '半人马座', link: '' },
				{
					label: 'seasonal',
					items: [{ label: '仙女座', link: '' }],
				},
			],
		},
	]}
/>

## 在 frontmatter 中自定义自动生成的链接

在单个页面中使用 [`sidebar` frontmatter 字段](/zh-cn/reference/frontmatter/#sidebar) 来自定义自动生成的链接。

侧边栏 frontmatter 选项允许你设置 [自定义标签](/zh-cn/reference/frontmatter/#label) 或者为链接添加 [徽章](/zh-cn/reference/frontmatter/#badge),[隐藏](/zh-cn/reference/frontmatter/#hidden) 侧边栏中的链接,或者定义 [自定义排序权重](/zh-cn/reference/frontmatter/#order)。

```md "sidebar:"
---
# src/content/docs/example.md
title: 我的页面
sidebar:
  # 为链接设置自定义标签
  label: 自定义侧边栏 label
  # 为链接设置自定义顺序(数字越小显示在上方)
  order: 2
  # 为链接添加徽章
  badge:
    text: New
    variant: tip
---
```

一个包含上面 frontmatter 的页面的自动生成分组将会生成以下侧边栏:

<SidebarPreview
	config={[
		{
			label: '指南',
			items: [
				{ label: '一个页面', link: '' },
				{
					label: '自定义侧边栏 label ',
					link: '',
					badge: { text: 'New', variant: 'tip' },
				},
				{ label: '其他页面', link: '' },
			],
		},
	]}
/>

:::note
`sidebar` frontmatter 配置仅用于自动生成分组中的链接和使用 `slug` 属性定义的文档链接。它并不适用于使用 `link` 属性定义的链接。
:::

## 徽章

链接、分组、自动生成的分组都可以包含一个 `badge` 属性,以在它们的标签旁边显示徽章。

```js {9,16}
starlight({
	sidebar: [
		{
			label: '星星',
			items: [
				// 带有 "Supergiant" 徽章的链接。
				{
					slug: 'stars/persei',
					badge: 'Supergiant',
				},
			],
		},
		// 带有 "Outdated" 徽章的自动生成分组。
		{
			label: '卫星',
			badge: 'Outdated',
			autogenerate: { directory: 'moons' },
		},
	],
});
```

以上配置将生成以下侧边栏:

<SidebarPreview
	config={[
		{
			label: '星星',
			items: [
				{
					label: '英仙座',
					link: '',
					badge: { text: '超巨星', variant: 'default' },
				},
			],
		},
		{
			label: '卫星',
			badge: { text: 'Outdated', variant: 'default' },
			items: [
				{
					label: '木卫一',
					link: '',
				},
				{
					label: '木卫二',
					link: '',
				},
				{
					label: '木卫三',
					link: '',
				},
			],
		},
	]}
/>

### 徽章种类和自定义样式

使用具有 `text`、`variant` 和 `class` 属性的对象自定义徽章样式。

`text` 属性表示要显示的内容(例如 "New")。

默认情况下,徽章将使用你的网站的强调色。要使用内置的徽章样式,请将 `variant` 属性设置为以下值之一:`note`、`tip`、`danger`、`caution` 或 `success`。

你还可以通过设置 `class` 属性为一个 CSS 类名来创建自定义的徽章样式。

```js {9}
starlight({
	sidebar: [
		{
			label: '星星',
			items: [
				// 一个带有黄色 "Stub" 徽章的链接。
				{
					slug: 'stars/sirius',
					badge: { text: 'Stub', variant: 'caution' },
				},
			],
		},
	],
});
```

以上配置将生成以下侧边栏:

<SidebarPreview
	config={[
		{
			label: '星星',
			items: [
				{
					label: '天狼星',
					link: '',
					badge: { text: 'Stub', variant: 'caution' },
				},
			],
		},
	]}
/>

了解关于[使用和自定义徽章](/zh-cn/components/badges/#用法)的更多信息。

## 自定义 HTML 属性

可以通过在链接对象里添加 `attrs` 属性来自定义链接元素的 HTML 属性。

在下面的例子中,通过 `attrs` 添加了一个 `target="_blank"` 属性,使得链接在新标签页中打开,并应用了一个自定义的 `style` 属性使链接标签变为斜体:

```js {10}
starlight({
	sidebar: [
		{
			label: '资源',
			items: [
				// 一个指向 NASA 网站的在新标签页打开的外部链接。
				{
					label: 'NASA',
					link: 'https://www.nasa.gov/',
					attrs: { target: '_blank', style: 'font-style: italic' },
				},
			],
		},
	],
});
```

以上配置将生成以下侧边栏:

<SidebarPreview
	config={[
		{
			label: '资源',
			items: [
				{
					label: 'NASA',
					link: 'https://www.nasa.gov/',
					attrs: {
						target: '_blank',
						style: 'font-style: italic',
					},
				},
			],
		},
	]}
/>

## 国际化

你可以使用链接和分组条目上的 `translations` 属性,通过指定 [BCP-47](https://www.w3.org/International/questions/qa-choosing-language-tags) 语言标签,为每种支持的语言翻译链接或分组标签,例如用 `"en"`、`"ar"` 或 `"zh-CN"` 作为键,翻译后的标签作为值。

`label` 属性将用于默认语言和没有翻译的语言。

```js {5-7,11-13,18-20}
starlight({
	sidebar: [
		{
			label: '星座',
			translations: {
				'pt-BR': 'Constelações',
			},
			items: [
				{
					label: '仙女座',
					translations: {
						'pt-BR': 'Andrômeda',
					},
					slug: 'constellations/andromeda',
				},
				{
					label: '天蝎座',
					translations: {
						'pt-BR': 'Escorpião',
					},
					slug: 'constellations/scorpius',
				},
			],
		},
	],
});
```

浏览巴西葡萄牙语文档将生成以下侧边栏:

<SidebarPreview
	config={[
		{
			label: 'Constelação',
			items: [
				{ label: 'Andrômeda', link: '' },
				{ label: 'Escorpião', link: '' },
			],
		},
	]}
/>

### 通过内部链接实现国际化

默认情况下,[内部链接](#内部链接)将从 frontmatter 自动使用翻译页面的标题:

```js {9-10}
starlight({
	sidebar: [
		{
			label: '星座',
			translations: {
				'pt-BR': 'Constelações',
			},
			items: [
				{ slug: 'constellations/andromeda' },
				{ slug: 'constellations/scorpius' },
			],
		},
	],
});
```

浏览巴西葡萄牙语文档将生成以下侧边栏:

<SidebarPreview
	config={[
		{
			label: 'Constelações',
			items: [
				{ label: 'Andrômeda', link: '' },
				{ label: 'Escorpião', link: '' },
			],
		},
	]}
/>

在多语言网站中,`slug` 的值不会包含 URL 的语言部分。
例如,如果页面位于 `en/intro` 和 `pt-br/intro`,则在配置侧边栏时,slug 为 `intro`。

### 通过徽章实现国际化

对于[徽章](#徽章),`text` 属性可以是字符串,而对于多语言网站,文本属性则可以是具有每个不同区域设置值的对象。
使用对象形式时,键必须是 [BCP-47](https://www.w3.org/International/questions/qa-choosing-language-tags) 标签(例如 `en`、`ar` 或 `zh-CN`):

```js {11-16}
starlight({
	sidebar: [
		{
			label: '星座',
			translations: {
				'pt-BR': 'Constelações',
			},
			items: [
				{
					slug: 'constellations/andromeda',
					badge: {
						text: {
							'zh-CN': '新',
							'pt-BR': 'Novo',
						},
					},
				},
			],
		},
	],
});
```

浏览巴西葡萄牙语文档将生成以下侧边栏:

<SidebarPreview
	config={[
		{
			label: 'Constelações',
			items: [
				{
					label: 'Andrômeda',
					link: '',
					badge: { text: 'Novo', variant: 'default' },
				},
			],
		},
	]}
/>

## 折叠分组

链接分组可以通过将 `collapsed` 属性设置为 `true` 来默认折叠。

```js {5-6}
starlight({
	sidebar: [
		{
			label: '星座',
			// 默认折叠分组
			collapsed: true,
			items: ['constellations/andromeda', 'constellations/orion'],
		},
	],
});
```

以上配置将生成以下侧边栏:

<SidebarPreview
	config={[
		{
			label: '星座',
			collapsed: true,
			items: [
				{ label: '仙女座', link: '' },
				{ label: '猎户座', link: '' },
			],
		},
	]}
/>

[自动生成的分组](#自动生成的分组) 遵循其父级分组的 `collapsed` 值:

```js {5-6}
starlight({
	sidebar: [
		{
			label: '星座',
			// 默认折叠分组及其自动生成的子组。
			collapsed: true,
			autogenerate: { directory: 'constellations' },
		},
	],
});
```

以上配置将生成以下侧边栏:

<SidebarPreview
	config={[
		{
			label: '星座',
			collapsed: true,
			items: [
				{ label: '船底座', link: '' },
				{ label: '半人马座', link: '' },
				{
					label: 'seasonal',
					collapsed: true,
					items: [{ label: '仙女座', link: '' }],
				},
			],
		},
	]}
/>

这个行为可以通过定义 `autogenerate.collapsed` 属性来覆盖。

```js {5-7} "collapsed: true"
starlight({
	sidebar: [
		{
			label: '星座',
			// 不折叠 "星座" 分组,但折叠其自动生成的子组。
			collapsed: false,
			autogenerate: { directory: 'Constellations', collapsed: true },
		},
	],
});
```

以上配置将生成以下侧边栏:

<SidebarPreview
	config={[
		{
			label: '星座',
			items: [
				{ label: '船底座', link: '' },
				{ label: '半人马座', link: '' },
				{
					label: 'seasonal',
					collapsed: true,
					items: [{ label: '仙女座', link: '' }],
				},
			],
		},
	]}
/>


================================================
FILE: docs/src/content/docs/zh-cn/guides/site-search.mdx
================================================
---
title: 全站搜索
description: 了解 Starlight 的内置全站搜索功能和如何自定义它们。
tableOfContents:
  maxHeadingLevel: 4
---

import { Tabs, TabItem, Steps } from '@astrojs/starlight/components';

默认情况下,Starlight 站点提供了基于 [Pagefind](https://pagefind.app/) 的全文搜索,它是一个为静态站点的快速且低带宽的搜索工具。

启用搜索不需要配置。构建并部署你的站点,然后使用网站顶部的搜索栏来查找内容。

## 从搜索结果中隐藏内容

### 排除一个页面

要从搜索结果中排除一个页面,需要将 [`pagefind: false`](/zh-cn/reference/frontmatter/#pagefind) 添加到页面的 frontmatter 中:

```md title="src/content/docs/不被索引.md" ins={3}
---
title: 要从搜索结果中隐藏的内容
pagefind: false
---
```

### 排除页面中的一部分

Pagefind 会忽略带有 [`data-pagefind-ignore`](https://pagefind.app/docs/indexing/#removing-individual-elements-from-the-index) 属性的元素内的内容。

在下面的示例中,第一个段落将显示在搜索结果中,但 `<div>` 的内容不会:

```md title="src/content/docs/部分索引.md" ins="data-pagefind-ignore"
---
title: 部分索引的页面
---

这段文字会被搜索到。

<div data-pagefind-ignore>

这段文字不会被搜索到。

</div>
```

## 其他搜索供应商

### Algolia DocSearch

如果你加入了 [Algolia 的 DocSearch 计划](https://docsearch.algolia.com/)并且想要用它来替代 Pagefind,你可以使用官方的 Starlight DocSearch 插件。

<Steps>

1. 安装 `@astrojs/starlight-docsearch`:

   <Tabs syncKey="pkg">

   <TabItem label="npm">

   ```sh
   npm install @astrojs/starlight-docsearch
   ```

   </TabItem>

   <TabItem label="pnpm">

   ```sh
   pnpm add @astrojs/starlight-docsearch
   ```

   </TabItem>

   <TabItem label="Yarn">

   ```sh
   yarn add @astrojs/starlight-docsearch
   ```

   </TabItem>

   </Tabs>

2. 把 DocSearch 加到 `astro.config.mjs` 里你的 Starlight [`plugins`](/zh-cn/reference/configuration/#plugins) 配置中,并传入你的 Algolia `appId`、`apiKey` 和 `indexName`:

   ```js ins={4,10-16}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';
   import starlightDocSearch from '@astrojs/starlight-docsearch';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: '使用 DocSearch 的网站',
   			plugins: [
   				starlightDocSearch({
   					appId: 'YOUR_APP_ID',
   					apiKey: 'YOUR_SEARCH_API_KEY',
   					indexName: 'YOUR_INDEX_NAME',
   				}),
   			],
   		}),
   	],
   });
   ```

</Steps>

像这样更新配置后,你站点上的搜索栏将会打开一个 Algolia 的模态框而不是默认的搜索模态框。

#### DocSearch 配置

Starlight DocSearch 插件支持通过下面这些内联的选项来自定义 DocSearch 组件:

- `maxResultsPerGroup`:限制每个搜索组所显示的结果数。默认值为 `5`。
- `disableUserPersonalization`:阻止 DocSearch 将用户的最近搜索和收藏夹保存到本地存储。默认值为 `false`。
- `insights`:启用 Algolia Insights 插件并将搜索事件发送到你的 DocSearch 索引。默认值为 `false`。
- `searchParameters`:一个可用于自定义 [Algolia 搜索参数](https://www.algolia.com/doc/api-reference/search-api-parameters/)的对象。

##### 其他 DocSearch 选项

为了将函数选项(如 `transformItems()` 或 `resultsFooterComponent()`)传递给 DocSearch 组件,需要创建一个单独的配置文件。

<Steps>

1. 创建一个 TypeScript 文件,导出 DocSearch 选项。

   ```ts
   // src/config/docsearch.ts
   import type { DocSearchClientOptions } from '@astrojs/starlight-docsearch';

   export default {
   	appId: 'YOUR_APP_ID',
   	apiKey: 'YOUR_SEARCH_API_KEY',
   	indexName: 'YOUR_INDEX_NAME',
   	getMissingResultsUrl({ query }) {
   		return `https://github.com/algolia/docsearch/issues/new?title=${query}`;
   	},
   	// ...
   } satisfies DocSearchClientOptions;
   ```

2. 在 `astro.config.mjs` 中将你的配置文件路径传递给 Starlight DocSearch 插件。

   ```js {11-13}
   // astro.config.mjs
   import { defineConfig } from 'astro/config';
   import starlight from '@astrojs/starlight';
   import starlightDocSearch from '@astrojs/starlight-docsearch';

   export default defineConfig({
   	integrations: [
   		starlight({
   			title: '使用 DocSearch 的网站',
   			plugins: [
   				starlightDocSearch({
   					clientOptionsModule: './src/config/docsearch.ts',
   				}),
   			],
   		}),
   	],
   });
   ```

</Steps>

请参阅 [DocSearch JavaScript 客户端 API 参考](https://docsearch.algolia.com/docs/api/) 以了解所有支持的选项。

#### 翻译 DocSearch UI

DocSearch 默认只提供了英语 UI 文本。
使用 Starlight 内置的[国际化系统](/zh-cn/guides/i18n/#翻译-starlight-的-ui)来添加你的语言的模态框 UI 的翻译。

<Steps>

1. 在 `src/content.config.ts` 中给 Starlight 的 `i18n` 内容集合定义添加 DocSearch schema:

   ```js ins={5} ins=/{ extend: .+ }/
   // src/content.config.ts
   import { defineCollection } from 'astro:content';
   import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
   import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';
   import { docSearchI18nSchema } from '@astrojs/starlight-docsearch/schema';

   export const collections = {
   	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
   	i18n: defineCollection({
   		loader: i18nLoader(),
   		schema: i18nSchema({ extend: docSearchI18nSchema() }),
   	}),
   };
   ```

2. 在 `src/content/i18n/` 里的 JSON 文件中添加翻译。

   这些是 DocSearch 使用的英文默认文本:

   ```json title="src/content/i18n/en.json"
   {
   	"docsearch.searchBox.resetButtonTitle": "Clear the query",
   	"docsearch.searchBox.resetButtonAriaLabel": "Clear the query",
   	"docsearch.searchBox.cancelButtonText": "Cancel",
   	"docsearch.searchBox.cancelButtonAriaLabel": "Cancel",
   	"docsearch.searchBox.searchInputLabel": "Search",

   	"docsearch.startScreen.recentSearchesTitle": "Recent",
   	"docsearch.startScreen.noRecentSearchesText": "No recent searches",
   	"docsearch.startScreen.saveRecentSearchButtonTitle": "Save this search",
   	"docsearch.startScreen.removeRecentSearchButtonTitle": "Remove this search from history",
   	"docsearch.startScreen.favoriteSearchesTitle": "Favorite",
   	"docsearch.startScreen.removeFavoriteSearchButtonTitle": "Remove this search from favorites",

   	"docsearch.errorScreen.titleText": "Unable to fetch results",
   	"docsearch.errorScreen.helpText": "You might want to check your network connection.",

   	"docsearch.footer.selectText": "to select",
   	"docsearch.footer.selectKeyAriaLabel": "Enter key",
   	"docsearch.footer.navigateText": "to navigate",
   	"docsearch.footer.navigateUpKeyAriaLabel": "Arrow up",
   	"docsearch.footer.navigateDownKeyAriaLabel": "Arrow down",
   	"docsearch.footer.closeText": "to close",
   	"docsearch.footer.closeKeyAriaLabel": "Escape key",
   	"docsearch.footer.searchByText": "Search by",

   	"docsearch.noResultsScreen.noResultsText": "No results for",
   	"docsearch.noResultsScreen.suggestedQueryText": "Try searching for",
   	"docsearch.noResultsScreen.reportMissingResultsText": "Believe this query should return results?",
   	"docsearch.noResultsScreen.reportMissingResultsLinkText": "Let us know."
   }
   ```

</Steps>


================================================
FILE: docs/src/content/docs/zh-cn/index.mdx
================================================
---
title: Starlight 🌟 使用 Astro 构建文档站点
head:
  - tag: title
    content: Starlight 🌟 使用 Astro 构建文档站点
description: Starlight 帮助你使用 Astro 构建漂亮、高性能的文档网站。
template: splash
editUrl: false
lastUpdated: false
banner:
  content: |
    更新到 Astro 5?
    <a href="https://github.com/withastro/starlight/releases/tag/%40astrojs/starlight%400.30.0">
      了解如何升级
    </a>
hero:
  title: Starlight <br/> 使你的文档闪耀夺目
  tagline: 快速、易用、易于访问 —— 构建卓越文档网站所需的一切。
  image:
    file: ~/assets/hero-star.webp
  actions:
    - text: 开始使用
      icon: right-arrow
      link: /zh-cn/getting-started/
    - text: 在 GitHub 上查看
      icon: external
      variant: minimal
      link: https://github.com/withastro/starlight
---

import { CardGrid, Card } from '@astrojs/starlight/components';
import AboutAstro from '~/components/about-astro.astro';
import TestimonialGrid from '~/components/testimonial-grid.astro';
import Testimonial from '~/components/testimonial.astro';

<CardGrid stagger>
	<Card title="令人愉悦的文档" icon="open-book">
		包括:网站导航、搜索、国际化、SEO、易于阅读的排版、代码高亮、深色模式等等。
	</Card>
	<Card title="由 Astro 提供支持" icon="rocket">
		充分利用 Astro 的全部功能和性能。使用你最喜欢的 Astro 集成和库扩展
		Starlight。
	</Card>
	<Card title="Markdown、Markdoc 和 MDX" icon="document">
		带上你最喜欢的标记语言。Starlight 为你提供了内置的 frontmatter 验证和
		TypeScript 类型安全。
	</Card>
	<Card title="带上你自己的 UI 组件" icon="puzzle">
		Starlight 作为一个不依赖于框架的完整文档解决方案。可以使用
		React、Vue、Svelte、Solid 等进行扩展。
	</Card>
</CardGrid>

<TestimonialGrid title="看看人们怎么说">
  <Testimonial
    name="Rachel"
    handle="rachelnabors"
    cite="https://twitter.com/astrodotbuild/status/1724934718745915558"
  >
    Astro 团队通过他们的 Starlight 项目彻底改变了文档处理的方式,现在你可以一站式获取所有功能。
  </Testimonial>
  <Testimonial
    name="Flavio"
    handle="flaviocopes"
    cite="https://twitter.com/flaviocopes/status/1738237658717905108"
  >
    Astro 官方的入门工具 Starlight 是一款非常令人难以置信的构建文档网站的工具。
  </Testimonial>
  <Testimonial
    name="Tomek"
    handle="sulco"
    cite="https://twitter.com/sulco/status/1735610348730802342"
  >
    Starlight 是我们极力推荐的出色开发体验(DX)的典范:其速度、便捷性和对细节的关注令人鼓舞。它负责技术和外观,让你可以专注于你的内容。👏

    StackBlitz 团队对它赞不绝口!

  </Testimonial>
  <Testimonial
    name="Roberto"
    handle="RmeetsH"
    cite="https://twitter.com/RmeetsH/status/1735783992018760090"
  >
    Starlight 对我来说是一个改变游戏规则的工具,让我能够专注于内容创作。

    它直观的设计不仅简化了我的工作流程,还缩短了开源开发者的入门时间。

  </Testimonial>
  <Testimonial
    name="Joel"
    handle="jhooks"
    cite="https://twitter.com/jhooks/status/1727405160547418405"
  >
    花了更多时间使用 Starlight 来创建课程构建文档,目前感觉非常不错。有很多巧妙的设计,可以专注于使用  Markdown 进行写作,而不必费心调整网站。
  </Testimonial>
  <Testimonial
    name="Rick"
    handle="rick_viscomi"
    cite="https://twitter.com/rick_viscomi/status/1665867447910510593"
  >
    开始尝试使用 Starlight。不得不说,我对其开箱即用的性能感到非常印象深刻。

    💯💯💯💯

  </Testimonial>
  <Testimonial
    name="Nicolas"
    handle="beaussan"
    cite="https://twitter.com/beaussan/status/1735625189583466893"
  >
    Starlight 是开始文档编写的最佳方式,结合了 Astro 的强大和速度,以及来自 Starlight 的工具,简直是天作之合。

    我已经使用它一段时间了,一直都很喜欢!

  </Testimonial>
  <Testimonial
    name="Sylwia"
    handle="SylwiaVargas"
    cite="https://x.com/SylwiaVargas/status/1726556825741578286"
  >
    我在上一份工作中使用了 Starlight,非常喜欢它。拥有出色的组件、直观的设计,以及非常响应的社区(每当有人需要帮助时,他们会很快提供支持或告诉你解决方法)。非常愉快的体验。
  </Testimonial>
  <Testimonial
    name="Lou Cyx"
    handle="loucyx"
    cite="https://elk.zone/m.webtoo.ls/@loucyx@mastodon.social/111587380021362284"
  >
    由于 Starlight 的帮助,我的 monorepo 站点上的文档看起来比以往任何时候都更好。它非常易于使用,同时不失Astro 的所有强大功能。感谢你们的努力工作!
  </Testimonial>
  <Testimonial
    name="BowTiedWebReaper"
    handle="BowTiedWebReapr"
    cite="https://twitter.com/BowTiedWebReapr/status/1735633399501697517"
  >
    Starlight 是我用于文档编写的首选工具。相比于使用其他需要子域的工具,它使得将文档添加到我现有的 Astro产品网站变得非常容易。
  </Testimonial>
  <Testimonial
    name="Jeff"
    handle="J_Everhart383"
    cite="https://twitter.com/J_Everhart383/status/1691900590048292908"
  >
    我一直在重建 WPEngine Atlas 平台文档。相信我,Starlight 拥有一切你需要打造 A+ 文档平台的要素。🙌
  </Testimonial>
  <Testimonial
    name="Chloe"
    handle="solelychloe"
    cite="https://twitter.com/solelychloe/status/1695115277602628082"
  >
    试试 Starlight 吧!

    我在我的几个网站上使用它,效果非常棒。

  </Testimonial>
</TestimonialGrid>

<AboutAstro title="由以下提供支持">
Astro 是专为速度而设计的全能 Web 框架。
从任何地方获取你的内容并在任何地方部署,所有这些都由你喜欢的 UI 组件和库提供支持。

[了解 Astro](https://astro.build/)

</AboutAstro>


================================================
FILE: docs/src/content/docs/zh-cn/manual-setup.mdx
================================================
---
title: 手动配置
description: 了解如何手动配置 Starlight 以将其添加到现有的 Astro 项目中。
---

import { Tabs, TabItem } from '@astrojs/starlight/components';

创建新的 Starlight 站点的最快方法是使用 `create astro`,如[入门指南](/zh-cn/getting-started/#创建一个新项目)所示。
如果你想将 Starlight 添加到现有的 Astro 项目中,本指南将解释如何操作。

## 设置 Starlight

要遵循本指南,你需要一个现有的 Astro 项目。

### 添加 Starlight 集成

Starlight 是一个 [Astro 集成](https://docs.astro.build/zh-cn/guides/integrations-guide/)。通过在项目的根目录中运行 `astro add` 命令将其添加到你的站点中:

<Tabs syncKey="pkg">
    <TabItem label="npm">
        ```sh
        npx astro add starlight
        ```

    </TabItem>
    <TabItem label="pnpm">
        ```sh
        pnpm astro add starlight
        ```
    </TabItem>
    <TabItem label="Yarn">
        ```sh
        yarn astro add starlight
        ```
    </TabItem>

</Tabs>

这将安装所需的依赖项,并将 Starlight 添加到 Astro 配置文件中的 `integrations` 数组中。

### 配置集成

Starlight 集成在 `astro.config.mjs` 文件中配置。

添加一个 `title` 以开始:

```js ins={8}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: '我的令人愉悦的文档网站',
		}),
	],
});
```

在 [Starlight 配置参考](/zh-cn/reference/configuration/) 中查找所有可用选项。

### 配置内容集合

Starlight 是建立在 Astro 的[内容集合](https://docs.astro.build/zh-cn/guides/content-collections/)之上的,这些集合在 `src/content.config.ts` 文件中配置。

创建或更新内容配置文件,添加一个使用 Starlight 的 `docsLoader` 和 `docsSchema` 的 `docs` 集合:

```js ins={3-4,7}
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
};
```

Starlight 也支持 [`legacy.collections` 标志](https://docs.astro.build/zh-cn/reference/legacy-flags/),其中集合使用旧版的内容集合实现处理。
这对于你有一个现有的 Astro 项目,目前无法对集合进行任何更改以使用加载器的情况非常有用。

### 添加内容

现在 Starlight 已经配置好了,是时候添加一些内容了!

创建一个 `src/content/docs/` 目录,并从添加一个 `index.md` 文件开始。
这将是你的新站点的首页:

```md
---
# src/content/docs/index.md
title: 我的文档
description: 通过 Starlight 构建的文档网站,了解有关我的项目的更多信息。
---

欢迎来到我的项目!
```

Starlight 使用基于文件的路由,这意味着 `src/content/docs/` 中的每个 Markdown、MDX 或 Markdoc 文件都将变成你站点上的一个页面。前置元数据(上面示例中的 `title` 和 `description` 字段)可以更改每个页面的显示方式。在 [frontmatter 指南](/zh-cn/reference/frontmatter/) 中查看所有可用选项。

## 现有站点的提示

如果你有一个现有的 Astro 项目,你可以使用 Starlight 快速地为你的站点添加一个文档部分。

### 在子路径中使用 Starlight

要在子路径中添加所有 Starlight 页面,请将所有文档内容放在 `src/content/docs/` 的子目录中。

例如,如果 Starlight 页面都应该以 `/guides/` 开头,请将内容添加到 `src/content/docs/guides/` 目录中:

import { FileTree } from '@astrojs/starlight/components';

<FileTree>

- src/
  - content/
    - docs/
      - **guides/**
        - guide.md
        - index.md
  - pages/
- astro.config.mjs

</FileTree>

在将来,我们计划更好地支持这种用例,以避免在 `src/content/docs/` 中需要额外的嵌套目录。

### 结合 SSR 使用 Starlight

要启用 SSR,请按照 Astro 文档中的 [“按需渲染适配器”](https://docs.astro.build/zh-cn/guides/on-demand-rendering/) 指南将服务器适配器添加到你的 Starlight 项目中。

无论项目的输出模式如何,Starlight 生成的文档页面都默认为预渲染。要选择不对 Starlight 页面进行预渲染,请将 [`prerender` 配置选项](/zh-cn/reference/configuration/#prerender) 设置为 `false`。


================================================
FILE: docs/src/content/docs/zh-cn/reference/configuration.mdx
================================================
---
title: 配置参考
description: Starlight 支持的所有配置选项的概述。
---

## 配置 `starlight` 集成

Starlight 是在 [Astro](https://astro.build) web 框架之上构建的集成。你可以在 `astro.config.mjs` 配置文件中配置你的项目:

```js
// astro.config.mjs
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: '我的令人愉快的文档网站',
		}),
	],
});
```

你可以将以下选项传递给`starlight`集成。

### `title` (必填)

**类型:** `string | Record<string, string>`

设置你的网站标题。将用于元数据和浏览器标签标题。

这个值可以是一个字符串,或者对于多语言网站,可以是一个包含每种不同语言值的对象。
当使用对象形式时,键必须是 BCP-47 标签(例如 `en`,`ar` 或 `zh-CN`):

```ts
starlight({
	title: {
		en: 'My delightful docs site',
		de: 'Meine bezaubernde Dokumentationsseite',
	},
});
```

### `description`

**类型:** `string`

设置你的网站描述。如果页面的 frontmatter 中没有设置 `description`,则在 `<meta name="description">` 标签中与搜索引擎共享元数据。

### `logo`

**类型:** [`LogoConfig`](#logoconfig)

在导航栏中设置一个 logo 图片,与网站标题一起显示或替代网站标题。你可以设置单个 `src` 属性,也可以为 `light` 和 `dark` 设置单独的图像源。

```js
starlight({
	logo: {
		src: './src/assets/my-logo.svg',
	},
});
```

#### `LogoConfig`

```ts
type LogoConfig = { alt?: string; replacesTitle?: boolean } & (
	| { src: string }
	| { light: string; dark: string }
);
```

### `tableOfContents`

**类型:** `false | { minHeadingLevel?: number; maxHeadingLevel?: number; }`  
**默认值:** `{ minHeadingLevel: 2, maxHeadingLevel: 3; }`

配置每个页面右侧显示的目录。默认情况下,`<h2>` 和 `<h3>` 标题将包含在此目录中。

### `editLink`

**类型:** `{ baseUrl: string }`

通过设置你要使用的 base URL 来启用 “编辑此页” 链接。最终链接将是`editLink.baseUrl` +当前页面路径。例如,要启用在 GitHub 上编辑`withastro/starlight` 仓库中的页面:

```js
starlight({
	editLink: {
		baseUrl: 'https://github.com/withastro/starlight/edit/main/',
	},
});
```

使用此配置,`/introduction` 页面将具有指向 `https://github.com/withastro/starlight/edit/main/src/content/docs/introduction.md` 的编辑链接。

### `sidebar`

**类型:** [`SidebarItem[]`](#sidebaritem)

配置你的网站的侧边栏导航项目。

侧边栏是包含链接和链接组的数组。
除了使用 `slug` 的项目之外,每个项目都必须具有 `label` 和以下属性之一:

- `link` — 指向特定 URL 的单个链接,例如 `'/home'` 或 `'https://example.com'`。

- `slug` — 指向一个内部页面的引用, 例如 `'guides/getting-started'`。

- `items` — 包含更多侧边栏链接和子组的数组。

- `autogenerate` — 指定要从中自动生成一组链接的文档目录的对象。

内部链接也可以被指定为字符串,而不是带有 `slug` 属性的对象。

```js
starlight({
	sidebar: [
		// 标记为“Home”的单个链接项。
		{ label: 'Home', link: '/' },
		// 一个标记为“Start Here”的组,其中包含四个链接。
		{
			label: 'Start Here',
			items: [
				// 在内部链接中使用 `slug`。
				{ slug: 'intro' },
				{ slug: 'installation' },
				// 或者使用内部链接的简易写法。
				'tutorial',
				'next-steps',
			],
		},
		// 一个链接到参考目录中所有页面的组。
		{
			label: 'Reference',
			autogenerate: { directory: 'reference' },
		},
	],
});
```

#### 排序

自动生成的侧边栏组按文档名字母顺序排序。例如,从 `astro.md` 生成的页面将显示在 `starlight.md`页面上方。

#### 折叠组

默认情况下,链接组是展开的。你可以通过将组的 `collapsed` 属性设置为 `true` 来更改此行为。

自动生成的子组默认情况下会遵守其父组的 `collapsed` 属性。设置 `autogenerate.collapsed` 属性以覆盖此行为。

```js {5,13}
sidebar: [
  // 一个折叠的链接组。
  {
    label: 'Collapsed Links',
    collapsed: true,
    items: ['intro', 'next-steps'],
  },
  // 一个展开的组,其中包含折叠的自动生成的子组。
  {
    label: 'Reference',
    autogenerate: {
      directory: 'reference',
      collapsed: true,
    },
  },
],
```

#### 翻译标签

如果你的网站是多语言的,每个项目的 `label` 被认为是默认语言。你可以设置一个 `translations` 属性来为你支持的其他语言提供标签:

```js {5,9,14}
sidebar: [
  // 一个侧边栏示例,其中的标签被翻译成简体中文。
  {
    label: 'Start Here',
    translations: { 'zh-CN': '从这里开始' },
    items: [
      {
        label: 'Getting Started',
        translations: { 'zh-CN': '开始使用' },
        link: '/getting-started',
      },
      {
        label: 'Project Structure',
        translations: { 'zh-CN': '项目结构' },
        link: '/structure',
      },
    ],
  },
],
```

#### `SidebarItem`

```ts
type SidebarItem =
	| string
	| ({
			translations?: Record<string, string>;
			badge?: string | BadgeConfig;
	  } & (
			| {
					// 链接
					link: string;
					label: string;
					attrs?: Record<string, string | number | boolean | undefined>;
			  }
			| {
					// 内部链接
					slug: string;
					label?: string;
					attrs?: Record<string, string | number | boolean | undefined>;
			  }
			| {
					// 链接组
					label: string;
					items: SidebarItem[];
					collapsed?: boolean;
			  }
			| {
					// 自动生成的链接组
					label: string;
					autogenerate: { directory: string; collapsed?: boolean };
					collapsed?: boolean;
			  }
	  ));
```

#### `BadgeConfig`

```ts
interface BadgeConfig {
	text: string;
	variant?: 'note' | 'tip' | 'caution' | 'danger' | 'success' | 'default';
	class?: string;
}
```

### `locales`

**类型:** <code>\{ \[dir: string\]: [LocaleConfig](#localeconfig) \}</code>

为你的网站设置支持的 `locales` 来[配置国际化(i18n)](/zh-cn/guides/i18n/)。

每个条目都应该使用该语言文件保存的目录作为 key。

```js
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
	integrations: [
		starlight({
			title: 'My Site',
			// 为这个网站设置英语作为默认语言。
			defaultLocale: 'en',
			locales: {
				// 英文文档在 `src/content/docs/en/`
				en: {
					label: 'English',
				},
				// 简体中文文档在 `src/content/docs/zh-cn/`
				'zh-cn': {
					label: '简体中文',
					lang: 'zh-CN',
				},
				// 阿拉伯文档在 `src/content/docs/ar/`
				ar: {
					label: 'العربية',
					dir: 'rtl',
				},
			},
		}),
	],
});
```

#### `LocaleConfig`

```ts
interface LocaleConfig {
	label: string;
	lang?: string;
	dir?: 'ltr' | 'rtl';
}
```

你可以为每个语言设置以下选项:

##### `label` (必填)

**类型:** `string`

要向用户显示的此语言的标签,例如在语言切换器中。大多数情况下,你会希望这是该语言的名称,因为该语言的用户希望阅读它,例如`"English"`,`"العربية"`,或者 `"简体中文"`。

##### `lang`

**类型:** `string`

此语言的 BCP-47 标签,例如`"en"`,`"ar"`,或者 `"zh-CN"`。如果未设置,则默认使用该语言的目录名称。 如果没有找到特定于区域的翻译,带有区域子标签的语言标签(例如`pt-BR`或`en-US`)将使用内置的 UI 翻译作为其基本语言。

##### `dir`

**类型:** `'ltr' | 'rtl'`

这种语言的写作方向; `"ltr"`表示从左到右(默认值)或`"rtl"`表示从右到左。

#### root locale

你可以通过设置 `root` locale 来提供不带 `/lang/` 目录的默认语言:

```js {3-6}
starlight({
	locales: {
		root: {
			label: 'English',
			lang: 'en',
		},
		fr: {
			label: 'Français',
		},
	},
});
```

举例,这允许你将 `/getting-started/` 作为英语路由提供,并将 `/fr/getting-started/` 作为等效的法语页面。

### `defaultLocale`

**类型:** `string`

设置此站点的默认语言。
该值应该与你的 [`locales`](#locales) 对象的键之一匹配。
(如果你的默认语言是你的[root locale](#root-locale),你可以跳过这一步。)

默认语言将用于在缺少翻译时提供回退内容。

### `social`

**类型:** <code>{`Array<{ label: string; icon: `}[StarlightIcon](/zh-cn/reference/icons/){`; href: string }>`}</code>

可选的社交媒体账户详情。
每个条目将显示为网站 header 中的图标链接。

```js
starlight({
	social: [
		{ icon: 'codeberg', label: 'Codeberg', href: 'https://codeberg.org/knut' },
		{ icon: 'discord', label: 'Discord', href: 'https://astro.build/chat' },
		{ icon: 'github', label: 'GitHub', href: 'https://github.com/withastro' },
		{ icon: 'gitlab', label: 'GitLab', href: 'https://gitlab.com/delucis' },
		{ icon: 'mastodon', label: 'Mastodon', href: 'https://m.webtoo.ls/@astro' },
	],
});
```

### `customCss`

**类型:** `string[]`

提供 CSS 文件来自定义你的 Starlight 网站的外观和风格。

支持相对于项目根目录的本地 CSS 文件,例如 `'./src/custom.css'`,以及你安装为 npm 模块的 CSS,例如 `'@fontsource/roboto'`。

```js
starlight({
	customCss: ['./src/custom-styles.css', '@fontsource/roboto'],
});
```

### `markdown`

**类型:** `{ headingLinks?: boolean }`  
**默认值:** `{ headingLinks: true }`

配置 Starlight 的 Markdown 处理。

#### `headingLinks`

**类型:** `boolean`  
**默认值:** `true`

控制标题是否渲染为可点击的锚点链接。

```js
starlight({
	markdown: {
    // 禁用 Starlight 的可点击标题锚点链接。
		headingLinks: false,
	},
}),
```

### `expressiveCode`

**类型:** `StarlightExpressiveCodeOptions | boolean`  
**默认值:** `true`

Starlight 使用 [Expressive Code](https://expressive-code.com) 来渲染代码块,并添加对代码示例的高亮支持,向代码块添加文件名等。
请参阅 [“代码块”指南](/zh-cn/guides/authoring-content/#代码块) 以了解如何在你的 Markdown 和 MDX 内容中使用 Expressive Code 语法。

你可以通过在 Starlight 的 `expressiveCode` 选项中设置任何标准的 [Expressive Code 配置选项](https://expressive-code.com/reference/configuration/) 以及一些特定于 Starlight 的属性。比如,设置 Expressive Code 的 `styleOverrides` 选项来覆盖默认的 CSS。这样就可以自定义代码块,比如给你的代码块添加圆角:

```js ins={2-4}
starlight({
	expressiveCode: {
		styleOverrides: { borderRadius: '0.5rem' },
	},
});
```

如果你想禁用 Expressive Code,请在 Starlight 配置中设置 `expressiveCode: false`:

```js ins={2}
starlight({
	expressiveCode: false,
});
```

除了标准的 Expressive Code 选项之外,你还可以在 `expressiveCode` 配置中设置以下 Starlight 特定属性,以进一步自定义代码块的主题行为:

#### `themes`

**类型:** `Array<string | ThemeObject | ExpressiveCodeTheme>`  
**默认值:** `['starlight-dark', 'starlight-light']`

设置用于代码块样式的主题。有关支持的主题格式的详细信息,请参阅 [Expressive Code `themes` 文档](https://expressive-code.com/guides/themes/)。

Starlight 默认使用 Sarah Drasner 的 [Night Owl 主题](https://github.com/sdras/night-owl-vscode-theme) 的深色和浅色变体。

如果你提供至少一个深色和一个浅色主题,Starlight 将自动将活动代码块主题与当前网站主题保持同步。
使用 [`useStarlightDarkModeSwitch`](#usestarlightdarkmodeswitch) 选项配置此行为。

#### `useStarlightDarkModeSwitch`

**类型:** `boolean`  
**默认值:** `true`

当设置为 `true` 时,代码块会在网站主题更改时自动在浅色和深色主题之间切换。
当设置为 `false` 时,你必须手动添加 CSS 来处理多个主题之间的切换。

:::note
当设置 `themes` 时,你必须为 Starlight 暗黑模式切换提供至少一个深色和一个浅色主题。
:::

#### `useStarlightUiThemeColors`

**类型:** `boolean`  
**默认值:** 如果未设置 `themes`,则为 `true`,否则为 `false`

当设置为 `true` 时,Starlight 的 CSS 变量用于代码块 UI 元素的颜色(背景、按钮、阴影等),与[网站颜色主题](/zh-cn/guides/css-and-tailwind/#主题)相匹配。
当设置为 `false` 时,这些元素使用活动语法高亮主题提供的颜色。

:::note
当使用自定义主题并将其设置为 `true` 时,你必须提供至少一个深色和一个浅色主题,以确保正确的颜色对比度。
:::

### `pagefind`

**类型:** <code>boolean | <a href="#pagefindoptions">PagefindOptions</a></code>  
**默认值:** `true`

配置 Starlight 的默认站点搜索 provider [Pagefind](https://pagefind.app/)。

将其设置为 `false` 以禁用使用 Pagefind 索引你的网站。这也将隐藏默认的搜索 UI。

当 [`prerender`](#prerender) 选项设置为 `false` 时,无法启用 Pagefind。

将 `pagefind` 设置为对象,以配置 Pagefind 搜索客户端。

- 查看 Pagefind 文档中的 [“自定义 Pagefind 的结果排序”](https://pagefind.app/docs/ranking/),了解如何使用 `pagefind.ranking` 选项来控制搜索结果排序的计算。
- 查看 Pagefind 文档中的 [“搜索多个站点”](https://pagefind.app/docs/multisite/),了解如何使用 `pagefind.mergeIndex` 选项来控制如何跨多个站点搜索。

#### `PagefindOptions`

```ts
interface PagefindOptions {
	ranking?: {
		pageLength?: number;
		termFrequency?: number;
		termSaturation?: number;
		termSimilarity?: number;
	};
	indexWeight?: number;
	mergeIndex?: Array<{
		bundlePath: string;
		indexWeight?: number;
		basePath?: string;
		baseUrl?: string;
		mergeFilter?: Record<string, string | string[]>;
		language?: string;
		ranking?: {
			pageLength?: number;
			termFrequency?: number;
			termSaturation?: number;
			termSimilarity?: number;
		};
	}>;
}
```

### `prerender`

**类型:** `boolean`  
**默认值:** `true`

定义 Starlight 页面是应预渲染为静态 HTML 还是由 [SSR 适配器](https://docs.astro.build/zh-cn/guides/on-demand-rendering/) 按需渲染。

默认情况下,Starlight 页面是预渲染的。
如果你正在使用 SSR 适配器并希望按需渲染 Starlight 页面,请设置为 `prerender: false`。

### `head`

**类型:** [`HeadConfig[]`](#headconfig)

添加自定义标签到你的 Starlight 网站的 `<head>` 中。
可以用于添加分析和其他第三方脚本和资源。

```js
starlight({
	head: [
		// 示例:添加 Fathom 分析脚本标签。
		{
			tag: 'script',
			attrs: {
				src: 'https://cdn.usefathom.com/script.js',
				'data-site': 'MY-FATHOM-ID',
				defer: true,
			},
		},
	],
});
```

在 `head` 中的条目会直接转换为 HTML 元素,并不会经过 Astro 的 [脚本](https://docs.astro.build/zh-cn/guides/client-side-scripts/#脚本处理) 或 [样式](https://docs.astro.build/zh-cn/guides/styling/#在-astro-进行设计) 处理。如果你需要导入本地资源,如脚本、样式或图片,请[重写 Head 组件](/zh-cn/guides/overriding-components/#复用内置组件)。

#### `HeadConfig`

```ts
interface HeadConfig {
	tag: string;
	attrs?: Record<string, string | boolean | undefined>;
	content?: string;
}
```

### `lastUpdated`

**类型:** `boolean`  
**默认值:** `false`

控制页脚是否显示页面上次更新的时间。

默认情况下,此功能依赖于你的存储库的 Git 历史记录,并且在某些执行[浅克隆](https://git-scm.com/docs/git-clone#Documentation/git-clone.txt---depthltdepthgt)的部署平台上可能不准确。页面可以使用 [`lastUpdated` frontmatter 字段](/zh-cn/reference/frontmatter/#lastupdated)覆盖此设置或基于 Git 的日期。

### `pagination`

**类型:** `boolean`  
**默认值:** `true`

定义页脚是否应包含上一页和下一页的链接。

页面可以使用 [`prev`](/zh-cn/reference/frontmatter/#prev) 和 [`next`](/zh-cn/reference/frontmatter/#next) frontmatter 字段覆盖此设置或链接文本和/或 URL。

### `favicon`

**类型:** `string`  
**默认值:** `'/favicon.svg'`

设置网站的默认 favicon 的路径,它应该位于 `public/` 目录中,并且是一个有效的(`.ico`,`.gif`,`.jpg`,`.png` 或 `.svg`)图标文件。

```js
starlight({
  favicon: '/images/favicon.svg',
}),
```

如果你需要设置其他变体或回退的 favicon,你可以使用 [`head` 选项](#head)添加标签:

```js
starlight({
	favicon: '/images/favicon.svg',
	head: [
		// 为 Safari 添加 ICO favicon 回退。
		{
			tag: 'link',
			attrs: {
				rel: 'icon',
				href: '/images/favicon.ico',
				sizes: '32x32',
			},
		},
	],
});
```

### `titleDelimiter`

**类型:** `string`  
**默认值:** `'|'`

设置在页面的 `<title>` 标签里页面标题和网站标题之间的分隔符,它会显示在浏览器标签上。

默认情况下,每个页面的 `<title>` 都是 `页面标题 | 网站标题`。
举例,本页面的标题是“配置参考”,本站点的标题是“Starlight”,所以本页面的 `<title>` 是“配置参考 | Starlight”。

### `disable404Route`

**类型:** `boolean`  
**默认值:** `false`

禁用注入 Starlight 的默认 [404 页面](https://docs.astro.build/zh-cn/basics/astro-pages/#自定义-404-错误页面)。要在项目中使用自定义的 `src/pages/404.astro` 路由,请将此选项设置为 `true`。

### `routeMiddleware`

**类型:** `string | string[]`

提供路由中间件的路径,可以修改 Starlight 处理数据的方式。
这些文件路径不能与 [Astro 的中间件](https://docs.astro.build/zh-cn/guides/middleware/) 冲突。

在 [路由数据指南](/zh-cn/guides/route-data/#自定义路由数据) 中查看有关如何创建路由中间件的详细信息。

### `components`

**类型:** `Record<string, string>`

提供组件的路径来覆盖 Starlight 的默认实现。

```js
starlight({
	components: {
		SocialLinks: './src/components/MySocialLinks.astro',
	},
});
```

要查阅所有可覆盖的组件,请参阅[覆盖参考](/zh-cn/reference/overrides/)。

### `plugins`

**类型:** [`StarlightPlugin[]`](/zh-cn/reference/plugins/#快速-api-参照)

使用自定义插件扩展 Starlight。
插件将更改应用到你的项目中,以修改或添加 Starlight 的功能。

访问 [插件 showcase](/zh-cn/resources/plugins/#插件) 查看可用插件列表。

```js
starlight({
	plugins: [starlightPlugin()],
});
```

有关创建自己的插件的详细信息,请参阅[插件参考](/zh-cn/reference/plugins/)。

### `credits`

**类型:** `boolean`  
**默认值:** `false`

启用在你的网站页脚显示 “基于 Starlight 构建” 的链接。

```js
starlight({
	credits: true,
});
```


================================================
FILE: docs/src/content/docs/zh-cn/reference/frontmatter.md
================================================
---
title: Frontmatter 参考
description: Starlight 支持的默认 frontmatter 字段的概述。
---

你可以通过设置 frontmatter 中的值来自定义 Starlight 中的单个 Markdown 和 MDX 页面。例如,一个常规页面可能会设置 `title` 和 `description` 字段:

```md {3-4}
---
# src/content/docs/example.md
title: 关于此项目
description: 了解更多关于此项目的信息。
---

欢迎来到关于页面!
```

## Frontmatter 字段

### `title` (必填)

**类型:** `string`

你必须为每个页面提供标题。它将显示在页面顶部、浏览器标签中和页面元数据中。

### `description`

**类型:** `string`

页面描述用于页面元数据,将被搜索引擎和社交媒体预览捕获。

### `slug`

**类型:** `string`

覆盖页面的slug。有关更多详细信息,请参阅 Astro文档中的 [ "定义自定义 ID"](https://docs.astro.build/zh-cn/guides/content-collections/#定义自定义-id) 部分。

### `editUrl`

**类型:** `string | boolean`

覆盖[全局 `editLink` 配置](/zh-cn/reference/configuration/#editlink)。设置为 false 可禁用特定页面的 “编辑页面” 链接,或提供此页面内容可编辑的备用 URL。

### `head`

**类型:** [`HeadConfig[]`](/zh-cn/reference/configuration/#headconfig)

你可以使用 `<head>` frontmatter 字段向页面的`<head>`添加其他标签。这意味着你可以将自定义样式、元数据或其他标签添加到单个页面。类似于[全局 `head` 选项](/zh-cn/reference/configuration/#head)。

```md
---
# src/content/docs/example.md
title: 关于我们
head:
  # 使用自定义 <title> 标签
  - tag: title
    content: 自定义关于我们页面标题
---
```

### `tableOfContents`

**类型:** `false | { minHeadingLevel?: number; maxHeadingLevel?: number; }`

覆盖[全局 `tableOfContents` 配置](/zh-cn/reference/configuration/#tableofcontents)。自定义要包含的标题级别,或设置为 `false` 以在此页面上隐藏目录。

```md
---
# src/content/docs/example.md
title: 目录中只有 H2 的页面
tableOfContents:
  minHeadingLevel: 2
  maxHeadingLevel: 2
---
```

```md
---
# src/content/docs/example.md
title: 没有目录的页面
tableOfContents: false
---
```

### `template`

**类型:** `'doc' | 'splash'`  
**默认值:** `'doc'`

为页面选择布局模板。
页面默认使用 `'doc'` 布局。
设置为 `'splash'` 以使用没有任何侧边栏的更宽的布局,该布局专为落地页设计。

### `hero`

**类型:** [`HeroConfig`](#heroconfig)

添加一个 hero 组件到页面顶部。与 `template: splash` 配合使用效果更佳。

例如,此配置显示了一些常见选项,包括从你的仓库加载图像。

```md
---
# src/content/docs/example.md
title: 我的主页
template: splash
hero:
  title: '我的项目: Stellar Stuff Sooner'
  tagline: 把你的东西带到月球上,眨眼间又回来。
  image:
    alt: 一个闪闪发光、色彩鲜艳的标志
    file: ../../assets/logo.png
  actions:
    - text: 告诉我更多
      link: /getting-started/
      icon: right-arrow
    - text: 在 GitHub 上查看
      link: https://github.com/astronaut/my-project
      icon: external
      variant: minimal
      attrs:
        rel: me
---
```

你可以在浅色和深色模式下显示不同版本的 hero 图像。

```md
---
# src/content/docs/example.md
hero:
  image:
    alt: 一个闪闪发光、色彩鲜艳的 logo
    dark: ../../assets/logo-dark.png
    light: ../../assets/logo-light.png
---
```

#### `HeroConfig`

```ts
interface HeroConfig {
  title?: string;
  tagline?: string;
  image?:
    | {
        // 你的仓库中的图像的相对路径。
        file: string;
        // 使图像对辅助技术可访问的 Alt 文本
        alt?: string;
      }
    | {
        // 使用深色模式的图像的相对路径。
        dark: string;
        // 使用浅色模式的图像的相对路径。
        light: string;
        // 使图像对辅助技术可访问的 Alt 文本
        alt?: string;
      }
    | {
        // 用于图像插槽的原始 HTML 。
        // 可以是自定义的 `<img>` 标签或内联的 `<svg>`。
        html: string;
      };
  actions?: Array<{
    text: string;
    link: string;
    variant?: 'primary' | 'secondary' | 'minimal';
    icon?: string;
    attrs?: Record<string, string | number | boolean>;
  }>;
}
```

### `banner`

**类型:** `{ content: string }`

在此页面顶部显示公告横幅。

`content` 的值可以包含链接或其他内容的 HTML。
例如,此页面显示了一个横幅,其中包含指向 `example.com` 的链接。

```md
---
# src/content/docs/example.md
title: 带有横幅的页面
banner:
  content: |
    我们刚刚发布了一下非常酷的东西!
    <a href="https://example.com">点击查看!</a>
---
```

### `lastUpdated`

**类型:** `Date | boolean`

覆盖[全局 `lastUpdated` 配置](/zh-cn/reference/configuration/#lastupdated)。如果指定了日期,它必须是有效的 [YAML 时间戳](https://yaml.org/type/timestamp.html),并将覆盖存储在 Git 历史记录中的此页面的日期。

```md
---
# src/content/docs/example.md
title: 带有自定义更新日期的页面
lastUpdated: 2022-08-09
---
```

### `prev`

**类型:** `boolean | string | { link?: string; label?: string }`

覆盖[全局 `pagination` 配置](/zh-cn/reference/configuration/#pagination)。如果指定了字符串,则将替换生成的链接文本;如果指定了对象,则将同时覆盖链接和文本。

```md
---
# src/content/docs/example.md
# 隐藏上一页链接
prev: false
---
```

```md
---
# src/content/docs/example.md
# 将上一页链接更改为“继续教程”
prev: 继续教程
---
```

```md
---
# src/content/docs/example.md
# 同时覆盖上一页的链接和文本
prev:
  link: /unrelated-page/
  label: 一个不相关的页面
---
```

### `next`

**类型:** `boolean | string | { link?: string; label?: string }`

和 [`prev`](#prev) 一样,但是用于下一页链接。

```md
---
# src/content/docs/example.md
# 隐藏下一页链接
next: false
---
```

### `pagefind`

**类型:** `boolean`  
**默认值:** `true`

设置此页面是否应包含在 [Pagefind](https://pagefind.app/) 搜索索引中。设置为 `false` 以从搜索结果中排除页面:

```md
---
# src/content/docs/example.md
# 在搜索索引中隐藏此页面
pagefind: false
---
```

### `draft`

**类型:** `boolean`  
**默认值:** `false`

设置此页面是否应被视为草稿,并且不包含在 [生产版本](https://docs.astro.build/zh-cn/reference/cli-reference/#astro-build)。设置为 `true` 可将页面标记为草稿,并使其仅在开发过程中可见。

```md
---
# src/content/docs/example.md
# 从生产版本中排除此页面
draft: true
---
```

因为草稿页面并不包含在构建输出中,所以你无法使用 [slug](/zh-cn/guides/sidebar/#内部链接) 直接将草稿页面添加到网页中。目录中用于 [自动生成侧边栏](/zh-cn/guides/sidebar/#自动生成的分组) 的草稿页面在生产版本中自动排除。

### `sidebar`

**类型:** [`SidebarConfig`](#sidebarconfig)

在使用自动生成的链接分组时,控制如何在[侧边栏](/zh-cn/reference/configuration/#sidebar)中显示此页面。

#### `SidebarConfig`

```ts
interface SidebarConfig {
  label?: string;
  order?: number;
  hidden?: boolean;
  badge?: string | BadgeConfig;
  attrs?: Record<string, string | number | boolean | undefined>;
}
```

#### `label`

**类型:** `string`  
**默认值:** 页面 [`title`](#title-必填)

在自动生成的链接组中显示时,设置侧边栏中此页面的标签。

```md
---
# src/content/docs/example.md
title: 关于此项目
sidebar:
  label: About
---
```

#### `order`

**类型:** `number`

当对链接组进行自动生成排序时,控制此页面的顺序。
数字越小,链接组中显示得越高。

```md
---
# src/content/docs/example.md
title: 要首先显示的页面
sidebar:
  order: 1
---
```

#### `hidden`

**类型:** `boolean`  
**默认值:** `false`

防止此页面包含在自动生成的侧边栏组中。

```md
---
# src/content/docs/example.md
title: 从自动生成的侧边栏中隐藏的页面
sidebar:
  hidden: true
---
```

#### `badge`

**类型:** <code>string | <a href="/zh-cn/reference/configuration/#badgeconfig">BadgeConfig</a></code>

当在自动生成的链接组中显示时,在侧边栏中为页面添加徽章。

当使用字符串时,徽章将显示为默认的强调色。可选择的,传递一个 [`BadgeConfig` 对象](/zh-cn/reference/configuration/#badgeconfig) ,其中包含 `text`、`variant` 和 `class` 字段,可以自定义徽章。

```md
---
# src/content/docs/example.md
title: 带有徽章的页面
sidebar:
  # 使用与你的网站的强调色相匹配的默认类型
  badge: 新增
---
```

```md
---
# src/content/docs/example.md
title: 带有徽章的页面
sidebar:
  badge:
    text: 实验性
    variant: caution
---
```

#### `attrs`

**类型:** `Record<string, string | number | boolean | undefined>`

给自动生成的侧边栏分组的链接添加的 HTML 属性。

```md
---
# src/content/docs/example.md
title: 新标签页中打开页面
sidebar:
  # 在新标签页中打开页面
  attrs:
    target: _blank
---
```

## 自定义 frontmatter schema

Starlight 的 `docs` 内容集合的 frontmatter schema 在 `src/content.config.ts` 中使用 `docsSchema()` 辅助函数进行配置:

```ts {4,7}
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
  docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
};
```

了解更多关于内容集合模式的信息,请参阅 Astro 文档中的 [“定义集合模式”](https://docs.astro.build/zh-cn/guides/content-collections/#定义集合模式schema) 部分。

`docsSchema()` 采用以下选项:

### `extend`

**类型:** Zod schema 或者返回 Zod schema 的函数  
**默认值:** `z.object({})`

通过在 `docsSchema()` 选项中设置 `extend` 来使用其他字段扩展 Starlight 的 schema。
值应该是一个 [Zod schema](https://docs.astro.build/zh-cn/guides/content-collections/#用-zod-定义数据类型)。

在下面的示例中,我们为 `description` 提供了一个更严格的类型,使其成为必填项,并添加了一个新的可选的 `category` 字段:

```ts {10-15}
// src/content.config.ts
import { defineCollection, z } from 'astro:content';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
  docs: defineCollection({
    loader: docsLoader(),
    schema: docsSchema({
      extend: z.object({
        // 将内置字段设置为必填项。
        description: z.string(),
        // 将新字段添加到 schema 中。
        category: z.enum(['tutorial', 'guide', 'reference']).optional(),
      }),
    }),
  }),
};
```

要利用 [Astro `image()` 辅助函数](https://docs.astro.build/zh-cn/guides/images/#内容集合中的图像),请使用返回 schema 扩展的函数:

```ts {10-15}
// src/content.config.ts
import { defineCollection, z } from 'astro:content';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
  docs: defineCollection({
    loader: docsLoader(),
    schema: docsSchema({
      extend: ({ image }) => {
        return z.object({
          // 添加一个必须解析为本地图像的字段。
          cover: image(),
        });
      },
    }),
  }),
};
```


================================================
FILE: docs/src/content/docs/zh-cn/reference/icons.mdx
================================================
---
title: 图标参考
description: Starlight 中所有可用图标的概述。
---

Starlight 提供了一组内置图标,你可以使用 `<Icon>` 组件在内容中显示这些图标。

## 使用图标

可以使用 [`<Icon>`](/zh-cn/components/icons/) 组件来显示图标。
图标也常用于其他组件,例如 [卡片](/zh-cn/components/cards/) 或 [hero actions](/zh-cn/reference/frontmatter/#hero) 等设置。

## `StarlightIcon` 类型

使用 `StarlightIcon` TypeScript 类型来引用 [Starlight 的内置图标的名称](#所有图标)。

```ts {2} /icon: (StarlightIcon)/
// src/icon.ts
import type { StarlightIcon } from '@astrojs/starlight/types';

function getIconLabel(icon: StarlightIcon) {
	// …
}
```

## 所有图标

下面显示了所有可用图标,包括它们对应名称的列表。单击图标将其名称复制到剪贴板。

import IconsList from '~/components/icons-list.astro';

<IconsList labels={{ copied: '已复制!' }} />


================================================
FILE: docs/src/content/docs/zh-cn/reference/overrides.md
================================================
---
title: 重写参考
description: Starlight 支持重写的组件以及组件参数的概述。
tableOfContents:
  maxHeadingLevel: 4
---

你可以通过在 Starlight 的 [`components`](/zh-cn/reference/configuration/#components) 配置选项中提供替代组件的路径来替换掉 (即重写) Starlight 的内置组件。
本页面列出了所有可被重写的组件和它们默认实现的 GitHub 链接。

在[重写组件指南](/zh-cn/guides/overriding-components/)中了解更多。

## 组件

### 头部

这些组件在每个页面的 `<head>` 元素内渲染。
它们应只包含[允许在 `<head>` 中使用的元素](https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/head#相关链接)。

#### `Head`

**默认组件:** [`Head.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Head.astro)

在每个页面的 `<head>` 元素内渲染的组件。

重写此组件应作为最后手段。
如果可能,请优先使用 [`head` 配置项](/zh-cn/reference/configuration/#head),[`head` frontmatter 字段](/zh-cn/reference/frontmatter/#head),或者使用 [路由数据中间件](/zh-cn/guides/route-data/#自定义路由数据) 来自定义默认组件渲染的路由数据。

#### `ThemeProvider`

**默认组件:** [`ThemeProvider.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/ThemeProvider.astro)

在 `<head>` 内渲染的用于提供暗色/亮色主题支持的组件。
默认实现包括一个内联脚本和一个 `<template>`,该脚本在 [`<ThemeSelect />`](#themeselect) 中使用该模板。

---

### 无障碍

#### `SkipLink`

**默认组件:** [`SkipLink.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/SkipLink.astro)

在 `<body>` 内渲染的第一个元素,它链接到主页面内容以实现无障碍访问。
默认实现默认为隐藏状态,只有在用户使用键盘通过 tab 键聚焦到它时才会显示。

---

### 布局

这些组件负责在不同的断点 (breakpoints) 上布局 Starlight 的组件、管理视图。
重写这些组件会有很大的复杂性。
如果可能,请优先重写较低级别的组件。

#### `PageFrame`

**默认组件:** [`PageFrame.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/PageFrame.astro)  
**命名插槽:** `header`, `sidebar`

包在绝大部分页面内容外的布局组件。
默认实现提供了头部—侧边栏—主内容的布局,并包含 `header` 和 `sidebar` 命名插槽以及主内容的默认插槽。
它还渲染了 [`<MobileMenuToggle />`](#mobilemenutoggle) 以支持在小 (移动) 视口 (viewports) 上切换侧边栏导航。

#### `MobileMenuToggle`

**默认组件:** [`MobileMenuToggle.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MobileMenuToggle.astro)

在 [`<PageFrame>`](#pageframe) 内渲染的负责在小 (移动) 视口上切换侧边栏导航的组件。

#### `TwoColumnContent`

**默认组件:** [`TwoColumnContent.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/TwoColumnContent.astro)  
**命名插槽:** `right-sidebar`

包在主内容列和右侧栏 (目录) 外的布局组件。
默认实现实现了在单列、小视口布局和两列、较大视口布局之间的切换。

---

### 导航

这些组件渲染 Starlight 的顶部导航栏。

#### `Header`

**默认组件:** [`Header.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Header.astro)

在每个页面顶部显示的导航栏组件。
默认实现显示了 [`<SiteTitle />`](#sitetitle)、[`<Search />`](#search)、[`<SocialIcons />`](#socialicons)、[`<ThemeSelect />`](#themeselect) 和 [`<LanguageSelect />`](#languageselect)。

#### `SiteTitle`

**默认组件:** [`SiteTitle.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/SiteTitle.astro)

在导航栏开头渲染的组件,用于渲染站点标题。
默认实现包含在 Starlight 配置中定义的 logo 的渲染逻辑。

#### `Search`

**默认组件:** [`Search.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Search.astro)

用于渲染 Starlight 搜索 UI 的组件。
默认实现包含在导航栏中的按钮和在点击时显示搜索模态框以及加载 [Pagefind UI](https://pagefind.app/) 的代码。

当 [`pagefind`](/zh-cn/reference/configuration/#pagefind) 被禁用时,默认的搜索组件不会被渲染。
然而,如果你重写了 `Search`,你的自定义组件将总是被渲染,即使 `pagefind` 配置选项是 `false`。
这允许你在禁用 Pagefind 时为其他搜索提供商添加 UI。

#### `SocialIcons`

**默认组件:** [`SocialIcons.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/SocialIcons.astro)

在导航栏中渲染的组件,用于渲染社交图标链接。
默认实现使用 Starlight 配置中的 [`social`](/zh-cn/reference/configuration/#social) 选项来渲染图标和链接。

#### `ThemeSelect`

**默认组件:** [`ThemeSelect.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/ThemeSelect.astro)

在导航栏中渲染的组件,用于允许用户选择深浅主题偏好。

#### `LanguageSelect`

**默认组件:** [`LanguageSelect.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/LanguageSelect.astro)

在导航栏中渲染的组件,用于允许用户切换到不同的语言。

---

### 全局侧边栏

Starlight 的全局侧边栏包含了主站点导航。
在较窄的视口上,它会隐藏在下拉菜单中。

#### `Sidebar`

**默认组件:** [`Sidebar.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Sidebar.astro)

在页面内容之前渲染的包含全局导航的组件。
默认实现在足够宽的视口上显示为侧边栏,在小 (移动) 视口上显示为下拉菜单。
它还渲染了 [`<MobileMenuFooter />`](#mobilemenufooter) 以在移动菜单中显示额外的项目。

#### `MobileMenuFooter`

**默认组件:** [`MobileMenuFooter.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MobileMenuFooter.astro)

在移动下拉菜单最底部中渲染的组件。
默认实现渲染了 [`<ThemeSelect />`](#themeselect) 和 [`<LanguageSelect />`](#languageselect)。

---

### 页面侧边栏

Starlight 的页面侧边栏负责显示当前页面的子标题的目录。
在较窄的视口上,它会缩为一个固定的下拉菜单。

#### `PageSidebar`

**默认组件:** [`PageSidebar.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/PageSidebar.astro)

在页面内容之前渲染的包含目录的组件。
默认实现渲染了 [`<TableOfContents />`](#tableofcontents) 和 [`<MobileTableOfContents />`](#mobiletableofcontents)。

#### `TableOfContents`

**默认组件:** [`TableOfContents.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/TableOfContents.astro)

在较宽的视口上渲染当前页面的目录的组件。

#### `MobileTableOfContents`

**默认组件:** [`MobileTableOfContents.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MobileTableOfContents.astro)

在小 (移动) 视口上渲染当前页面的目录的组件。

---

### 内容

这些组件在页面主内容列中渲染。

#### `Banner`

**默认组件:** [`Banner.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Banner.astro)

横幅 (Banner) 组件在每个页面的顶部渲染。
默认实现使用页面的 [`banner`](/zh-cn/reference/frontmatter/#banner) frontmatter 值来决定是否渲染。

#### `ContentPanel`

**默认组件:** [`ContentPanel.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/ContentPanel.astro)

包在页面主内容列中的段落外的布局组件。

#### `PageTitle`

**默认组件:** [`PageTitle.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/PageTitle.astro)

包含当前页面的 `<h1>` 元素的组件。

自定义实现应确保在 `<h1>` 元素上设置 `id="_top"`,就像默认实现中一样。

#### `DraftContentNotice`

**默认组件:** [`DraftContentNotice.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/DraftContentNotice.astro)

在开发过程中,当当前页面被标记为草稿时,向用户显示的通知。

#### `FallbackContentNotice`

**默认组件:** [`FallbackContentNotice.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/FallbackContentNotice.astro)

在本页面当前语言没有翻译时显示给用户的通知。
仅在多语言站点中使用。

#### `Hero`

**默认组件:** [`Hero.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Hero.astro)

当设置了 frontmatter 中的 [`hero`](/zh-cn/reference/frontmatter/#hero) 时在页面顶部渲染的组件。
默认实现显示了一个大标题、标语、动作链接 (call-to-action links) 和可选的图片。

#### `MarkdownContent`

**默认组件:** [`MarkdownContent.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/MarkdownContent.astro)

在页面主内容列中渲染 Markdown 内容的组件。
默认实现为 Markdown 内容提供了基本的样式。

Markdown 内容样式也暴露在 `@astrojs/starlight/style/markdown.css` 中,并且作用域限制在 `.sl-markdown-content` CSS 类中。

---

### 页脚

这些组件在页面主内容列的底部渲染。

#### `Footer`

**默认组件:** [`Footer.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Footer.astro)

页脚 (Footer) 组件在每个页面的底部渲染。
默认实现显示了 [`<LastUpdated />`](#lastupdated)、[`<Pagination />`](#pagination) 和 [`<EditLink />`](#editlink)。

#### `LastUpdated`

**默认组件:** [`LastUpdated.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/LastUpdated.astro)

在页脚中渲染的组件,用于显示最后更新日期。

#### `EditLink`

**默认组件:** [`EditLink.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/EditLink.astro)

在页脚中渲染的组件,用于显示指向页面编辑地址的链接。

#### `Pagination`

**默认组件:** [`Pagination.astro`](https://github.com/withastro/starlight/blob/main/packages/starlight/components/Pagination.astro)

在页脚中渲染的组件,用于显示上一页和下一页的导航箭头。


================================================
FILE: docs/src/content/docs/zh-cn/reference/plugins.md
================================================
---
title: 插件参考
description: Starlight 的插件 API 的概述
tableOfContents:
  maxHeadingLevel: 4
---

Starlight 插件可以自定义 Starlight 的配置、UI 和行为,同时也易于共享和重用。
本参考页面记录了插件可以使用的 API。

在 [配置参考](/zh-cn/reference/configuration/#plugins) 中了解更多关于使用 Starlight 插件的内容。
或者访问 [插件 showcase](/zh-cn/resources/plugins/#插件) 来查看可用插件的列表。

## 快速 API 参照

一个 Starlight 插件的形状如下。
请参阅下面的不同属性和钩子参数的详细信息。

<!-- prettier-ignore-start -->
```ts
interface StarlightPlugin {
  name: string;
  hooks: {
    'i18n:setup'?: (options: {
       injectTranslations: (
         translations: Record<string, Record<string, string>>
       ) => void;
     }) => void | Promise<void>;
    'config:setup': (options: {
      config: StarlightUserConfig;
      updateConfig: (newConfig: StarlightUserConfig) => void;
      addIntegration: (integration: AstroIntegration) => void;
      addRouteMiddleware: (config: { entrypoint: string; order?: 'pre' | 'post' | 'default' }) => void;
      astroConfig: AstroConfig;
      command: 'dev' | 'build' | 'preview';
      isRestart: boolean;
      logger: AstroIntegrationLogger;
      useTranslations: (lang: string) => I18nT;
      absolutePathToLang: (path: string) => string;
    }) => void | Promise<void>;
  };
}
```
<!-- prettier-ignore-end -->

## `name`

**类型:** `string`

一个插件必须提供一个描述它的唯一名字。该名字会在[输出与本插件有关的日志消息](#logger)时使用,并且可能被其他插件用于检测此插件是否存在。

## `hooks`

钩子是 Starlight 在特定时机调用的插件函数。

要获取钩子的参数类型,请使用 `HookParameters` 工具类型并传入钩子名称。
在下面的例子中,`options` 参数被类型化为与 `config:setup` 钩子传递的参数匹配:

```ts
import type { HookParameters } from '@astrojs/starlight/types';

function configSetup(options: HookParameters['config:setup']) {
  options.useTranslations('en');
}
```

### `i18n:setup`

当 Starlight 初始化时会调用插件国际化设置函数。
`i18n:setup` 钩子可以用于注入翻译字符串,以便插件可以支持不同的语言环境。这些翻译字符串可以通过 [`useTranslations()`](#usetranslations) 在 `config:setup` 钩子中使用,也可以在 UI 组件中通过 [`Astro.locals.t()`](/zh-cn/guides/i18n/#使用-ui-翻译) 使用。

`i18n:setup` 钩子会传入以下选项:

#### `injectTranslations`

**类型:** `(translations: Record<string, Record<string, string>>) => void`

一个回调函数,用于添加或更新 Starlight 的 [本地化 API](/zh-cn/guides/i18n/#使用-ui-翻译) 中使用的翻译字符串。

在下面的例子中,一个插件为名为 `myPlugin.doThing` 的自定义 UI 字符串注入翻译字符串,用于 `en` 和 `fr` 语言环境:

```ts {6-13} /(injectTranslations)[^(]/
// plugin.ts
export default {
  name: 'plugin-with-translations',
  hooks: {
    'i18n:setup'({ injectTranslations }) {
      injectTranslations({
        en: {
          'myPlugin.doThing': 'Do the thing',
        },
        fr: {
          'myPlugin.doThing': 'Faire le truc',
        },
      });
    },
  },
};
```

要在插件 UI 中使用注入的翻译字符串,请遵循 [“使用 UI 翻译”](/zh-cn/guides/i18n/#使用-ui-翻译) 指南。
如果你需要在插件的 [`config:setup`](#configsetup) 钩子中使用 UI 字符串,可以使用 [`useTranslations()`](#usetranslations) 回调。

插件注入的翻译字符串的类型会自动在用户项目中生成,但当在插件的代码库中工作时还不可用。
要在插件的上下文中类型化 `locals.t` 对象,请在 TypeScript 声明文件中声明以下全局命名空间:

```ts
// env.d.ts
declare namespace App {
  type StarlightLocals = import('@astrojs/starlight').StarlightLocals;
  // 在插件的上下文中定义 `locals.t` 对象。
  interface Locals extends StarlightLocals {}
}

declare namespace StarlightApp {
  // 在 `I18n` 接口中定义额外的插件翻译。
  interface I18n {
    'myPlugin.doThing': string;
  }
}
```

如果你有一个包含你的翻译的对象,你也可以从源文件推断 `StarlightApp.I18n` 接口的类型。

例如,给定以下源文件:

```ts title="ui-strings.ts"
export const UIStrings = {
  en: { 'myPlugin.doThing': 'Do the thing' },
  fr: { 'myPlugin.doThing': 'Faire le truc' },
};
```

以下声明会从源文件中推断类型:

```ts title="env.d.ts"
declare namespace StarlightApp {
  type UIStrings = typeof import('./ui-strings').UIStrings.en;
  interface I18n extends UIStrings {}
}
```

### `config:setup`

插件配置设置函数会在 Starlight 初始化时调用(在 [`astro:config:setup`](https://docs.astro.build/zh-cn/reference/integrations-reference/#astroconfigsetup) 集成钩子期间)。
`config:setup` 钩子可以用于更新 Starlight 配置或添加 Astro 集成。

这个钩子会被传入以下选项:

#### `config`

**类型:** `StarlightUserConfig`

一个用户提供的 [Starlight 配置](/zh-cn/reference/configuration/)的只读副本。
这个配置可能已经被当前插件之前的其他插件更新过了。

#### `updateConfig`

**类型:** `(newConfig: StarlightUserConfig) => void`

一个可以更新用户提供的 [Starlight 配置](/zh-cn/reference/configuration/)的回调函数。
传入你想要覆盖的根级配置键。
要更新嵌套的配置值,你必须提供整个嵌套对象。

要扩展现有的配置选项而不是覆盖它,可以将现有值展开到新值中。
在下面的例子中,通过将 `config.social` 展开到新的 `social` 数组中,向现有配置添加了一个新的 [`social`](/zh-cn/reference/configuration/#social) 媒体账号:

```ts {6-15}
// plugin.ts
export default {
  name: 'add-twitter-plugin',
  hooks: {
    'config:setup'({ config, updateConfig }) {
      updateConfig({
        social: [
          ...config.social,
          {
            icon: 'twitter',
            label: 'Twitter',
            href: 'https://twitter.com/astrodotbuild',
          },
        ],
      });
    },
  },
};
```

#### `addIntegration`

**类型:** `(integration: AstroIntegration) => void`

一个添加插件所需的 [Astro 集成](https://docs.astro.build/zh-cn/reference/integrations-reference/)的回调函数。

在下面的例子中,插件首先检查是否已经配置了 [Astro 的 React 集成](https://docs.astro.build/zh-cn/guides/integrations-guide/react/),如果没有,就使用 `addIntegration()` 来添加它:

```ts {14} "addIntegration,"
// plugin.ts
import react from '@astrojs/react';

export default {
  name: 'plugin-using-react',
  hooks: {
    'config:setup'({ addIntegration, astroConfig }) {
      const isReactLoaded = astroConfig.integrations.find(
        ({ name }) => name === '@astrojs/react'
      );

      // 只在 React 集成没有已经被添加的时候添加它。
      if (!isReactLoaded) {
        addIntegration(react());
      }
    },
  },
};
```

#### `addRouteMiddleware`

**类型:** `(config: { entrypoint: string; order?: 'pre' | 'post' | 'default' }) => void`

一个回调函数,用于向站点添加 [路由中间件处理程序](/zh-cn/guides/route-data/)。

`entrypoint` 属性必须符合插件的中间件文件的模块规范,该文件导出一个 `onRequest` 处理程序。

在下面的例子中,一个名为 `@example/starlight-plugin` 的插件使用 npm 模块规范添加了一个路由中间件:

```js {6-9}
// plugin.ts
export default {
  name: '@example/starlight-plugin',
  hooks: {
    'config:setup'({ addRouteMiddleware }) {
      addRouteMiddleware({
        entrypoint: '@example/starlight-plugin/route-middleware',
      });
    },
  },
};
```

##### 控制执行顺序

默认情况下,插件中间件按插件添加的顺序运行。

如果你需要更精细地控制中间件的执行顺序,可以使用可选的 `order` 属性。
设置 `order: "pre"` 在用户中间件之前运行。
设置 `order: "post"` 在所有其他中间件之后运行。

如果两个插件添加了具有相同 `order` 值的中间件,则先添加的插件将先运行。

#### `astroConfig`

**类型:** `AstroConfig`

一个用户提供的 [Astro 配置](https://docs.astro.build/zh-cn/reference/configuration-reference/)的只读副本。

#### `command`

**类型:** `'dev' | 'build' | 'preview'`

被用于运行 Starlight 的命令:

- `dev` - 项目是用 `astro dev` 运行的
- `build` - 项目是用 `astro build` 运行的
- `preview` - 项目是用 `astro preview` 运行的

#### `isRestart`

**类型:** `boolean`

当开发服务器启动时为 `false`,当触发重新加载时为 `true`。
触发重新加载的常见原因包括用户在开发服务器运行时编辑了他们的 `astro.config.mjs`。

#### `logger`

**类型:** `AstroIntegrationLogger`

一个 [Astro 集成日志记录器](https://docs.astro.build/zh-cn/reference/integrations-reference/#astrointegrationlogger)的实例,你可以用它来写日志。
所有被记录的消息都会带有插件名字的前缀。

```ts {6}
// plugin.ts
export default {
  name: 'long-process-plugin',
  hooks: {
    'config:setup'({ logger }) {
      logger.info('启动一个长流程…');
      // 一些很长的流程…
    },
  },
};
```

上面的例子会记录一条下面这样的消息:

```shell
[long-process-plugin] 启动一个长流程…
```

#### `useTranslations`

**类型:** `(lang: string) => I18nT`

使用 BCP-47 语言标签调用 `useTranslations()` 以生成一个工具函数,该函数提供对特定语言的 UI 字符串的访问。
`useTranslations()` 返回一个等效于 `Astro.locals.t()` API 的工具函数,该 API 在 Astro 组件中可用。
要了解更多可用的 API,请参阅 [“使用 UI 翻译”](/zh-cn/guides/i18n/#使用-ui-翻译) 指南。

```ts {6}
// plugin.ts
export default {
  name: 'plugin-use-translations',
  hooks: {
    'config:setup'({ useTranslations, logger }) {
      const t = useTranslations('zh-CN');
      logger.info(t('builtWithStarlight.label'));
    },
  },
};
```

上面的例子会记录一条包含简体中文语言的默认 UI 字符串的消息:

```shell
[plugin-use-translations] 基于 Starlight 构建
```

#### `absolutePathToLang`

**类型:** `(path: string) => string`

使用绝对文件路径调用 `absolutePathToLang()` 以获取该文件的语言。

这在添加 [remark 或 rehype 插件](https://docs.astro.build/zh-cn/guides/markdown-content/#markdown-plugins) 以处理 Markdown 或 MDX 文件时特别有用。
这些插件使用的 [虚拟文件格式](https://github.com/vfile/vfile) 包括正在处理的文件的 [绝对路径](https://github.com/vfile/vfile#filepath),可以与 `absolutePathToLang()` 一起使用以确定文件的语言。
返回的语言可以与 [`useTranslations()`](#usetranslations) 工具函数一起使用以获取该语言的 UI 字符串。

例如,给定以下 Starlight 配置:

```js
starlight({
  title: 'My Docs',
  defaultLocale: 'en',
  locales: {
    // English docs in `src/content/docs/en/`
    en: { label: 'English' },
    // French docs in `src/content/docs/fr/`
    fr: { label: 'Français', lang: 'fr' },
  },
});
```

一个插件可以使用它的绝对路径来确定文件的语言:

```ts {6-8} /fr/
// plugin.ts
export default {
  name: 'plugin-use-translations',
  hooks: {
    'config:setup'({ absolutePathToLang, useTranslations, logger }) {
      const lang = absolutePathToLang(
        '/absolute/path/to/project/src/content/docs/fr/index.mdx'
      );
      const t = useTranslations(lang);
      logger.info(t('aside.tip'));
    },
  },
};
```

上面的例子会记录一条包含法语语言的默认 UI 字符串的消息:

```shell
[plugin-use-translations] Astuce
```


================================================
FILE: docs/src/content/docs/zh-cn/reference/route-data.mdx
================================================
---
title: 路由数据参考
description: Starlight 的路由数据对象的完整参考文档。
---

Starlight 的路由数据对象包含有关当前页面的信息。请在 [“路由数据”指南](/zh-cn/guides/route-data/) 中了解更多关于 Starlight 的数据模型如何工作的信息。

在 Astro 组件中,从 `Astro.locals.starlightRoute` 访问路由数据:

```astro {4}
---
// src/components/Custom.astro

const { hasSidebar } = Astro.locals.starlightRoute;
---
```

在 [路由中间件](/zh-cn/guides/route-data/#自定义路由数据) 中,从传递给你的中间件函数的上下文对象中访问路由数据:

```ts {5}
// src/routeData.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

export const onRequest = defineRouteMiddleware((context) => {
	const { hasSidebar } = context.locals.starlightRoute;
});
```

## `starlightRoute`

`starlightRoute` 对象具有以下属性:

### `dir`

**类型:** `'ltr' | 'rtl'`

页面书写方向。

### `lang`

**类型:** `string`

此页面区域设置的 BCP-47 语言标记,例如 `en`、`zh-CN` 或 `pt-BR`。

### `locale`

**类型:** `string | undefined`

提供语言的基本路径。对于根语言环境的 slug,返回 `undefined`。

### `siteTitle`

**类型:** `string`

该页面区域设置的站点标题。

### `siteTitleHref`

**类型:** `string`

网站标题的 `href` 属性值,链接回主页,例如 `/`。对于多语言站点,这将包括当前区域设置,例如 `/en/` 或 `/zh-cn/`。

### `slug`

**类型:** `string`

该页面的 slug 由内容文件名生成。

此属性已弃用,并将在 Starlight 的未来版本中删除。通过使用 [Starlight 的 `docsLoader`](/zh-cn/manual-setup/#配置内容集合) 迁移到新的内容层 API,并使用 [`id`](#id) 属性代替。

### `id`

**类型:** `string`

此页面的 slug,或者如果使用 [`legacy.collections`](https://docs.astro.build/zh-cn/reference/legacy-flags/#集合) 标志,则基于内容文件名的此页面的唯一 ID。

### `isFallback`

**类型:** `boolean | undefined`

如果此页面在当前语言中未翻译,并且正在使用来自默认语言环境的回退内容,则为 `true`。
仅在多语言站点中使用。

### `entryMeta`

**类型:** `{ dir: 'ltr' | 'rtl'; lang: string }`

页面内容的区域设置元数据。当页面使用回退内容时,可以与顶级区域设置值不同。

### `entry`

当前页面的 Astro 内容集合条目。
包括当前页面在 `entry.data` 中的 frontmatter 值。

```ts
entry: {
	data: {
		title: string;
		description: string | undefined;
		// 等等
	}
}
```

在 [Astro的集合条目类型参考](https://docs.astro.build/zh-cn/reference/modules/astro-content/#collectionentry) 中了解更多关于此对象结构的信息。

### `sidebar`

**类型:** `SidebarEntry[]`

此页面的网站导航侧边栏条目。

### `hasSidebar`

**类型:** `boolean`

是否在此页面上显示侧边栏。

### `pagination`

**类型:** `{ prev?: Link; next?: Link }`

如果启用了侧边栏,则链接到侧边栏中的上一页和下一页。

### `toc`

**类型:** `{ minHeadingLevel: number; maxHeadingLevel: number; items: TocItem[] } | undefined`

如果启用,则为此页面的目录。

### `headings`

**类型:** `{ depth: number; slug: string; text: string }[]`

从当前页面提取的所有 Markdown 标题的数组。如果要构建一个遵循 Starlight 配置选项的目录组件,请使用 [`toc`](#toc)

### `lastUpdated`

**类型:** `Date | undefined`

JavaScript `Date` 对象,表示启用时此页面上次更新的时间。

### `editUrl`

**类型:** `URL | undefined`

如果启用,则用于编辑此页面的地址的 `URL` 对象。

### `head`

**类型:** [`HeadConfig[]`](/zh-cn/reference/configuration/#headconfig)

包含在当前页面 `<head>` 中的所有标签的数组。包括重要的标签,如 `<title>` 和 `<meta charset="utf-8">`。

## 工具函数

### `defineRouteMiddleware()`

使用 `defineRouteMiddleware()` 工具函数来帮助定义你的路由中间件模块:

```ts "defineRouteMiddleware"
// src/routeData.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';

export const onRequest = defineRouteMiddleware((context) => {
	// ...
});
```

### `StarlightRouteData` 类型

如果您正在编写需要使用 Starlight 路由数据的代码,您可以导入 `StarlightRouteData` 类型来匹配 `Astro.locals.starlightRoute` 的结构。

在下面的例子中,`usePageTitleInTOC()` 函数更新路由数据,以使用当前页面的标题作为目录中第一个项目的标签,替换默认的 “Overview” 标签。
`StarlightRouteData` 类型允许你检查路由数据更改是否有效。

```ts "StarlightRouteData"
// src/route-utils.ts
import type { StarlightRouteData } from '@astrojs/starlight/route-data';

export function usePageTitleInTOC(starlightRoute: StarlightRouteData) {
	const overviewLink = starlightRoute.toc?.items[0];
	if (overviewLink) {
		overviewLink.text = starlightRoute.entry.data.title;
	}
}
```

然后可以从路由中间件调用此函数:

```ts {3,6}
// src/route-middleware.ts
import { defineRouteMiddleware } from '@astrojs/starlight/route-data';
import { usePageTitleInTOC } from './route-utils';

export const onRequest = defineRouteMiddleware((context) => {
	usePageTitleInTOC(context.locals.starlightRoute);
});
```


================================================
FILE: docs/src/content/docs/zh-cn/resources/community-content.mdx
================================================
---
title: 社区内容
description: 发现社区制作的指南、文章和视频,以帮助你学习和构建 Starlight!
---

:::tip[添加你自己的!]
你是否制作过关于 Starlight 的内容?
创建一个 PR 来添加链接到此页面!
:::

import { CardGrid, LinkCard } from '@astrojs/starlight/components';

## 文章和评论

以下是一系列帖子和文章,以了解有关 Starlight 和其他人的经历的更多信息:

<CardGrid>
	<LinkCard
		href="https://devm.io/open-source/starlight-astro"
		title="使用 Starlight 生成静态站点"
		description="“在设计组件时,没有太大或太小的想法”——对 Starlight 负责人 Chris Swithinbank 的采访"
	/>
	<LinkCard
		href="https://frontendatscale.com/blog/hybrid-frontend-architecture/"
		title="使用 Astro 和 Starlight 的混合前端架构"
		description="Maxi Ferreira 和 Ben Holmes 使用 Starlight、TinaCMS 和具有身份验证功能的交互式 API Playground 构建了一个文档站点。"
	/>
	<LinkCard
		href="https://www.olets.dev/posts/comparing-docs-site-builders-vuepress-vs-starlight/"
		title="比较文档网站构建工具:VuePress 与 Starlight"
		description="这两个框架如何衡量?"
	/>
	<LinkCard
		href="https://astro.build/case-studies/wp-engine/"
		title="案例研究:削减开发成本"
		description="WP Engine 是如何通过 Astro 的 Starlight 来降低超过 50% 的开发成本的。"
	/>
	<LinkCard
		href="https://maciekpalmowski.dev/blog/building-a-documentation-site-using-astro-starlight/"
		title="使用 Astro Starlight 来构建文档网站"
		description="Maciek Palmowski 描述了他是如何将 Patchstack 的文档迁移到 Starlight 的。"
	/>
	<LinkCard
		href="https://blog.cloudflare.com/open-source-all-the-way-down-upgrading-our-developer-documentation/"
		title="一路开源"
		description="Cloudflare 是如何使用 Starlight 来升级他们的开发者文档的。"
	/>
	<LinkCard
		href="https://starlight-changelog.netlify.app/"
		title="Starlight Changelog"
		description="在一个精美的页面上查看 @astrojs/starlight 包的所有发布版本。"
	/>
</CardGrid>

## 方案和指南

方案通常是短小的、专注的指南,指导读者完成特定任务的工作示例。通过按照逐步说明完成,方案是向 Starlight 项目添加新功能或行为的绝佳方式!其他指南可能会解释与内容领域相关的概念,例如使用图像或使用 MDX。

浏览由 Starlight 用户维护的社区内容:

<CardGrid>
	<LinkCard
		href="https://www.webpro.nl/scraps/versioned-docs-with-starlight-and-vercel"
		title="Starlight & Vercel 的版本化文档"
		description="为项目的每个主要版本实现单独版本的文档的指南"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-heading-links"
		title="添加指向 Starlight 标题的链接"
		description="使用 rehype 插件共享文档特定部分链接的指南"
	/>
	<LinkCard
		href="https://blog.otterlord.dev/posts/starlight-sponsors/"
		title="将赞助商添加到你的 Starlight 网站"
		description="在文档侧边栏中实现自定义赞助商组件的指南"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-og-images"
		title="将 Open Graph 图像添加到 Starlight"
		description="为你的网页生成社交图像和相应 meta 标签的指南"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-third-party-icon-sets"
		title="在 Starlight 中使用第三方图标集"
		description="使用 unplugin-icons 扩展 Starlight 可用图标选择的指南"
	/>
	<LinkCard
		href="https://hideoo.dev/notes/starlight-custom-html-head"
		title="编辑 Starlight 页面的 HTML head 部分"
		description="了解如何添加常见的 head 内容,例如 Web 分析、字体和脚本"
	/>
	<LinkCard
		href="https://dev.to/mrrobot/publishing-documentation-with-astro-starlight-691"
		title="使用 Astro Starlight 发布文档"
		description="开始使用 Starlight 文档"
	/>
	<LinkCard
		href="https://events-3bg.pages.dev/jotter/starlight/guide/"
		title="启用视图过渡"
		description="通过 Bag of Tricks 的视图过渡支持,获得 SPA 一样的观感"
	/>
	<LinkCard
		href="https://jamcomments.com/posts/structured-data-with-starlight"
		title="向 Starlight 页面添加结构化数据"
		description="了解如何为你的文档页面构建动态的 JSON-LD 结构化数据。"
	/>
	<LinkCard
		href="https://starlight-examples.netlify.app/"
		title="Starlight 示例"
		description="这是一组 StackBlitz 嵌入示例,展示了在 Starlight 文档网站中各种实用的操作方法。"
	/>
</CardGrid>

## 视频内容

发现 Starlight 内容的视频和频道,包括直播和教育内容。

import YouTubeGrid from '~/components/youtube-grid.astro';

### Astro 视频

<YouTubeGrid
	videos={[
		{
			href: 'https://www.youtube.com/watch?v=5u0Ds7wzUeI',
			title: '基于 Astro 的 Starlight',
			description: '观看 Starlight 官方发布视频',
		},
		{
			href: 'https://www.youtube.com/shorts/zjOWezSzd18',
			title: '🌟 1分钟内启动',
			description: '观看 Ben 在不到一分钟的时间内推出新的 Starlight 网站!',
		},
	]}
/>

### 社区视频和直播

<YouTubeGrid
	videos={[
		{
			href: 'https://www.youtube.com/watch?v=sF6UcV3moZg',
			title: '使用 Starlight 和 Astro 构建文档',
			description:
				'观看 Chris 和 Alex 通过 CodingCat.dev 深入研究 Starlight 代码。',
		},
		{
			href: 'https://www.youtube.com/watch?v=sWkkHbwDeQc',
			title: 'Astro Starlight',
			description: '在不到一分钟的时间内介绍 Starlight。',
		},
		{
			href: 'https://www.youtube.com/watch?v=-Ki-1E5gNCk',
			title: 'Astro Starlight 文档模板(构建自定义 app 文档!)',
			description: '在大约 5 分钟内启动并运行新的 Starlight 网站',
		},
		{
			href: 'https://www.youtube.com/watch?v=12o7WxjAxjM',
			title: '使用代理将 Starlight 文档包含在 Next.js 项目中',
			description: '将 Starlight 设置为 Next.js 网站内的子目录项目',
		},
		{
			href: 'https://www.youtube.com/watch?v=5pq80drDrNs',
			title: '我用这个神奇的工具在 30 分钟内重建了 Shadcn 的文档',
			description:
				'在这个视频中,我将介绍 Starlight 的酷炫之处以及为什么你可能想在下一个项目中尝试它。',
		},
		{
			href: 'https://www.youtube.com/watch?v=Q1E4Gkt63ko',
			title:
				'与 Chris Swithinbank 一起试试联动 Astro Starlight 和 emoji-blast ',
			description:
				'Astro Starlight 框架的开发者 Chris 引导我完成了一个全新的 emoji-blast 网站。 🌟 🎇',
		},
	]}
/>


================================================
FILE: docs/src/content/docs/zh-cn/resources/plugins.mdx
================================================
---
title: 插件和集成
description: 发现扩展 Starlight 的插件和集成等社区工具!
sidebar:
  order: 1
---

:::tip[添加你自己的!]
你是否构建过 Starlight 插件或 Starlight 工具?
创建一个 PR 来添加链接到此页面!
:::

## 插件

[插件](/zh-cn/reference/plugins/) 可以自定义 Starlight 的配置、UI 和行为,同时也易于共享和复用。使用 Starlight 团队支持的官方插件和由 Starlight 用户维护的社区插件扩展你的网站。

### 官方插件

<CardGrid>
	<LinkCard
		href="/zh-cn/guides/site-search/#algolia-docsearch"
		title="Algolia DocSearch"
		description="将默认搜索 provider Pagefind 替换为 Algolia DocSearch。"
	/>
</CardGrid>

### 社区插件

<CardGrid>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-links-validator"
		title="starlight-links-validator"
		description="在你的 Starlight 页面中检查损坏的链接"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-typedoc"
		title="starlight-typedoc"
		description=" 使用 TypeDoc 从 TypeScript 生成 Starlight 页面。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-blog"
		title="starlight-blog"
		description="添加一个博客到你的文档网站。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-openapi"
		title="starlight-openapi"
		description="从 OpenAPI/Swagger 规范创建文档页面。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-obsidian"
		title="starlight-obsidian"
		description="将 Obsidian vaults 发布到 Starlight 网站。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-image-zoom"
		title="starlight-image-zoom"
		description="为你的文档图像添加缩放功能。"
	/>
	<LinkCard
		href="https://github.com/lorenzolewis/starlight-utils"
		title="starlight-utils"
		description="通过一系列常用工具扩展 Starlight。"
	/>
	<LinkCard
		href="https://github.com/trueberryless/starlight-view-modes"
		title="starlight-view-modes"
		description="为你的文档网站添加不同的视图模式。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-versions"
		title="starlight-versions"
		description="版本化你的 Starlight 文档页面。"
	/>
	<LinkCard
		href="https://inox-tools.fryuni.dev/star-warp"
		title="star-warp"
		description="为你的文档搜索结果添加曲速引擎。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-heading-badges"
		title="starlight-heading-badges"
		description="添加徽章到你的 Markdown 和 MDX 标题中。"
	/>
	<LinkCard
		href="https://github.com/Fevol/starlight-site-graph"
		title="starlight-site-graph"
		description="在页面的侧边栏中添加一个交互式站点图。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-sidebar-topics"
		title="starlight-sidebar-topics"
		description="将你的文档分成不同的部分,每个部分都有自己的侧边栏。"
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-sidebar-topics-dropdown"
		title="starlight-sidebar-topics-dropdown"
		description="将你的文档页面拆分为多个子页面,并使用侧边栏中的下拉菜单在它们之间切换。"
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-cooler-credit"
		title="starlight-cooler-credit"
		description="为 Starlight 或 Astro 在目录的底部添加一个漂亮的 credit。"
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-contributor-list"
		title="starlight-contributor-list"
		description="在你项目中显示一个包含所有贡献者的列表。"
	/>
	<LinkCard
		href="https://github.com/dragomano/starlight-giscus"
		title="starlight-giscus"
		description="将 Giscus 评论系统添加到你的文档网站。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-videos"
		title="starlight-videos"
		description="通过视频指南和课程增强你的文档。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-kbd"
		title="starlight-kbd"
		description="轻松绑定键盘快捷键。"
	/>
	<LinkCard
		href="https://events-3bg.pages.dev/library/StarlightPlugin/"
		title="starlight-view-transitions"
		description="添加浏览器原生的跨文档视图过渡动画。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-auto-sidebar"
		title="starlight-auto-sidebar"
		description="调整自动生成的侧边栏组。"
	/>
	<LinkCard
		href="https://github.com/delucis/starlight-llms-txt"
		title="starlight-llms-txt"
		description="基于 llmstxt.org 将 llms.txt 添加到你的文档站点。"
	/>
	<LinkCard
		href="https://github.com/trueberryless-org/starlight-toc-overview-customizer"
		title="starlight-toc-overview-customizer"
		description="调整 Starlight的 目录,可自定义概述标题。"
	/>
	<LinkCard
		href="https://delucis.github.io/starlight-markdown-blocks/"
		title="starlight-markdown-blocks"
		description="扩展 Starlight 的 Markdown 旁白语法,增加自定义块类型。"
	/>
	<LinkCard
		href="https://github.com/WindMillCode/starlight-fullview-mode"
		title="starlight-fullview-mode"
		description="收起侧边栏,展开内容以获得全屏体验。"
	/>
	<LinkCard
		href="https://github.com/frostybee/starlight-scroll-to-top"
		title="starlight-scroll-to-top"
		description="在你的文档网站添加一个滚动到顶部的按钮。"
	/>
</CardGrid>

## 社区工具和集成

import { CardGrid, LinkCard } from '@astrojs/starlight/components';

这些社区工具和集成可用于为你的 Starlight 网站添加新功能。

<CardGrid>
	<LinkCard
		href="https://www.feelback.dev/blog/new-astro-starlight-integration/"
		title="FeelBack"
		description="在文档页面中添加用户反馈系统。"
	/>
	<LinkCard
		href="https://github.com/val-town/notion-to-astro"
		title="notion-to-astro"
		description="将 Notion 输出转换为 Astro Starlight 文档"
	/>
	<LinkCard
		href="https://github.com/mattjennings/astro-live-code"
		title="astro-live-code"
		description="将你的 MDX 代码块渲染为交互式组件"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-i18n"
		title="starlight-i18n"
		description="帮助翻译 Starlight 页面的 Visual Studio Code 扩展"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-package-managers"
		title="starlight-package-managers"
		description="快速显示多个包管理器的 npm 相关命令。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/starlight-showcases"
		title="starlight-showcases"
		description="一套 Starlight 组件,用于创建展示页面。"
	/>
	<LinkCard
		href="https://github.com/HiDeoo/generator-starlight-plugin"
		title="@hideoo/starlight-plugin"
		description="一个快速搭建 Starlight 插件的生成器。"
	/>
	<LinkCard
		href="https://github.com/Linkerin/starlight-to-pdf"
		title="starlight-to-pdf"
		description="一个用于将 Starlight 网页转换为 PDF 文件的命令行工具。"
	/>
	<LinkCard
		href="https://github.com/joesaby/astro-plantuml"
		title="astro-plantuml"
		description="在 Markdown 代码块中渲染 PlantUML 内容。"
	/>
</CardGrid>


================================================
FILE: docs/src/content/docs/zh-cn/resources/showcase.mdx
================================================
---
title: Starlight 展示
description: 发现用 Starlight 构建的网站!
sidebar:
  label: 网站展示
---

:::tip[添加你自己的!]
你是否构建过 Starlight 网站?
[创建一个 PR](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md#showcase) 来添加链接到此页面!
:::

## 网站

import ShowcaseSites from '~/components/showcase-sites.astro';

Starlight 已投入生产。 这些是网络上的一些网站:

<ShowcaseSites />

查看所有[在 GitHub 上使用 Starlight 的公共项目仓库](https://github.com/withastro/starlight/network/dependents)。


================================================
FILE: docs/src/content/docs/zh-cn/resources/themes.mdx
================================================
---
title: 主题
description: 使用社区主题为 Starlight 文档添加样式
tableOfContents: false
sidebar:
  order: 2
head:
  - tag: style
    content: |
      body { --sl-content-width: 66.75rem; }
---

import ThemeGrid from '~/components/theme-grid.astro';

主题是一个 Starlight 插件,它通过 [自定义 CSS](/zh-cn/guides/css-and-tailwind/)、[组件重写](/zh-cn/guides/overriding-components/) 或其他新功能来改变网站的视觉外观。

## 社区主题

安装由社区构建的主题,快速自定义网站的外观和风格。

<ThemeGrid
	labels={{
		/** 主题切换按钮的无障碍标签。 */
		legend: '预览',
		/** 深色配色方案变体的无障碍标签。 */
		dark: '深色',
		/** 浅色主题变体的无障碍标签。 */
		light: '浅色',
	}}
	themes={[
		{
			title: 'Starlight Rapide',
			description:
				'Starlight 主题,灵感来源于 Visual Studio Code Vitesse 主题。',
			href: 'https://starlight-theme-rapide.vercel.app/',
			previews: { light: 'rapide-light.png', dark: 'rapide-dark.png' },
		},
		{
			title: 'Starlight Obsidian Theme',
			description: 'Starlight 主题,灵感来源于 Obsidian Publish 网站的风格。',
			href: 'https://fevol.github.io/starlight-theme-obsidian/',
			previews: { light: 'obsidian-light.png', dark: 'obsidian-dark.png' },
		},
		{
			title: 'Catppuccin for Starlight',
			description: '宁静的柔和色调的 Starlight 主题。',
			href: 'https://starlight.catppuccin.com/',
			previews: { light: 'catppuccin-light.png', dark: 'catppuccin-dark.png' },
		},
		{
			title: 'Ion',
			description: '一个时尚、现代的 Starlight 主题。',
			href: 'https://louisescher.github.io/starlight-ion-theme/',
			previews: { light: 'ion-light.png', dark: 'ion-dark.png' },
		},
		{
			title: 'Starlight Black',
			description: 'Starlight 主题,灵感来源于 shadcn 文档。',
			href: 'https://starlight-theme-black.vercel.app/',
			previews: { light: 'black-light.png', dark: 'black-dark.png' },
		},
		{
			title: 'Starlight Flexoki',
			description: '基于 Flexoki 配色方案的温暖友好主题。',
			href: 'https://delucis.github.io/starlight-theme-flexoki/',
			previews: { light: 'flexoki-light.png', dark: 'flexoki-dark.png' },
		},
		{
			title: 'Starlight Nova',
			description: '一个现代而美丽的 Starlight 主题。',
			href: 'https://starlight-theme-nova.pages.dev/',
			previews: { light: 'nova-light.png', dark: 'nova-dark.png' },
		},
		{
			title: 'Starlight NextJS Theme',
			description: 'Starlight 主题,灵感来源于 NextJS 文档。',
			href: 'https://starlight-nextjs-theme.trueberryless.org/',
			previews: { light: 'nextjs-light.png', dark: 'nextjs-dark.png' },
		},
	]}
/>

:::tip[添加你自己的!]
你构建了自己的 Starlight 主题吗?
[创建一个 PR](https://github.com/withastro/starlight/blob/main/CONTRIBUTING.md#themes) 来添加你的主题到此页面!
:::


================================================
FILE: docs/src/content/i18n/de.json
================================================
{
  "component.preview": "Vorschau"
}


================================================
FILE: docs/src/content/i18n/en.json
================================================
{
  "component.preview": "Preview"
}


================================================
FILE: docs/src/content/i18n/fr.json
================================================
{
  "component.preview": "Aperçu"
}


================================================
FILE: docs/src/content/i18n/ja.json
================================================
{
  "component.preview": "プレビュー"
}


================================================
FILE: docs/src/content/i18n/ko.json
================================================
{
  "component.preview": "미리보기"
}


================================================
FILE: docs/src/content/i18n/ru.json
================================================
{
  "component.preview": "Превью"
}


================================================
FILE: docs/src/content/i18n/zh-CN.json
================================================
{
  "component.preview": "预览"
}


================================================
FILE: docs/src/content.config.ts
================================================
import { defineCollection } from 'astro:content';
import { z } from 'astro/zod';
import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';

export const collections = {
	docs: defineCollection({
		loader: docsLoader(),
		schema: docsSchema(),
	}),
	i18n: defineCollection({
		loader: i18nLoader(),
		schema: i18nSchema({
			extend: z.object({
				'component.preview': z.string().optional(),
			}),
		}),
	}),
};


================================================
FILE: docs/tsconfig.json
================================================
{
  "extends": "astro/tsconfigs/strictest",
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "~/*": ["src/*"]
    }
  }
}


================================================
FILE: eslint.config.mjs
================================================
// @ts-check
import { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import eslint from '@eslint/js';
import tseslint from 'typescript-eslint';
import { globalIgnores } from 'eslint/config';
import globals from 'globals';
import prettierConfig from 'eslint-config-prettier';

export default tseslint.config(
	// Ignore hidden files and directories, `*.d.ts` files (as most recommendations are mostly for
	// users rather than libraries), types testing files, example directories, and build directories.
	globalIgnores([
		'**/.*',
		'**/*.d.ts',
		'**/*.test-d.ts',
		'**/examples/',
		'**/dist/',
		'**/build/',
		'**/examples/',
	]),

	// Setup Node.js globals from `globalThis` (does not include CommonJS arguments).
	{
		languageOptions: {
			globals: {
				...globals.nodeBuiltin,
			},
		},
	},

	// Add ESLint recommended rules.
	eslint.configs.recommended,

	// Add TypeScript ESLint recommended rules with type checking.
	tseslint.configs.recommendedTypeChecked,
	// Setup typed linting.
	{
		languageOptions: {
			parserOptions: {
				projectService: true,
				tsconfigRootDir: dirname(fileURLToPath(import.meta.url)),
			},
		},
	},
	// Disabled typed linting in JavaScript files.
	{
		files: ['**/*.js', '**/*.cjs', '**/*.mjs'],
		extends: [tseslint.configs.disableTypeChecked],
	},

	// Disable all formatting rules.
	prettierConfig,

	// Tweak some rules in all files.
	{
		rules: {
			// Allow triple-slash references that we heavily use.
			'@typescript-eslint/triple-slash-reference': 'off',
			// Disable unbound method checks which requires another plugin to properly work with `expect`
			// calls.
			'@typescript-eslint/unbound-method': 'off',
			// Allow empty catch blocks.
			'no-empty': ['error', { allowEmptyCatch: true }],
			// Allow unused variables for sibling properties in destructuring (used to omit properties)
			// or starting with `_`.
			'@typescript-eslint/no-unused-vars': [
				'error',
				{
					ignoreRestSiblings: true,
					destructuredArrayIgnorePattern: '^_',
					varsIgnorePattern: '^_',
					argsIgnorePattern: '^_',
				},
			],
			// Allow using `any` in rest parameter arrays, e.g. `(...args: any[]) => void`.
			'@typescript-eslint/no-explicit-any': ['error', { ignoreRestArgs: true }],
			// Allow duplicated types in unions as it's not an error and the extra verbosity can make it
			// easier to understand some unions, e.g. for Zod input and output types.
			'@typescript-eslint/no-duplicate-type-constituents': 'off',
			// Allow redundant types in unions as it's not an error and we use such mechanisms to provide
			// fallbacks for some types that may not be accessible in some user environments, e.g. i18n
			// keys for plugins.
			'@typescript-eslint/no-redundant-type-constituents': 'off',
		},
	}
);


================================================
FILE: examples/basics/.gitignore
================================================
# build output
dist/
# generated types
.astro/

# dependencies
node_modules/

# logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*


# environment variables
.env
.env.production

# macOS-specific files
.DS_Store


================================================
FILE: examples/basics/.vscode/extensions.json
================================================
{
  "recommendations": ["astro-build.astro-vscode"],
  "unwantedRecommendations": []
}


================================================
FILE: examples/basics/.vscode/launch.json
================================================
{
  "version": "0.2.0",
  "configurations": [
    {
      "command": "./node_modules/.bin/astro dev",
      "name": "Development server",
      "request": "launch",
      "type": "node-terminal"
    }
  ]
}


================================================
FILE: examples/basics/README.md
================================================
# Starlight Starter Kit: Basics

[![Built with Starlight](https://astro.badg.es/v2/built-with-starlight/tiny.svg)](https://starlight.astro.build)

```
npm create astro@latest -- --template starlight
```

<!-- ASTRO:REMOVE:START -->

[![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/github/withastro/starlight/tree/main/examples/basics)
[![Open with CodeSandbox](https://assets.codesandbox.io/github/button-edit-lime.svg)](https://codesandbox.io/p/sandbox/github/withastro/starlight/tree/main/examples/basics)
[![Deploy to Netlify](https://www.netlify.com/img/deploy/button.svg)](https://app.netlify.com/start/deploy?repository=https://github.com/withastro/starlight&create_from_path=examples/basics)
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fwithastro%2Fstarlight%2Ftree%2Fmain%2Fexamples%2Fbasics&project-name=my-starlight-docs&repository-name=my-starlight-docs)

<!-- ASTRO:REMOVE:END -->

> 🧑‍🚀 **Seasoned astronaut?** Delete this file. Have fun!

## 🚀 Project Structure

Inside of your Astro + Starlight project, you'll see the following folders and files:

```
.
├── public/
├── src/
│   ├── assets/
│   ├── content/
│   │   └── docs/
│   └── content.config.ts
├── astro.config.mjs
├── package.json
└── tsconfig.json
```

Starlight looks for `.md` or `.mdx` files in the `src/content/docs/` directory. Each file is exposed as a route based on its file name.

Images can be added to `src/assets/` and embedded in Markdown with a relative link.

Static assets, like favicons, can be placed in the `public/` directory.

## 🧞 Commands

All commands are run from the root of the project, from a terminal:

| Command                   | Action                                           |
| :------------------------ | :----------------------------------------------- |
| `npm install`             | Installs dependencies                            |
| `npm run dev`             | Starts local dev server at `localhost:4321`      |
| `npm run build`           | Build your production site to `./dist/`          |
| `npm run preview`         | Preview your build locally, before deploying     |
| `npm run astro ...`       | Run CLI commands like `astro add`, `astro check` |
| `npm run astro -- --help` | Get help using the Astro CLI                     |

## 👀 Want to learn more?

Check out [Starlight’s docs](https://starlight.astro.build/), read [the Astro documentation](https://docs.astro.build), or jump into the [Astro Discord server](https://astro.build/chat).


================================================
FILE: examples/basics/astro.config.mjs
================================================
// @ts-check
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

// https://astro.build/config
export default defineConfig({
	integrations: [
		starlight({
			title: 'My Docs',
			social: [{ icon: 'github', label: 'GitHub', href: 'https://github.com/withastro/starlight' }],
			sidebar: [
				{
					label: 'Guides',
					items: [
						// Each item here is one entry in the navigation menu.
						{ label: 'Example Guide', slug: 'guides/example' },
					],
				},
				{
					label: 'Reference',
					autogenerate: { directory: 'reference' },
				},
			],
		}),
	],
});


================================================
FILE: examples/basics/package.json
================================================
{
  "name": "@example/starlight-basics",
  "type": "module",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "dev": "astro dev",
    "start": "astro dev",
    "build": "astro build",
    "preview": "astro preview",
    "astro": "astro"
  },
  "dependencies": {
    "@astrojs/starlight": "^0.38.2",
    "astro": "^6.0.1",
    "sharp": "^0.34.2"
  }
}


================================================
FILE: examples/basics/src/content/docs/guides/example.md
================================================
---
title: Example Guide
description: A guide in my new Starlight docs site.
---

Guides lead a user through a specific task they want to accomplish, often with a sequence of steps.
Writing a good guide requires thinking about what your users are trying to do.

## Further reading

- Read [about how-to guides](https://diataxis.fr/how-to-guides/) in the Diátaxis framework


================================================
FILE: examples/basics/src/content/docs/index.mdx
================================================
---
title: Welcome to Starlight
description: Get started building your docs site with Starlight.
template: splash # Remove or comment out this line to display the site sidebar on this page.
hero:
  tagline: Congrats on setting up a new Starlight project!
  image:
    file: ../../assets/houston.webp
  actions:
    - text: Example Guide
      link: /guides/example/
      icon: right-arrow
    - text: Read the Starlight docs
      link: https://starlight.astro.build
      icon: external
      variant: minimal
---

import { Card, CardGrid } from '@astrojs/starlight/components';

## Next steps

<CardGrid stagger>
	<Card title="Update content" icon="pencil">
		Edit `src/content/docs/index.mdx` to see this page change.
	</Card>
	<Card title="Change page layout" icon="document">
		Delete `template: splash` in `src/content/docs/index.mdx` to display a
		sidebar on this page.
	</Card>
	<Card title="Add new content" icon="add-document">
		Add Markdown or MDX files to `src/content/docs` to create new pages.
	</Card>
	<Card title="Configure your site" icon="setting">
		Edit your `sidebar` and other config in `astro.config.mjs`.
	</Card>
	<Card title="Read the docs" icon="open-book">
		Learn more in [the Starlight Docs](https://starlight.astro.build/).
	</Card>
</CardGrid>


================================================
FILE: examples/basics/src/content/docs/reference/example.md
================================================
---
title: Example Reference
description: A reference page in my new Starlight docs site.
---

Reference pages are ideal for outlining how things work in terse and clear terms.
Less concerned with telling a story or addressing a specific use case, they should give a comprehensive outline of what you're documenting.

## Further reading

- Read [about reference](https://diataxis.fr/reference/) in the Diátaxis framework


================================================
FILE: examples/basics/src/content.config.ts
================================================
import { defineCollection } from 'astro:content';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
};


================================================
FILE: examples/basics/tsconfig.json
================================================
{
  "extends": "astro/tsconfigs/strict",
  "include": [".astro/types.d.ts", "**/*"],
  "exclude": ["dist"]
}


================================================
FILE: examples/markdoc/.gitignore
================================================
# build output
dist/
# generated types
.astro/

# dependencies
node_modules/

# logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*


# environment variables
.env
.env.production

# macOS-specific files
.DS_Store


================================================
FILE: examples/markdoc/.vscode/extensions.json
================================================
{
  "recommendations": ["astro-build.astro-vscode", "stripe.markdoc-language-support"],
  "unwantedRecommendations": []
}


================================================
FILE: examples/markdoc/.vscode/launch.json
================================================
{
  "version": "0.2.0",
  "configurations": [
    {
      "command": "./node_modules/.bin/astro dev",
      "name": "Development server",
      "request": "launch",
      "type": "node-terminal"
    }
  ]
}


================================================
FILE: examples/markdoc/README.md
================================================
# Starlight Starter Kit: Markdoc

[![Built with Starlight](https://astro.badg.es/v2/built-with-starlight/tiny.svg)](https://starlight.astro.build)

```
npm create astro@latest -- --template starlight/markdoc
```

<!-- ASTRO:REMOVE:START -->

[![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/github/withastro/starlight/tree/main/examples/markdoc)
[![Open with CodeSandbox](https://assets.codesandbox.io/github/button-edit-lime.svg)](https://codesandbox.io/p/sandbox/github/withastro/starlight/tree/main/examples/markdoc)
[![Deploy to Netlify](https://www.netlify.com/img/deploy/button.svg)](https://app.netlify.com/start/deploy?repository=https://github.com/withastro/starlight&create_from_path=examples/markdoc)
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fwithastro%2Fstarlight%2Ftree%2Fmain%2Fexamples%2Fmarkdoc&project-name=my-starlight-docs&repository-name=my-starlight-docs)

<!-- ASTRO:REMOVE:END -->

> 🧑‍🚀 **Seasoned astronaut?** Delete this file. Have fun!

## 🚀 Project Structure

Inside of your Astro + Starlight project, you'll see the following folders and files:

```
.
├── public/
├── src/
│   ├── assets/
│   ├── content/
│   │   └── docs/
│   └── content.config.ts
├── astro.config.mjs
├── markdoc.config.mjs
├── package.json
└── tsconfig.json
```

Starlight looks for `.md`, `.mdx` or `.mdoc` files in the `src/content/docs/` directory. Each file is exposed as a route based on its file name.

Images can be added to `src/assets/` and embedded in Markdown with a relative link.

Static assets, like favicons, can be placed in the `public/` directory.

## 🧞 Commands

All commands are run from the root of the project, from a terminal:

| Command                   | Action                                           |
| :------------------------ | :----------------------------------------------- |
| `npm install`             | Installs dependencies                            |
| `npm run dev`             | Starts local dev server at `localhost:4321`      |
| `npm run build`           | Build your production site to `./dist/`          |
| `npm run preview`         | Preview your build locally, before deploying     |
| `npm run astro ...`       | Run CLI commands like `astro add`, `astro check` |
| `npm run astro -- --help` | Get help using the Astro CLI                     |

## 👀 Want to learn more?

Check out [Starlight’s docs](https://starlight.astro.build/), read [the Astro documentation](https://docs.astro.build), or jump into the [Astro Discord server](https://astro.build/chat).


================================================
FILE: examples/markdoc/astro.config.mjs
================================================
// @ts-check
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';
import markdoc from '@astrojs/markdoc';

// https://astro.build/config
export default defineConfig({
	integrations: [
		markdoc(),
		starlight({
			title: 'My Docs',
			social: [{ icon: 'github', label: 'GitHub', href: 'https://github.com/withastro/starlight' }],
			sidebar: [
				{
					label: 'Guides',
					items: [
						// Each item here is one entry in the navigation menu.
						{ label: 'Example Guide', slug: 'guides/example' },
					],
				},
				{
					label: 'Reference',
					autogenerate: { directory: 'reference' },
				},
			],
		}),
	],
});


================================================
FILE: examples/markdoc/markdoc.config.mjs
================================================
import { defineMarkdocConfig } from '@astrojs/markdoc/config';
import starlightMarkdoc from '@astrojs/starlight-markdoc';

// https://docs.astro.build/en/guides/integrations-guide/markdoc/
export default defineMarkdocConfig({
	extends: [starlightMarkdoc()],
});


================================================
FILE: examples/markdoc/package.json
================================================
{
  "name": "@example/starlight-markdoc",
  "type": "module",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "dev": "astro dev",
    "start": "astro dev",
    "build": "astro build",
    "preview": "astro preview",
    "astro": "astro"
  },
  "dependencies": {
    "@astrojs/markdoc": "^1.0.0",
    "@astrojs/starlight": "^0.38.2",
    "@astrojs/starlight-markdoc": "^0.6.0",
    "astro": "^6.0.1",
    "sharp": "^0.34.2"
  }
}


================================================
FILE: examples/markdoc/src/content/docs/guides/example.mdoc
================================================
---
title: Example Guide
description: A guide in my new Starlight docs site.
---

Guides lead a user through a specific task they want to accomplish, often with a sequence of steps.
Writing a good guide requires thinking about what your users are trying to do.

## Further reading

- Read [about how-to guides](https://diataxis.fr/how-to-guides/) in the Diátaxis framework


================================================
FILE: examples/markdoc/src/content/docs/index.mdoc
================================================
---
title: Welcome to Starlight
description: Get started building your docs site with Starlight.
template: splash # Remove or comment out this line to display the site sidebar on this page.
hero:
  title: Welcome to Starlight with Markdoc
  tagline: Congrats on setting up a new Starlight project!
  image:
    file: ../../assets/houston.webp
  actions:
    - text: Example Guide
      link: /guides/example/
      icon: right-arrow
    - text: Read the Starlight docs
      link: https://starlight.astro.build
      icon: external
      variant: minimal
---

## Next steps

{% cardgrid stagger=true %}

{% card title="Update content" icon="pencil" %}
Edit `src/content/docs/index.mdoc` to see this page change.
{% /card %}

{% card title="Change page layout" icon="document" %}
Delete `template: splash` in `src/content/docs/index.mdoc` to display a sidebar on this page.
{% /card %}

{% card title="Add new content" icon="add-document" %}
Add Markdoc files to `src/content/docs` to create new pages.
{% /card %}

{% card title="Configure your site" icon="setting" %}
Edit your `sidebar` and other config in `astro.config.mjs`.
{% /card %}

{% card title="Read the docs" icon="open-book" %}
Learn more in [the Starlight Docs](https://starlight.astro.build/).
{% /card %}

{% /cardgrid %}


================================================
FILE: examples/markdoc/src/content/docs/reference/example.mdoc
================================================
---
title: Example Reference
description: A reference page in my new Starlight docs site.
---

Reference pages are ideal for outlining how things work in terse and clear terms.
Less concerned with telling a story or addressing a specific use case, they should give a comprehensive outline of what you're documenting.

## Further reading

- Read [about reference](https://diataxis.fr/reference/) in the Diátaxis framework


================================================
FILE: examples/markdoc/src/content.config.ts
================================================
import { defineCollection } from 'astro:content';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
};


================================================
FILE: examples/markdoc/tsconfig.json
================================================
{
  "extends": "astro/tsconfigs/strict",
  "include": [".astro/types.d.ts", "**/*"],
  "exclude": ["dist"]
}


================================================
FILE: examples/tailwind/.gitignore
================================================
# build output
dist/
# generated types
.astro/

# dependencies
node_modules/

# logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*


# environment variables
.env
.env.production

# macOS-specific files
.DS_Store


================================================
FILE: examples/tailwind/.vscode/extensions.json
================================================
{
  "recommendations": ["astro-build.astro-vscode"],
  "unwantedRecommendations": []
}


================================================
FILE: examples/tailwind/.vscode/launch.json
================================================
{
  "version": "0.2.0",
  "configurations": [
    {
      "command": "./node_modules/.bin/astro dev",
      "name": "Development server",
      "request": "launch",
      "type": "node-terminal"
    }
  ]
}


================================================
FILE: examples/tailwind/README.md
================================================
# Starlight Starter Kit: Tailwind

[![Built with Starlight](https://astro.badg.es/v2/built-with-starlight/tiny.svg)](https://starlight.astro.build)

```
npm create astro@latest -- --template starlight/tailwind
```

<!-- ASTRO:REMOVE:START -->

[![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/github/withastro/starlight/tree/main/examples/tailwind)
[![Open with CodeSandbox](https://assets.codesandbox.io/github/button-edit-lime.svg)](https://codesandbox.io/p/sandbox/github/withastro/starlight/tree/main/examples/tailwind)
[![Deploy to Netlify](https://www.netlify.com/img/deploy/button.svg)](https://app.netlify.com/start/deploy?repository=https://github.com/withastro/starlight&create_from_path=examples/tailwind)
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fwithastro%2Fstarlight%2Ftree%2Fmain%2Fexamples%2Ftailwind&project-name=my-starlight-docs&repository-name=my-starlight-docs)

<!-- ASTRO:REMOVE:END -->

> 🧑‍🚀 **Seasoned astronaut?** Delete this file. Have fun!

## 🚀 Project Structure

Inside of your Astro + Starlight project, you'll see the following folders and files:

```
.
├── public/
├── src/
│   ├── assets/
│   ├── content/
│   │   └── docs/
│   ├── styles/
│   │   └── global.css
│   └── content.config.ts
├── astro.config.mjs
├── package.json
└── tsconfig.json
```

Starlight looks for `.md` or `.mdx` files in the `src/content/docs/` directory. Each file is exposed as a route based on its file name.

Images can be added to `src/assets/` and embedded in Markdown with a relative link.

Static assets, like favicons, can be placed in the `public/` directory.

The project includes [Tailwind CSS](https://starlight.astro.build/guides/css-and-tailwind/#tailwind-css) for styling. Customize your design by modifying `src/styles/global.css`.

## 🧞 Commands

All commands are run from the root of the project, from a terminal:

| Command                   | Action                                           |
| :------------------------ | :----------------------------------------------- |
| `npm install`             | Installs dependencies                            |
| `npm run dev`             | Starts local dev server at `localhost:4321`      |
| `npm run build`           | Build your production site to `./dist/`          |
| `npm run preview`         | Preview your build locally, before deploying     |
| `npm run astro ...`       | Run CLI commands like `astro add`, `astro check` |
| `npm run astro -- --help` | Get help using the Astro CLI                     |

## 👀 Want to learn more?

Check out [Starlight’s docs](https://starlight.astro.build/), read [the Astro documentation](https://docs.astro.build), or jump into the [Astro Discord server](https://astro.build/chat).


================================================
FILE: examples/tailwind/astro.config.mjs
================================================
// @ts-check
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';
import tailwindcss from '@tailwindcss/vite';

// https://astro.build/config
export default defineConfig({
	integrations: [
		starlight({
			title: 'Docs with Tailwind',
			social: [{ icon: 'github', label: 'GitHub', href: 'https://github.com/withastro/starlight' }],
			sidebar: [
				{
					label: 'Guides',
					items: [
						// Each item here is one entry in the navigation menu.
						{ label: 'Example Guide', slug: 'guides/example' },
					],
				},
				{
					label: 'Reference',
					autogenerate: { directory: 'reference' },
				},
			],
			customCss: ['./src/styles/global.css'],
		}),
	],
	vite: {
		plugins: [tailwindcss()],
	},
});


================================================
FILE: examples/tailwind/package.json
================================================
{
  "name": "@example/starlight-tailwind",
  "type": "module",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "dev": "astro dev",
    "start": "astro dev",
    "build": "astro build",
    "preview": "astro preview",
    "astro": "astro"
  },
  "dependencies": {
    "@astrojs/starlight": "^0.38.2",
    "@astrojs/starlight-tailwind": "^5.0.0",
    "@tailwindcss/vite": "^4.1.18",
    "astro": "^6.0.1",
    "sharp": "^0.34.2",
    "tailwindcss": "^4.1.18"
  }
}


================================================
FILE: examples/tailwind/src/content/docs/guides/example.md
================================================
---
title: Example Guide
description: A guide in my new Starlight docs site.
---

Guides lead a user through a specific task they want to accomplish, often with a sequence of steps.
Writing a good guide requires thinking about what your users are trying to do.

## Further reading

- Read [about how-to guides](https://diataxis.fr/how-to-guides/) in the Diátaxis framework


================================================
FILE: examples/tailwind/src/content/docs/index.mdx
================================================
---
title: Welcome to Starlight
description: Get started building your docs site with Starlight.
template: splash # Remove or comment out this line to display the site sidebar on this page.
hero:
  title: |
    Welcome to Starlight with
    <span
      class="font-black text-transparent
        bg-clip-text bg-gradient-to-b
        from-accent-700 to-accent-400
        dark:from-accent-500 dark:to-accent-200"
    >
      Tailwind
    </span>
  tagline: Congrats on setting up a new Starlight project!
  image:
    file: ../../assets/houston.webp
  actions:
    - text: Example Guide
      link: /guides/example/
      icon: right-arrow
    - text: Read the Starlight docs
      link: https://starlight.astro.build
      icon: external
      variant: minimal
---

import { Card, CardGrid } from '@astrojs/starlight/components';

## Next steps

<CardGrid stagger>
	<Card title="Update content" icon="pencil">
		Edit `src/content/docs/index.mdx` to see this page change.
	</Card>
	<Card title="Change page layout" icon="document">
		Delete `template: splash` in `src/content/docs/index.mdx` to display a
		sidebar on this page.
	</Card>
	<Card title="Add new content" icon="add-document">
		Add Markdown or MDX files to `src/content/docs` to create new pages.
	</Card>
	<Card title="Configure your site" icon="setting">
		Edit your `sidebar` and other config in `astro.config.mjs`.
	</Card>
	<Card title="Read the docs" icon="open-book">
		Learn more in [the Starlight Docs](https://starlight.astro.build/).
	</Card>
</CardGrid>


================================================
FILE: examples/tailwind/src/content/docs/reference/example.md
================================================
---
title: Example Reference
description: A reference page in my new Starlight docs site.
---

Reference pages are ideal for outlining how things work in terse and clear terms.
Less concerned with telling a story or addressing a specific use case, they should give a comprehensive outline of what you're documenting.

## Further reading

- Read [about reference](https://diataxis.fr/reference/) in the Diátaxis framework


================================================
FILE: examples/tailwind/src/content.config.ts
================================================
import { defineCollection } from 'astro:content';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';

export const collections = {
	docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
};


================================================
FILE: examples/tailwind/src/styles/global.css
================================================
@layer base, starlight, theme, components, utilities;

@import '@astrojs/starlight-tailwind';
@import 'tailwindcss/theme.css' layer(theme);
@import 'tailwindcss/utilities.css' layer(utilities);

@theme {
	/*
	Configure your Tailwind theme that will be used by Starlight.
	https://starlight.astro.build/guides/css-and-tailwind/#styling-starlight-with-tailwind
	*/
}

/*
Add additional Tailwind styles to this file:
https://tailwindcss.com/docs/adding-custom-styles#using-custom-css
*/


================================================
FILE: examples/tailwind/tsconfig.json
================================================
{
  "extends": "astro/tsconfigs/strict",
  "include": [".astro/types.d.ts", "**/*"],
  "exclude": ["dist"]
}


================================================
FILE: package.json
================================================
{
  "name": "starlight-root",
  "private": true,
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "build:examples": "pnpm --no-bail --workspace-concurrency 1 --filter '@example/*' build",
    "lint": "eslint . --max-warnings 0",
    "size": "size-limit",
    "version": "pnpm changeset version && pnpm i --no-frozen-lockfile",
    "format": "prettier -w --cache --plugin prettier-plugin-astro .",
    "typecheck": "astro check --minimumSeverity warning --noSync && pnpm --filter starlight-docs typecheck"
  },
  "license": "MIT",
  "devDependencies": {
    "@astrojs/check": "^0.9.7",
    "@changesets/changelog-github": "^0.5.0",
    "@changesets/cli": "^2.27.9",
    "@eslint/js": "^9.33.0",
    "@size-limit/file": "^11.1.6",
    "astro": "^6.0.1",
    "eslint": "^9.33.0",
    "eslint-config-prettier": "^10.1.8",
    "globals": "^16.3.0",
    "prettier": "3.3.3",
    "prettier-plugin-astro": "^0.14.1",
    "size-limit": "^11.1.6",
    "typescript": "^5.6.3",
    "typescript-eslint": "^8.39.1"
  },
  "packageManager": "pnpm@9.15.9",
  "size-limit": [
    {
      "name": "/index.html",
      "path": "examples/basics/dist/index.html",
      "limit": "8 kB",
      "gzip": true
    },
    {
      "name": "/_astro/*.js",
      "path": "examples/basics/dist/_astro/*.js",
      "limit": "27 kB",
      "gzip": true
    },
    {
      "name": "/_astro/*.css",
      "path": [
        "examples/basics/dist/_astro/*.css",
        "!examples/basics/dist/_astro/print.*.css"
      ],
      "limit": "16.75 kB",
      "gzip": true
    }
  ],
  "pnpm": {
    "peerDependencyRules": {
      "ignoreMissing": [
        "@algolia/client-search",
        "playwright",
        "search-insights"
      ]
    }
  }
}


================================================
FILE: packages/docsearch/CHANGELOG.md
================================================
# @astrojs/starlight-docsearch

## 0.7.0

### Minor Changes

- [#3644](https://github.com/withastro/starlight/pull/3644) [`0d2e7ed`](https://github.com/withastro/starlight/commit/0d2e7ed74a604b028fcab0c81b4c35c0c9365343) Thanks [@HiDeoo](https://github.com/HiDeoo)! - ⚠️ **BREAKING CHANGE:** The minimum supported version of Starlight is now 0.38.0

  Please use the `@astrojs/upgrade` command to upgrade your project:

  ```sh
  npx @astrojs/upgrade
  ```

## 0.6.1

### Patch Changes

- [#3500](https://github.com/withastro/starlight/pull/3500) [`7700456`](https://github.com/withastro/starlight/commit/770045663c8ca3cc44983dd0d444955eba441243) Thanks [@delucis](https://github.com/delucis)! - This is the first release published with OIDC trusted publishing.

## 0.6.0

### Minor Changes

- [#2578](https://github.com/withastro/starlight/pull/2578) [`f895f75`](https://github.com/withastro/starlight/commit/f895f75b17f36c826cc871ba1826e5ae1dff44ca) and [#2390](https://github.com/withastro/starlight/pull/2390) [`f493361`](https://github.com/withastro/starlight/commit/f493361d7b64a3279980e0f046c3a52196ab94e0) Thanks [@HiDeoo](https://github.com/HiDeoo) and [@delucis](https://github.com/delucis)!  
  ⚠️ **BREAKING CHANGE:** The minimum supported version of Starlight is now 0.32.0

  Please use the `@astrojs/upgrade` command to upgrade your project:

  ```sh
  npx @astrojs/upgrade
  ```

## 0.5.0

### Minor Changes

- [#2822](https://github.com/withastro/starlight/pull/2822) [`e56586a`](https://github.com/withastro/starlight/commit/e56586add37188b43f3f4c8c15883724fe8fdf87) Thanks [@KianNH](https://github.com/KianNH)! - Adds a new `clientOptionsModule` plugin option to support configuring unserializable DocSearch options such as `resultsFooterComponent()`.

  See [“DocSearch configuration”](https://starlight.astro.build/guides/site-search/#docsearch-configuration) in the Starlight docs for more details.

## 0.4.0

### Minor Changes

- [#2612](https://github.com/withastro/starlight/pull/2612) [`8d5a4e8`](https://github.com/withastro/starlight/commit/8d5a4e8000d9e3a4bb9ca8178767cf3d8bc48773) Thanks [@HiDeoo](https://github.com/HiDeoo)! - ⚠️ **BREAKING CHANGE:** The minimum supported version of Starlight is now 0.30.0

  Please use the `@astrojs/upgrade` command to upgrade your project:

  ```sh
  npx @astrojs/upgrade
  ```

### Patch Changes

- [#2664](https://github.com/withastro/starlight/pull/2664) [`62ff007`](https://github.com/withastro/starlight/commit/62ff0074d9a3f82e46f5c62db85c04d87ff5e931) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Publishes provenance containing verifiable data to link a package back to its source repository and the specific build instructions used to publish it.

## 0.3.0

### Minor Changes

- [#2589](https://github.com/withastro/starlight/pull/2589) [`d4cf8cc`](https://github.com/withastro/starlight/commit/d4cf8cc5633dc87474f943657ec4846e821f7f5b) Thanks [@delucis](https://github.com/delucis)! - Adds support for some more of the DocSearch component’s configuration options

## 0.2.0

### Minor Changes

- [#1923](https://github.com/withastro/starlight/pull/1923) [`5269aad`](https://github.com/withastro/starlight/commit/5269aad928773ae08b35ba8e19c0f2832d0d2c89) Thanks [@HiDeoo](https://github.com/HiDeoo)! - ⚠️ **BREAKING CHANGE:** The minimum supported version of Starlight is now 0.28.0

  Please use the `@astrojs/upgrade` command to upgrade your project:

  ```sh
  npx @astrojs/upgrade
  ```

## 0.1.1

### Patch Changes

- [#2009](https://github.com/withastro/starlight/pull/2009) [`1e8bfe4`](https://github.com/withastro/starlight/commit/1e8bfe4b7bb8e958ce22e65c4719e7f281cd6e88) Thanks [@delucis](https://github.com/delucis)! - Updates Docsearch packages to 3.6.0

## 0.1.0

### Minor Changes

- [#1168](https://github.com/withastro/starlight/pull/1168) [`8155d1a`](https://github.com/withastro/starlight/commit/8155d1a27c5a783c0abdfb6ce1ec066c6926290d) Thanks [@delucis](https://github.com/delucis)! - Adds a Starlight plugin to support using Algolia DocSearch as the Starlight search provider.


================================================
FILE: packages/docsearch/DocSearch.astro
================================================
---
import '@docsearch/css/dist/modal.css';
import type docsearch from '@docsearch/js';
import './variables.css';

type DocSearchTranslationProps = Pick<
	Parameters<typeof docsearch>[0],
	'placeholder' | 'translations'
>;

const pick = (keyStart: string) =>
	Object.fromEntries(
		Object.entries(Astro.locals.t.all())
			.filter(([key]) => key.startsWith(keyStart))
			.map(([key, value]) => [key.replace(keyStart, ''), value])
	);

const docsearchTranslations: DocSearchTranslationProps = {
	placeholder: Astro.locals.t('search.label'),
	translations: {
		button: {
			buttonText: Astro.locals.t('search.label'),
			buttonAriaLabel: Astro.locals.t('search.label'),
		},
		modal: {
			searchBox: pick('docsearch.searchBox.'),
			startScreen: pick('docsearch.startScreen.'),
			errorScreen: pick('docsearch.errorScreen.'),
			footer: pick('docsearch.footer.'),
			noResultsScreen: pick('docsearch.noResultsScreen.'),
		},
	},
};
---

<sl-doc-search data-translations={JSON.stringify(docsearchTranslations)}>
	<button
		type="button"
		class="DocSearch DocSearch-Button"
		aria-label={Astro.locals.t('search.label')}
	>
		<span class="DocSearch-Button-Container">
			<svg width="20" height="20" class="DocSearch-Search-Icon" viewBox="0 0 20 20">
				<path
					d="M14.386 14.386l4.0877 4.0877-4.0877-4.0877c-2.9418 2.9419-7.7115 2.9419-10.6533 0-2.9419-2.9418-2.9419-7.7115 0-10.6533 2.9418-2.9419 7.7115-2.9419 10.6533 0 2.9419 2.9418 2.9419 7.7115 0 10.6533z"
					stroke="currentColor"
					fill="none"
					fill-rule="evenodd"
					stroke-linecap="round"
					stroke-linejoin="round"></path>
			</svg>
			<span class="DocSearch-Button-Placeholder">{Astro.locals.t('search.label')}</span>
		</span>
		<span class="DocSearch-Button-Keys"></span>
	</button>
</sl-doc-search>

<style is:global>
	.DocSearch-Button {
		display: flex;
		align-items: center;
		gap: 0.5rem;
		border: 0;
		background-color: transparent;
		color: var(--sl-color-gray-1);
		cursor: pointer;
		height: 2.5rem;
		font-size: var(--sl-text-xl);
	}
	.DocSearch-Button-Container {
		display: contents;
	}
	.DocSearch-Search-Icon {
		width: 0.875em;
		height: 0.875em;
		stroke-width: 0.125rem;
	}
	.DocSearch-Button-Placeholder,
	.DocSearch-Button-Keys,
	.DocSearch-Button-Key {
		display: none;
	}

	@media (min-width: 50rem) {
		sl-doc-search {
			width: 100%;
		}

		.DocSearch-Button {
			border: 1px solid var(--sl-color-gray-5);
			border-radius: 0.5rem;
			padding-inline-start: 0.75rem;
			padding-inline-end: 1rem;
			background-color: var(--sl-color-black);
			color: var(--sl-color-gray-2);
			font-size: var(--sl-text-sm);
			width: 100%;
			max-width: 22rem;
		}
		.DocSearch-Button:hover {
			border-color: var(--sl-color-gray-2);
			color: var(--sl-color-white);
		}

		.DocSearch-Button-Placeholder,
		.DocSearch-Button-Keys {
			display: flex;
		}
		.DocSearch-Button-Keys {
			margin-inline-start: auto;
		}
		.DocSearch-Button-Keys::before {
			content: '';
			width: 1em;
			height: 1em;
			-webkit-mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath d='M17 2H7a5 5 0 0 0-5 5v10a5 5 0 0 0 5 5h10a5 5 0 0 0 5-5V7a5 5 0 0 0-5-5Zm3 15a3 3 0 0 1-3 3H7a3 3 0 0 1-3-3V7a3 3 0 0 1 3-3h10a3 3 0 0 1 3 3v10Z'%3E%3C/path%3E%3Cpath d='M15.293 6.707a1 1 0 1 1 1.414 1.414l-8.485 8.486a1 1 0 0 1-1.414-1.415l8.485-8.485Z'%3E%3C/path%3E%3C/svg%3E");
			mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath d='M17 2H7a5 5 0 0 0-5 5v10a5 5 0 0 0 5 5h10a5 5 0 0 0 5-5V7a5 5 0 0 0-5-5Zm3 15a3 3 0 0 1-3 3H7a3 3 0 0 1-3-3V7a3 3 0 0 1 3-3h10a3 3 0 0 1 3 3v10Z'%3E%3C/path%3E%3Cpath d='M15.293 6.707a1 1 0 1 1 1.414 1.414l-8.485 8.486a1 1 0 0 1-1.414-1.415l8.485-8.485Z'%3E%3C/path%3E%3C/svg%3E");
			-webkit-mask-size: 100%;
			mask-size: 100%;
			background-color: currentColor;
		}
	}
</style>

<script>
	import config from 'virtual:starlight/docsearch-config';

	class StarlightDocSearch extends HTMLElement {
		constructor() {
			super();
			window.addEventListener('DOMContentLoaded', async () => {
				const { default: docsearch } = await import('@docsearch/js');
				const options = { ...config, container: 'sl-doc-search' };
				try {
					const translations = JSON.parse(this.dataset.translations || '{}');
					Object.assign(options, translations);
				} catch {}
				docsearch(options);
			});
		}
	}
	customElements.define('sl-doc-search', StarlightDocSearch);
</script>


================================================
FILE: packages/docsearch/README.md
================================================
# <img src="https://github.com/withastro/starlight/assets/357379/494fcd83-42aa-4891-87e0-87402fa0b6f3" alt="" align="left" width="40" height="40"> @astrojs/starlight-docsearch

Algolia DocSearch plugin for the [Starlight][starlight] documentation theme for [Astro][astro].

## Documentation

See the [Starlight site search guide][docs] for how to use this plugin.

## License

MIT

Copyright (c) 2023–present [Starlight contributors][contributors]

[starlight]: https://starlight.astro.build/
[astro]: https://astro.build/
[docs]: https://starlight.astro.build/guides/site-search/#algolia-docsearch
[contributors]: https://github.com/withastro/starlight/graphs/contributors


================================================
FILE: packages/docsearch/index.ts
================================================
import type { StarlightPlugin } from '@astrojs/starlight/types';
import type docsearch from '@docsearch/js';
import type { AstroUserConfig, ViteUserConfig } from 'astro';
import { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { z } from 'astro/zod';

const moduleId = 'virtual:starlight/docsearch-config';
const resolvedModuleId = `\0${moduleId}`;

// https://vite.dev/guide/api-plugin#hook-filters
const pluginResolveIdIdFilter = new RegExp(`^${moduleId}$`);
const pluginLoadIdFilter = new RegExp(`^${resolvedModuleId}$`);

export type DocSearchClientOptions = Omit<
	Parameters<typeof docsearch>[0],
	'container' | 'translations'
>;

type SearchOptions = DocSearchClientOptions['searchParameters'];

/** DocSearch configuration options. */
const DocSearchConfigSchema = z
	.strictObject({
		// Required config without which DocSearch won’t work.
		/** Your Algolia application ID. */
		appId: z.string(),
		/** Your Algolia Search API key. */
		apiKey: z.string(),
		/** Your Algolia index name. */
		indexName: z.string(),
		// Optional DocSearch component config (only the serializable properties can be included here)
		/**
		 * The maximum number of results to display per search group.
		 * @default 5
		 */
		maxResultsPerGroup: z.number().optional(),
		/**
		 * Disable saving recent searches and favorites to the local storage.
		 * @default false
		 */
		disableUserPersonalization: z.boolean().optional(),
		/**
		 * Whether to enable the Algolia Insights plugin and send search events to your DocSearch index.
		 * @default false
		 */
		insights: z.boolean().optional(),
		/**
		 * The Algolia Search Parameters.
		 * @see https://www.algolia.com/doc/api-reference/search-api-parameters/
		 */
		searchParameters: z.custom<SearchOptions>().optional(),
	})
	.or(
		z.strictObject({
			/**
			 * The path to a JavaScript or TypeScript file containing a default export of options to
			 * pass to the DocSearch client.
			 *
			 * The value can be a path to a local JS/TS file relative to the root of your project,
			 * e.g. `'/src/docsearch.js'`, or an npm module specifier for a package you installed,
			 * e.g. `'@company/docsearch-config'`.
			 *
			 * Use `clientOptionsModule` when you need to configure options that are not serializable,
			 * such as `transformSearchClient()` or `resultsFooterComponent()`.
			 *
			 * When `clientOptionsModule` is set, all options must be set via the module file. Other
			 * inline options passed to the plugin in `astro.config.mjs` will be ignored.
			 *
			 * @see https://docsearch.algolia.com/docs/api
			 *
			 * @example
			 * // astro.config.mjs
			 * // ...
			 * starlightDocSearch({ clientOptionsModule: './src/config/docsearch.ts' }),
			 * // ...
			 *
			 * // src/config/docsearch.ts
			 * import type { DocSearchClientOptions } from '@astrojs/starlight-docsearch';
			 *
			 * export default {
			 *   appId: '...',
			 *   apiKey: '...',
			 *   indexName: '...',
			 *   getMissingResultsUrl({ query }) {
			 *     return `https://github.com/algolia/docsearch/issues/new?title=${query}`;
			 *   },
			 * } satisfies DocSearchClientOptions;
			 */
			clientOptionsModule: z.string(),
		})
	);

type DocSearchUserConfig = z.infer<typeof DocSearchConfigSchema>;

/** Starlight DocSearch plugin. */
export default function starlightDocSearch(userConfig: DocSearchUserConfig): StarlightPlugin {
	const opts = DocSearchConfigSchema.parse(userConfig);
	return {
		name: 'starlight-docsearch',
		hooks: {
			'config:setup'({ addIntegration, config, logger, updateConfig }) {
				// If the user has already has a custom override for the Search component, don't override it.
				if (config.components?.Search) {
					logger.warn(
						'It looks like you already have a `Search` component override in your Starlight configuration.'
					);
					logger.warn(
						'To render `@astrojs/starlight-docsearch`, remove the override for the `Search` component.\n'
					);
				} else {
					// Otherwise, add the Search component override to the user's configuration.
					updateConfig({
						pagefind: false,
						components: {
							...config.components,
							Search: '@astrojs/starlight-docsearch/DocSearch.astro',
						},
					});
				}

				// Add an Astro integration that injects a Vite plugin to expose
				// the DocSearch config via a virtual module.
				addIntegration({
					name: 'starlight-docsearch',
					hooks: {
						'astro:config:setup': ({ config, updateConfig }) => {
							updateConfig({
								vite: {
									plugins: [vitePluginDocSearch(config.root, opts)],
								},
							} satisfies AstroUserConfig);
						},
					},
				});
			},
		},
	};
}

/** Vite plugin that exposes the DocSearch config via virtual modules. */
function vitePluginDocSearch(root: URL, config: DocSearchUserConfig): VitePlugin {
	const resolveId = (id: string, base = root) =>
		JSON.stringify(id.startsWith('.') ? resolve(fileURLToPath(base), id) : id);

	const moduleContent = `
	${
		'clientOptionsModule' in config
			? `export { default } from ${resolveId(config.clientOptionsModule)};`
			: `export default ${JSON.stringify(config)};`
	}
	`;

	return {
		name: 'vite-plugin-starlight-docsearch-config',
		load: {
			filter: { id: pluginLoadIdFilter },
			handler(id) {
				return id === resolvedModuleId ? moduleContent : undefined;
			},
		},
		resolveId: {
			filter: { id: pluginResolveIdIdFilter },
			handler(id) {
				return id === moduleId ? resolvedModuleId : undefined;
			},
		},
	};
}

type VitePlugin = NonNullable<ViteUserConfig['plugins']>[number];


================================================
FILE: packages/docsearch/package.json
================================================
{
  "name": "@astrojs/starlight-docsearch",
  "version": "0.7.0",
  "description": "Algolia DocSearch plugin for the Starlight documentation theme for Astro",
  "author": "Chris Swithinbank <swithinbank@gmail.com>",
  "license": "MIT",
  "repository": {
    "type": "git",
    "url": "https://github.com/withastro/starlight",
    "directory": "packages/docsearch"
  },
  "bugs": "https://github.com/withastro/starlight/issues",
  "homepage": "https://starlight.astro.build",
  "type": "module",
  "files": [
    "index.ts",
    "DocSearch.astro",
    "schema.ts",
    "variables.css",
    "virtual.d.ts"
  ],
  "exports": {
    ".": "./index.ts",
    "./DocSearch.astro": "./DocSearch.astro",
    "./schema": "./schema.ts"
  },
  "peerDependencies": {
    "@astrojs/starlight": ">=0.38.0"
  },
  "dependencies": {
    "@docsearch/css": "^3.6.0",
    "@docsearch/js": "^3.6.0"
  },
  "devDependencies": {
    "@astrojs/starlight": "workspace:*"
  },
  "publishConfig": {
    "provenance": true
  }
}


================================================
FILE: packages/docsearch/schema.ts
================================================
import { z } from 'astro/zod';

/**
 * Schema for the Algolia DocSearch modal’s strings.
 *
 * Add this to your `src/content.config.ts`:
 *
 * ```js
 * import { defineCollection } from 'astro:content';
 * import { docsLoader, i18nLoader } from '@astrojs/starlight/loaders';
 * import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';
 * import { docSearchI18nSchema } from '@astrojs/starlight-docsearch/schema';
 *
 * export const collections = {
 * 		docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
 * 		i18n: defineCollection({
 * 			loader: i18nLoader(),
 * 			schema: i18nSchema({ extend: docSearchI18nSchema() }),
 * 		}),
 * };
 * ```
 *
 * DocSearch uses a nested object structure.
 * This schema is a flattened version of DocSearch’s `modal` translations.
 *
 * For example, customizing DocSearch labels looks like this
 * when using the component from JavaScript:
 *
 * ```js
 * {
 *    modal: {
 *      footer: {
 *        selectKeyAriaLabel: 'Return key',
 *      },
 *    },
 * },
 * ```
 *
 * In your Starlight translation files, set this using the object path inside `modal`
 * as the key for each string, prefixed with `docsearch`:
 *
 * ```json
 * {
 *   "docsearch.footer.selectKeyAriaLabel": "Return key"
 * }
 * ```
 *
 * @see https://docsearch.algolia.com/docs/api/#translations
 */
export const docSearchI18nSchema = () =>
	z
		.object({
			// SEARCH BOX
			/** Default: `Clear the query` */
			'docsearch.searchBox.resetButtonTitle': z.string(),
			/** Default: `Clear the query` */
			'docsearch.searchBox.resetButtonAriaLabel': z.string(),
			/** Default: `Cancel` */
			'docsearch.searchBox.cancelButtonText': z.string(),
			/** Default: `Cancel` */
			'docsearch.searchBox.cancelButtonAriaLabel': z.string(),
			/** Default: `Search` */
			'docsearch.searchBox.searchInputLabel': z.string(),

			// START SCREEN
			/** Default: `Recent` */
			'docsearch.startScreen.recentSearchesTitle': z.string(),
			/** Default: `No recent searches` */
			'docsearch.startScreen.noRecentSearchesText': z.string(),
			/** Default: `Save this search` */
			'docsearch.startScreen.saveRecentSearchButtonTitle': z.string(),
			/** Default: `Remove this search from history` */
			'docsearch.startScreen.removeRecentSearchButtonTitle': z.string(),
			/** Default: `Favorite` */
			'docsearch.startScreen.favoriteSearchesTitle': z.string(),
			/** Default: `Remove this search from favorites` */
			'docsearch.startScreen.removeFavoriteSearchButtonTitle': z.string(),

			// ERROR SCREEN
			/** Default: `Unable to fetch results` */
			'docsearch.errorScreen.titleText': z.string(),
			/** Default: `You might want to check your network connection.` */
			'docsearch.errorScreen.helpText': z.string(),

			// FOOTER
			/** Default: `to select` */
			'docsearch.footer.selectText': z.string(),
			/** Default: `Enter key` */
			'docsearch.footer.selectKeyAriaLabel': z.string(),
			/** Default: `to navigate` */
			'docsearch.footer.navigateText': z.string(),
			/** Default: `Arrow up` */
			'docsearch.footer.navigateUpKeyAriaLabel': z.string(),
			/** Default: `Arrow down` */
			'docsearch.footer.navigateDownKeyAriaLabel': z.string(),
			/** Default: `to close` */
			'docsearch.footer.closeText': z.string(),
			/** Default: `Escape key` */
			'docsearch.footer.closeKeyAriaLabel': z.string(),
			/** Default: `Search by` */
			'docsearch.footer.searchByText': z.string(),

			// NO RESULTS SCREEN
			/** Default: `No results for` */
			'docsearch.noResultsScreen.noResultsText': z.string(),
			/** Default: `Try searching for` */
			'docsearch.noResultsScreen.suggestedQueryText': z.string(),
			/** Default: `Believe this query should return results?` */
			'docsearch.noResultsScreen.reportMissingResultsText': z.string(),
			/** Default: `Let us know.` */
			'docsearch.noResultsScreen.reportMissingResultsLinkText': z.string(),
		})
		.partial();


================================================
FILE: packages/docsearch/variables.css
================================================
/* Variables */
:root {
	--docsearch-primary-color: var(--sl-color-text-accent);
	--docsearch-text-color: var(--sl-color-text);
	--docsearch-spacing: 12px;
	--docsearch-icon-stroke-width: 1.4;
	--docsearch-highlight-color: var(--docsearch-primary-color);
	--docsearch-muted-color: var(--sl-color-gray-3);
	--docsearch-container-background: var(--sl-color-backdrop-overlay);

	/* modal */
	--docsearch-modal-width: 560px;
	--docsearch-modal-height: 600px;
	--docsearch-modal-background: var(--sl-color-gray-6);
	--docsearch-modal-shadow: var(--sl-shadow-lg);

	/* searchbox */
	--docsearch-searchbox-height: 56px;
	--docsearch-searchbox-background: var(--sl-color-gray-7, var(--sl-color-gray-6));
	--docsearch-searchbox-focus-background: var(--sl-color-black);
	--docsearch-searchbox-shadow: inset 0 0 0 1px var(--docsearch-primary-color);

	/* hit */
	--docsearch-hit-height: 56px;
	--docsearch-hit-color: var(--sl-color-white);
	--docsearch-hit-active-color: var(--sl-color-black);
	--docsearch-hit-background: var(--sl-color-black);

	/* key */
	--docsearch-key-gradient: linear-gradient(
		var(--sl-color-bg-inline-code) 0%,
		var(--sl-color-bg-inline-code) 100%
	);

	/* footer */
	--docsearch-footer-height: 44px;
	--docsearch-footer-background: var(--sl-color-black);
	--docsearch-footer-shadow: 0 -1px 0 0 var(--sl-color-hairline-light);
}

/* Custom style overrides */
.DocSearch-Modal {
	border: 1px solid var(--sl-color-hairline-light);
}
.DocSearch-Logo svg * {
	fill: var(--docsearch-muted-color);
}


================================================
FILE: packages/docsearch/virtual.d.ts
================================================
declare module 'virtual:starlight/docsearch-config' {
	const DocSearchClientOptions: import('./index').DocSearchClientOptions;
	export default DocSearchClientOptions;
}


================================================
FILE: packages/file-icons-generator/config.ts
================================================
import type { Definitions } from '../starlight/user-components/rehype-file-tree';

export const seti = {
	/** The GitHub repository containing the Seti UI theme using the `username/repo` format. */
	repo: 'jesseweed/seti-ui',
	/** The repository branch to use. */
	branch: 'master',
	/** The path to the icon mapping file in the repository. */
	mapping: 'styles/components/icons/mapping.less',
	/** The path to the icon font file in the repository. */
	font: 'styles/_fonts/seti/seti.woff',
	/**
	 * Some Seti UI icons share identical SVG for multiple icons. When converted to a font, identical
	 * SVGs will be saved as one unique glyph with its name being the first icon encountered. The
	 * other names are lost in the process and only their associated unicode character will be kept.
	 * As we want to access icons by their name, we need to manually map the names of identical SVGs
	 * to the icon name that is embedded in the font glyph.
	 * Note that when this happens, an error will be thrown indicating which icon is affected.
	 */
	aliases: {
		coffee: 'cjsx',
		html_erb: 'html',
		less: 'json',
	},
	/**
	 * Seti UI icons can be overridden to use another Seti UI icon.
	 * The key is the icon name to override and the value is the Seti icon name to use instead.
	 * The reason to support aliasing to another Seti UI icon is that some Seti UI icons can be
	 * almost identical. For example, the `npm_ignored` icon used for `npm-debug.log` files is
	 * identical to the `npm` icon except the npm logo is shifted 1px to the right. There is no need
	 * to provide a separate icon for this case and we can just use the `npm` icon instead.
	 */
	overrides: {
		ejs: 'html',
		go: 'go2',
		npm_ignored: 'npm',
	},
	/**
	 * Allows for renaming Seti UI icons to another name.
	 * For example, the Visual Studio Code icon used for Go is named `go2` and this is not the name
	 * we want to expose to the user.
	 * Note that renaming an icon happens after overrides are applied.
	 */
	renames: {
		go2: 'go',
	},
	/**
	 * A list of Seti UI icons to ignore.
	 * Each entry should be commented with the reason why the icon is ignored.
	 */
	ignores: [
		// The ReasonML SVG icon contains a path issue that makes it render a plain square instead of a
		// square with the "RE" letters when converted to a font.
		// This is also an issue in Visual Studio Code but considering that in Starlight, all the icons
		// are also available with the `<Icon>` component, it's better to ignore it for now instead of
		// providing an icon with no meaning.
		'reasonml',
	],
};

export const starlight = {
	/** The path of the generated file in the Starlight package directory. */
	output: 'user-components/file-tree-icons.ts',
	/** A prefix to add to the Seti icon names. */
	prefix: 'seti:',
	/**
	 * The Starlight `<Icon>` component viewBox size.
	 * @see {@link file://../starlight/user-components/Icon.astro}
	 */
	iconViewBoxSize: 24,
	/**
	 * Extra definitions for the `<FileTree>` component that add mappings using built-in Starlight
	 * icons.
	 */
	definitions: {
		files: {
			'astro.config.js': 'astro',
			'astro.config.mjs': 'astro',
			'astro.config.cjs': 'astro',
			'astro.config.ts': 'astro',
			'pnpm-debug.log': 'pnpm',
			'pnpm-lock.yaml': 'pnpm',
			'pnpm-workspace.yaml': 'pnpm',
			'biome.json': 'biome',
			'bun.lockb': 'bun',
		},
		extensions: {
			'.astro': 'astro',
			'.mdx': 'mdx',
			'.pkl': 'pkl',
		},
		partials: {},
	} satisfies Definitions,
};


================================================
FILE: packages/file-icons-generator/index.ts
================================================
import { writeDefinitionsAndSVGs } from './utils/file';
import { getIconSvgPaths } from './utils/font';
import { deleteRepo, parseMapping, setupRepo } from './utils/seti';

/**
 * Script generating definitions used by the Starlight `<FileTree>` component and associated SVGs.
 *
 * To do so, it clones the Seti UI repository, installs dependencies, generates icons, parses the
 * mapping to generate the definitions and a list of icons to extract as SVGs, and finally extracts
 * the SVGs from the font and writes the definitions and SVGs to the Starlight package in a file
 * ready to be consumed by Starlight.
 *
 * @see {@link file://./config.ts} for the configuration used by this script.
 * @see {@link file://../starlight/user-components/file-tree-icons.ts} for the generated file.
 * @see {@link https://opentype.js.org/glyph-inspector.html} for a font glyph inspector.
 */

const repoPath = await setupRepo();

try {
	const { definitions, icons } = await parseMapping(repoPath);

	const svgPaths = await getIconSvgPaths(repoPath, icons, definitions);

	await writeDefinitionsAndSVGs(definitions, svgPaths);
} finally {
	await deleteRepo(repoPath);
}


================================================
FILE: packages/file-icons-generator/package.json
================================================
{
  "name": "starlight-file-icons-generator",
  "version": "0.1.0",
  "description": "Generates Starlight file icons based on the Seti UI theme",
  "private": true,
  "scripts": {
    "build": "tsx ."
  },
  "license": "MIT",
  "dependencies": {
    "opentype.js": "^1.3.4",
    "tsx": "^4.15.2"
  },
  "devDependencies": {
    "@types/opentype.js": "^1.3.8"
  },
  "type": "module"
}


================================================
FILE: packages/file-icons-generator/utils/file.ts
================================================
import { spawn } from 'node:child_process';
import fs from 'node:fs/promises';
import path from 'node:path';
import { starlight } from '../config';
import type { Definitions } from '../../starlight/user-components/rehype-file-tree';

const copyrightNotice = `/**
* Based on https://github.com/elviswolcott/seti-icons which
* is derived from https://github.com/jesseweed/seti-ui/
*
* Copyright (c) 2014 Jesse Weed
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/`;

const generatedFileHeader = `/**
* This file was generated by the \`file-icons-generator\` package.
* Do not edit this file directly as it will be overwritten.
*/`;

/** Write the generated definitions and SVGs to the Starlight package. */
export async function writeDefinitionsAndSVGs(
	definitions: Definitions,
	svgPaths: Record<string, string>
) {
	const content = `${generatedFileHeader}

import type { Definitions } from './rehype-file-tree.ts';

${copyrightNotice}
export const definitions: Definitions = ${JSON.stringify(definitions)};

export const FileIcons = ${JSON.stringify(svgPaths)};
`;

	const filePath = path.join('..', 'starlight', starlight.output);

	await fs.writeFile(filePath, content);

	await prettifyFile(path.resolve(filePath));
}

/** Run Prettier on a generated file. */
function prettifyFile(filePath: string) {
	return new Promise<void>((resolve, reject) => {
		const child = spawn('pnpm', ['prettier', '-w', filePath], {
			cwd: '../..',
			stdio: [],
		});

		const error = new Error('Failed to run Prettier on the generated file.');

		child.on('error', () => reject(error));
		child.on('close', (code) => {
			if (code !== 0) {
				reject(error);

				return;
			}

			resolve();
		});
	});
}


================================================
FILE: packages/file-icons-generator/utils/font.ts
================================================
import opentype, { type Font, Glyph } from 'opentype.js';
import { seti, starlight } from '../config';
import type { Definitions } from '../../starlight/user-components/rehype-file-tree';
import { getFont, getSetiIconName } from './seti';

// This matches the default precision used by the SVGO default preset.
const pathDecimalPrecision = 3;

/** Extract SVG paths from the Seti UI icon font from a list of icon names matching font glyphs. */
export async function getIconSvgPaths(repoPath: string, icons: string[], definitions: Definitions) {
	const fontBuffer = await getFont(repoPath);

	const iconSvgs: Record<string, string> = {};

	let font: Font;

	try {
		font = opentype.parse(fontBuffer);
	} catch (error) {
		throw new Error('Failed to parse icon SVGs.', { cause: error });
	}

	for (const icon of icons) {
		let glyph: Glyph;

		try {
			// Find the glyph matching the icon name.
			glyph = font.nameToGlyph(icon);
		} catch {
			// If the glyph is not found, this means that multiple icons share the same glyph and we have
			// a mapping for such case.
			const alias = getFontGlyphAlias(icon);

			// When an alias is found, we update the definitions to use the alias instead of the original
			// icon name and continue to the next icon as there is no need to extract an SVG.
			updateDefinitionsWithAlias(definitions, icon, alias);
			continue;
		}

		// We need to compute various metrics to ensure the icon properly fits the viewBox size.
		const { fontSize, offsetX, offsetY } = getComputedFontSizeToFit(
			glyph,
			starlight.iconViewBoxSize
		);
		const path = glyph.getPath(offsetX, offsetY, fontSize);
		const iconName = getSetiIconName(icon);
		iconSvgs[iconName] = path.toSVG(pathDecimalPrecision);
	}

	return iconSvgs;
}

/**
 * Compute the font size and offsets to fit a glyph in a viewBox of a given size.
 * We first try to fit the glyph in the viewBox and increase the font size until it no longer fits
 * to get the best fit possible.
 */
function getComputedFontSizeToFit(glyph: opentype.Glyph, size: number, fontSize = size) {
	const { width, height } = getGlyphPathDimensions(glyph, fontSize);

	// If one of the glyph path dimensions is greater than the viewBox size, we can stop here and return
	// the previous font size and offsets.
	if (width > size || height > size) {
		const fittingFontSize = fontSize - 1;
		const { x1, y1, width, height } = getGlyphPathDimensions(glyph, fittingFontSize);

		return {
			fontSize: fittingFontSize,
			// We need to ensure that the glyph is centered in the viewBox.
			offsetX: (x1 + (width - size) / 2) * -1,
			offsetY: (y1 + (height - size) / 2) * -1,
		};
	}

	// If the glyph path dimensions are smaller than the viewBox size, we can increase the font size
	// and try again.
	return getComputedFontSizeToFit(glyph, size, fontSize + 1);
}

/** Returns the bounding box, width, and height of a glyph path. */
function getGlyphPathDimensions(glyph: opentype.Glyph, fontSize: number) {
	const path = glyph.getPath(0, 0, fontSize);
	const boundingBox = path.getBoundingBox();

	return {
		...boundingBox,
		width: boundingBox.x2 - boundingBox.x1,
		height: boundingBox.y2 - boundingBox.y1,
	};
}

/**
 * Return the alias of a font glyph when multiple icons share the same glyph or throw an error if
 * no mapping is found.
 */
function getFontGlyphAlias(icon: string): string {
	const alias = seti.aliases[icon as keyof typeof seti.aliases];

	if (!alias) {
		throw new Error(
			`Failed to find a glyph for the icon '${icon}'. This usually means that the icon is sharing a glyph with another icon and such association must be defined in the 'seti.aliases' configuration.`
		);
	}

	return alias;
}

/** Update the definitions to use an alias instead of a specific icon name. */
function updateDefinitionsWithAlias(definitions: Definitions, icon: string, alias: string) {
	const prefixedIcon = getSetiIconName(icon);
	const prefixedAlias = getSetiIconName(alias);

	updateDefinitionsRecordWithAlias(definitions.files, prefixedIcon, prefixedAlias);
	updateDefinitionsRecordWithAlias(definitions.extensions, prefixedIcon, prefixedAlias);
	updateDefinitionsRecordWithAlias(definitions.partials, prefixedIcon, prefixedAlias);
}

/** Update a definitions record to use an alias instead of a specific icon name. */
function updateDefinitionsRecordWithAlias(
	record: Record<string, string>,
	icon: string,
	alias: string
) {
	for (const [key, value] of Object.entries(record)) {
		if (value === icon) {
			record[key] = alias;
		}
	}
}


================================================
FILE: packages/file-icons-generator/utils/seti.ts
================================================
import { spawnSync, type SpawnSyncOptions } from 'node:child_process';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { seti, starlight } from '../config';
import type { Definitions } from '../../starlight/user-components/rehype-file-tree.ts';

// https://github.com/jesseweed/seti-ui/blob/master/styles/components/icons/mapping.less
// .icon-set(".bsl", "bsl", @red);
// .icon-partial("mix", "hex", @red);
const mappingRegex =
	/^\.icon-(?<type>(set|partial))\((?<quote>['"])(?<identifier>.+)\k<quote>, \k<quote>(?<lang>.+)\k<quote>, @.+\);$/;

/** Clone the Seti UI repository, install dependencies, and generate the Seti UI icons. */
export async function setupRepo() {
	try {
		const repoPath = await fs.mkdtemp(path.join(os.tmpdir(), 'starlight-file-icons-'));

		const spawnOptions: SpawnSyncOptions = {
			cwd: repoPath,
			encoding: 'utf8',
		};

		let result = spawnSync('git', ['clone', `https://github.com/${seti.repo}`, '.'], spawnOptions);
		if (result.error) throw new Error('Failed to clone the Seti UI repository.');

		result = spawnSync('npm', ['install'], spawnOptions);
		if (result.error) throw new Error('Failed to install the Seti UI dependencies.');

		result = spawnSync('npm', ['run', 'createIcons'], spawnOptions);
		if (result.error) throw new Error('Failed to generate the Seti UI icons.');

		return repoPath;
	} catch (error) {
		throw new Error(
			'Failed to setup the Seti UI repo. Make sure the repository URL and font path are correct.',
			{ cause: error }
		);
	}
}

/** Delete the Seti UI repository. */
export async function deleteRepo(repoPath: string) {
	try {
		await fs.rm(repoPath, { force: true, recursive: true });
	} catch (error) {
		throw new Error('Failed to remove the Seti UI repo.', { cause: error });
	}
}

/**
 * Get the Seti UI icon font from a local repository.
 * Note that the `woff` font format is used and not `woff2` as we would manually need to decompress
 * it and we do not need the compression benefits for this use case.
 */
export async function getFont(repoPath: string) {
	try {
		const result = await fs.readFile(path.join(repoPath, seti.font));
		return new Uint8Array(result).buffer;
	} catch (error) {
		throw new Error('Failed to read Seti UI font. Make sure the font path is correct.', {
			cause: error,
		});
	}
}

/**
 * Parse the Seti UI icon mapping file to generate the definitions used by the `<FileTree>`
 * component and a list of Seti UI icons to extract as SVGs.
 * @see https://github.com/elviswolcott/seti-icons/blob/master/build/extract.ts
 */
export async function parseMapping(repoPath: string) {
	const mapping = await getMapping(repoPath);

	const lines = mapping.split('\n');
	// Include the `folder` icon by default as it is not defined in the mapping file.
	const icons = new Set<string>(['folder']);
	const definitions: Definitions = {
		files: { ...starlight.definitions.files },
		extensions: { ...starlight.definitions.extensions },
		partials: { ...starlight.definitions.partials },
	};

	for (const line of lines) {
		const match = line.match(mappingRegex);
		if (!match) continue;
		const { identifier, lang, type } = match.groups!;
		if (!identifier || !lang || !type) continue;
		if (seti.ignores.includes(lang)) continue;

		const maybeOverride: string | undefined = seti.overrides[lang as keyof typeof seti.overrides];

		// Add the icon to the list of icons to extract as SVGs.
		icons.add(maybeOverride ?? lang);

		const icon = getSetiIconName(lang);

		if (type === 'set') {
			if (identifier?.startsWith('.')) {
				definitions.extensions[identifier] = icon;
			} else {
				definitions.files[identifier] = icon;
			}
		} else {
			definitions.partials[identifier] = icon;
		}
	}

	return { definitions, icons: [...icons] };
}

/** Return the name of an icon by taking rename configuration into account. */
export function getSetiIconName(icon: string) {
	const name = seti.renames[icon as keyof typeof seti.renames] ?? icon;

	return `${starlight.prefix}${name}`;
}

/** Get the Seti UI icon mapping file from a local repository. */
async function getMapping(repoPath: string) {
	try {
		return await fs.readFile(path.join(repoPath, seti.mapping), 'utf8');
	} catch (error) {
		throw new Error(
			'Failed to read Seti UI icon mapping file. Make sure the mapping file path is correct.',
			{ cause: error }
		);
	}
}


================================================
FILE: packages/markdoc/.npmignore
================================================
__tests__/


================================================
FILE: packages/markdoc/CHANGELOG.md
================================================
# @astrojs/starlight-markdoc

## 0.6.0

### Minor Changes

- [#3644](https://github.com/withastro/starlight/pull/3644) [`0d2e7ed`](https://github.com/withastro/starlight/commit/0d2e7ed74a604b028fcab0c81b4c35c0c9365343) Thanks [@HiDeoo](https://github.com/HiDeoo)! - ⚠️ **BREAKING CHANGE:** The minimum supported version of Starlight is now 0.38.0

  Please use the `@astrojs/upgrade` command to upgrade your project:

  ```sh
  npx @astrojs/upgrade
  ```

## 0.5.1

### Patch Changes

- [#3500](https://github.com/withastro/starlight/pull/3500) [`7700456`](https://github.com/withastro/starlight/commit/770045663c8ca3cc44983dd0d444955eba441243) Thanks [@delucis](https://github.com/delucis)! - This is the first release published with OIDC trusted publishing.

## 0.5.0

### Minor Changes

- [#2261](https://github.com/withastro/starlight/pull/2261) [`778b743`](https://github.com/withastro/starlight/commit/778b743cdb832551ed576c745728358d8bbf9d7a) Thanks [@shubham-padia](https://github.com/shubham-padia)! - Adds support for the `icon` attribute in the `aside` tag, allowing the use of any of Starlight’s built-in icons.

## 0.4.0

### Minor Changes

- [#3033](https://github.com/withastro/starlight/pull/3033) [`8c19678`](https://github.com/withastro/starlight/commit/8c19678e57c0270d3d80d4678f23a6fc287ebf12) Thanks [@delucis](https://github.com/delucis)! - Adds support for generating clickable anchor links for headings.

  By default, the Starlight Markdoc preset now includes a default `heading` node, which renders an anchor link beside headings in your Markdoc content.

  If you want to disable this new feature, pass `headingLinks: false` in your Markdoc config:

  ```js
  export default defineMarkdocConfig({
    // Disable the default heading anchor link support
    extends: [starlightMarkdoc({ headingLinks: false })],
  });
  ```

  ⚠️ **BREAKING CHANGE:** The minimum supported peer version of Starlight is now v0.34.0.

  Please update Starlight and the Starlight Markdoc preset together:

  ```sh
  npx @astrojs/upgrade
  ```

## 0.3.1

### Patch Changes

- [#3090](https://github.com/withastro/starlight/pull/3090) [`fc3ffa8`](https://github.com/withastro/starlight/commit/fc3ffa8e27a3113a8eb70a3d8e7bf69c2bb214e5) Thanks [@delucis](https://github.com/delucis)! - Adds support for newer versions of `@astrojs/markdoc`

- [#3109](https://github.com/withastro/starlight/pull/3109) [`b5cc1b4`](https://github.com/withastro/starlight/commit/b5cc1b4d4ee7dc737616c6ada893369b13ddb9c6) Thanks [@dhruvkb](https://github.com/dhruvkb)! - Updates Expressive Code to v0.41.1

## 0.3.0

### Minor Changes

- [#2931](https://github.com/withastro/starlight/pull/2931) [`10b93b3`](https://github.com/withastro/starlight/commit/10b93b336cf4e3500e3003635b5afc430284d1a7) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds support for the `title`, `frame`, and `meta` fence attributes to code blocks.

  These new optional attributes add support for Expressive Code [text & line markers](https://expressive-code.com/key-features/text-markers/). The following example renders a code block using a [terminal frame](https://expressive-code.com/key-features/frames/#terminal-frames) with a [title](https://expressive-code.com/key-features/frames/#code-editor-frames):

  ````mdoc
  ```js {% title="editor.exe" frame="terminal" %}
  console.log('Hello, world!');
  ```
  ````

  Any other text or line markers should be specified using the `meta` fence attribute. For example, the following code block renders a code block using the `diff` syntax combined with the `js` language syntax highlighting and the `markers` text highlighted:

  ````mdoc
  ```diff {% meta="lang=js 'markers'" %}
    function thisIsJavaScript() {
      // This entire block gets highlighted as JavaScript,
      // and we can still add diff markers to it!
  -   console.log('Old code to be removed')
  +   console.log('New and shiny code!')
    }
  ```
  ````

  To learn more about all the available options, check out the [Expressive Code documentation](https://expressive-code.com/key-features/text-markers/#usage-in-markdown--mdx).

## 0.2.0

### Minor Changes

- [#2612](https://github.com/withastro/starlight/pull/2612) [`8d5a4e8`](https://github.com/withastro/starlight/commit/8d5a4e8000d9e3a4bb9ca8178767cf3d8bc48773) Thanks [@HiDeoo](https://github.com/HiDeoo)! - ⚠️ **BREAKING CHANGE:** The minimum supported version of Starlight is now 0.30.0

  Please use the `@astrojs/upgrade` command to upgrade your project:

  ```sh
  npx @astrojs/upgrade
  ```

### Patch Changes

- [#2664](https://github.com/withastro/starlight/pull/2664) [`62ff007`](https://github.com/withastro/starlight/commit/62ff0074d9a3f82e46f5c62db85c04d87ff5e931) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Publishes provenance containing verifiable data to link a package back to its source repository and the specific build instructions used to publish it.

## 0.1.0

### Minor Changes

- [#2249](https://github.com/withastro/starlight/pull/2249) [`20cbf3b`](https://github.com/withastro/starlight/commit/20cbf3b6a4d1598a62fdb176ebaa849bc7b978f7) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds Starlight Markdoc preset.

  See the [“Markdoc”](https://starlight.astro.build/guides/authoring-content/#markdoc) guide to learn more on how to use this preset in a new or existing project.


================================================
FILE: packages/markdoc/Code.astro
================================================
---
import { Code as Default } from '@astrojs/starlight/components';

interface Props {
	code: string;
	lang?: string;
}

/**
 * This component is a basic wrapper for the `<Code>` component from Starlight used for Markdoc
 * fenced code blocks that ensures that we do not pass any child content to the `<Code>` component
 * which is an usage not supported by Expressive Code and would throw an error.
 */
---

<Default {...Astro.props} />


================================================
FILE: packages/markdoc/README.md
================================================
# <img src="https://github.com/withastro/starlight/assets/357379/494fcd83-42aa-4891-87e0-87402fa0b6f3" alt="" align="left" width="40" height="40"> @astrojs/starlight-markdoc

Markdoc preset for the [Starlight][starlight] documentation theme for [Astro][astro].

## Documentation

See the [Starlight Markdoc docs][docs] for how to use this preset.

## License

MIT

Copyright (c) 2024–present [Starlight contributors][contributors]

[starlight]: https://starlight.astro.build/
[astro]: https://astro.build/
[docs]: https://starlight.astro.build/guides/authoring-content/#markdoc
[contributors]: https://github.com/withastro/starlight/graphs/contributors


================================================
FILE: packages/markdoc/__tests__/markdoc.test-d.ts
================================================
import type { ComponentProps, HTMLAttributes } from 'astro/types';
import { describe, expectTypeOf, test } from 'vitest';

import {
	Aside,
	Badge,
	Card,
	CardGrid,
	Code,
	FileTree,
	Icon,
	LinkButton,
	LinkCard,
	Steps,
	TabItem,
	Tabs,
} from '@astrojs/starlight/components';

type UserComponents = keyof typeof import('@astrojs/starlight/components');
type UserComponentProps<T extends (args: any) => any> = keyof RemoveIndexSignature<
	ComponentProps<T>
>;

type MarkdocPreset = typeof import('../index.mjs').StarlightMarkdocPreset;
type MarkdocNodes = keyof MarkdocPreset['nodes'];
type MarkdocNodeAttributes<T extends MarkdocNodes> = keyof MarkdocPreset['nodes'][T]['attributes'];
type MarkdocTags = keyof MarkdocPreset['tags'];
type MarkdocTagAttributes<T extends MarkdocTags> = keyof MarkdocPreset['tags'][T]['attributes'];

describe('nodes', () => {
	test('defines attributes for fenced code blocks with support for some text markers', () => {
		type FenceAttributes = MarkdocNodeAttributes<'fence'>;

		// Markdoc default fence attributes are `content` and `language`.
		type MarkdocFenceAttributes = 'content' | 'language';

		// Ensure Markdoc default fence attributes are always mapped.
		expectTypeOf<
			Extract<FenceAttributes, MarkdocFenceAttributes>
		>().toEqualTypeOf<MarkdocFenceAttributes>();

		type UnsupportedCodeProps =
			/** The `code` and `lang` attributes mapping is tested above. */
			| 'code'
			| 'lang'
			/** Not all `<Code>` component props are supported in code fences. */
			| 'class'
			| 'hangingIndent'
			| 'locale'
			| 'preserveIndent'
			| 'useDiffSyntax'
			| 'wrap'
			/**
			 * Some props cannot be described using Markdoc attribute validation syntax.
			 * @see {@link file://./../index.mjs}
			 */
			| 'mark'
			| 'ins'
			| 'del';

		// Ensure all non-unsupported `<Code>` component props are mapped.
		expectTypeOf<Exclude<FenceAttributes, MarkdocFenceAttributes>>().toEqualTypeOf<
			Exclude<UserComponentProps<typeof Code>, UnsupportedCodeProps>
		>();
	});
});

describe('tags', () => {
	test('defines a tag for each user components', () => {
		expectTypeOf<MarkdocTags>().toEqualTypeOf<Lowercase<UserComponents>>();
	});

	test('defines all `<Aside>` component attributes', () => {
		expectTypeOf<MarkdocTagAttributes<'aside'>>().toEqualTypeOf<UserComponentProps<typeof Aside>>();
	});

	test('defines all `<Badge>` component attributes', () => {
		/**
		 * Only supports a list of well-known `<span>` attributes.
		 * @see {@link file://./../html.mjs}
		 */
		type UnsupportedBadgeProps = Exclude<keyof HTMLAttributes<'span'>, WellKnownElementAttributes>;

		expectTypeOf<MarkdocTagAttributes<'badge'>>().toEqualTypeOf<
			Exclude<UserComponentProps<typeof Badge>, UnsupportedBadgeProps>
		>();
	});

	test('defines all `<Card>` component attributes', () => {
		expectTypeOf<MarkdocTagAttributes<'card'>>().toEqualTypeOf<UserComponentProps<typeof Card>>();
	});

	test('defines all `<CardGrid>` component attributes', () => {
		expectTypeOf<MarkdocTagAttributes<'cardgrid'>>().toEqualTypeOf<
			UserComponentProps<typeof CardGrid>
		>();
	});

	test('defines all `<Code>` component attributes', () => {
		/**
		 * Some props cannot be described using Markdoc attribute validation syntax.
		 * @see {@link file://./../index.mjs}
		 */
		type UnsupportedCodeProps = 'mark' | 'ins' | 'del';

		expectTypeOf<MarkdocTagAttributes<'code'>>().toEqualTypeOf<
			Exclude<UserComponentProps<typeof Code>, UnsupportedCodeProps>
		>();
	});

	test('defines all `<FileTree>` component attributes', () => {
		expectTypeOf<MarkdocTagAttributes<'filetree'>>().toEqualTypeOf<
			UserComponentProps<typeof FileTree>
		>();
	});

	test('defines all `<Icon>` component attributes', () => {
		expectTypeOf<MarkdocTagAttributes<'icon'>>().toEqualTypeOf<UserComponentProps<typeof Icon>>();
	});

	test('defines all `<LinkButton>` component attributes', () => {
		/**
		 * Only supports a list of well-known `<a>` attributes.
		 * @see {@link file://./../html.mjs}
		 */
		type UnsupportedLinkButtonProps = Exclude<keyof HTMLAttributes<'a'>, WellKnownAnchorAttributes>;

		expectTypeOf<MarkdocTagAttributes<'linkbutton'>>().toEqualTypeOf<
			Exclude<UserComponentProps<typeof LinkButton>, UnsupportedLinkButtonProps>
		>();
	});

	test('defines all `<LinkCard>` component attributes', () => {
		/**
		 * Only supports a list of well-known `<a>` attributes.
		 * @see {@link file://./../html.mjs}
		 */
		type UnsupportedLinkCardProps = Exclude<keyof HTMLAttributes<'a'>, WellKnownAnchorAttributes>;

		expectTypeOf<MarkdocTagAttributes<'linkcard'>>().toEqualTypeOf<
			Exclude<UserComponentProps<typeof LinkCard>, UnsupportedLinkCardProps>
		>();
	});

	test('defines all `<Steps>` component attributes', () => {
		expectTypeOf<MarkdocTagAttributes<'steps'>>().toEqualTypeOf<UserComponentProps<typeof Steps>>();
	});

	test('defines all `<TabItem>` component attributes', () => {
		expectTypeOf<MarkdocTagAttributes<'tabitem'>>().toEqualTypeOf<
			UserComponentProps<typeof TabItem>
		>();
	});

	test('defines all `<Tabs>` component attributes', () => {
		expectTypeOf<MarkdocTagAttributes<'tabs'>>().toEqualTypeOf<UserComponentProps<typeof Tabs>>();
	});
});

type WellKnownElementAttributes = keyof typeof import('../html.mjs').WellKnownElementAttributes;
type WellKnownAnchorAttributes = keyof typeof import('../html.mjs').WellKnownAnchorAttributes;

// https://stackoverflow.com/a/66252656/1945960
type RemoveIndexSignature<T> = {
	[K in keyof T as string extends K
		? never
		: number extends K
			? never
			: symbol extends K
				? never
				: K]: T[K];
};


================================================
FILE: packages/markdoc/components.ts
================================================
export { default as Code } from './Code.astro';
export { default as Heading } from '@astrojs/starlight/components/AnchorHeading.astro';


================================================
FILE: packages/markdoc/html.mjs
================================================
/**
 * A list of well-known HTML element global attributes that can be used on any HTML element.
 *
 * @satisfies {HTMLElementTagAttributes<'span'>}
 * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes
 */
export const WellKnownElementAttributes = {
	class: { type: String },
	dir: { type: String, matches: ['ltr', 'rtl', 'auto'] },
	hidden: { type: String, matches: ['', 'hidden', 'until-found'] },
	id: { type: String },
	lang: { type: String },
	role: { type: String },
	style: { type: String },
	title: { type: String },
};

/**
 * A list of well-known HTML attributes that can be used on an `<a>` element.
 *
 * @satisfies {HTMLElementTagAttributes<'a'>}
 * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes
 */
export const WellKnownAnchorAttributes = {
	...WellKnownElementAttributes,
	download: { type: String },
	href: { type: String },
	hreflang: { type: String },
	media: { type: String },
	ping: { type: String },
	rel: { type: String },
	target: { type: String, matches: ['_self', '_blank', '_parent', '_top'] },
};

/**
 * The configuration of a tag attribute.
 * @typedef {NonNullable<NonNullable<import('@astrojs/markdoc/config').AstroMarkdocConfig['tags']>[string]['attributes']>[string]} TagAttributeConfig
 */

/**
 * A map of HTML attributes for a specific HTML element with their associated attribute configuration.
 * @typedef {Partial<Record<keyof import('astro/types').HTMLAttributes<T>, TagAttributeConfig>>} HTMLElementTagAttributes
 * @template {import('astro/types').HTMLTag} T
 */


================================================
FILE: packages/markdoc/index.mjs
================================================
import { component, nodes } from '@astrojs/markdoc/config';
import { WellKnownElementAttributes, WellKnownAnchorAttributes } from './html.mjs';

/**
 * The Markdoc preset for Starlight mapping Starlight components to Markdoc nodes and tags.
 *
 * - The icons are not using a `matches` to provide a list of supported icons as it is not possible
 * to import a TypeScript file in this file (which can also not be a TypeScript file). When
 * Starlight is bundled, this could be refactored to provide a list of supported icons.
 * - Some components (`<Badge>`, `<LinkButton>`, and `<LinkCard>`) support extra attributes, e.g.
 * all the attributes supported by the `<a>` tag. As Markdoc requires type definitions for each
 * attribute, only some well-known attributes are supported in these tags.
 *
 * @satisfies {import('@astrojs/markdoc/config').AstroMarkdocConfig}
 */
export const StarlightMarkdocPreset = {
	nodes: {
		fence: {
			render: component('@astrojs/starlight-markdoc/components', 'Code'),
			attributes: {
				content: {
					type: String,
					required: true,
					render: 'code',
				},
				language: {
					type: String,
					required: false,
					render: 'lang',
				},
				/**
				 * Markdoc ignores meta attributes (markers) after a fence block (e.g.
				 * ```js title="example.js" del={2} ins={3-4} {6} ).
				 * This means that Expressive Code markers defined after the fence block are ignored and
				 * users would need to either use the Markdoc syntax for fence attributes or the `code` tag
				 * instead.
				 *
				 * @see https://github.com/withastro/astro/blob/9f943c1344671b569a0d1ddba683b3cca0068adc/packages/integrations/markdoc/src/extensions/shiki.ts#L15-L17
				 * @see https://github.com/markdoc/markdoc/discussions/318#discussioncomment-4821979
				 */
				frame: {
					type: String,
					required: false,
					default: 'auto',
					matches: ['auto', 'code', 'terminal', 'none'],
				},
				meta: {
					type: String,
					required: false,
				},
				title: {
					type: String,
					required: false,
				},
				/**
				 * `mark`, `ins`, `del`, and the label syntax are not supported as the Markdoc attribute
				 * validation syntax does not allow to describe properly all the possible values.
				 * Users should use the `meta` attribute instead.
				 *
				 * @see https://expressive-code.com/key-features/code-component/#mark--ins--del
				 * @see https://expressive-code.com/key-features/code-component/#meta
				 */
			},
		},
	},
	tags: {
		aside: {
			render: component('@astrojs/starlight/components', 'Aside'),
			attributes: {
				icon: {
					type: String,
					required: false,
				},
				title: {
					type: String,
					required: false,
				},
				type: {
					type: String,
					required: false,
					default: 'note',
					matches: ['note', 'danger', 'caution', 'tip'],
				},
			},
		},
		badge: {
			render: component('@astrojs/starlight/components', 'Badge'),
			attributes: {
				...WellKnownElementAttributes,
				text: {
					type: String,
					required: true,
				},
				size: {
					type: String,
					required: false,
					default: 'small',
					matches: ['small', 'medium', 'large'],
				},
				variant: {
					type: String,
					required: false,
					matches: ['note', 'tip', 'danger', 'caution', 'success'],
				},
			},
		},
		card: {
			render: component('@astrojs/starlight/components', 'Card'),
			attributes: {
				icon: {
					type: String,
					required: false,
				},
				title: {
					type: String,
					required: true,
				},
			},
		},
		cardgrid: {
			render: component('@astrojs/starlight/components', 'CardGrid'),
			attributes: {
				stagger: {
					type: Boolean,
					required: false,
					default: false,
				},
			},
		},
		code: {
			render: component('@astrojs/starlight/components', 'Code'),
			attributes: {
				class: {
					type: String,
					required: false,
				},
				code: {
					type: String,
					required: true,
				},
				hangingIndent: {
					type: Number,
					required: false,
				},
				lang: {
					type: String,
					required: false,
				},
				meta: {
					type: String,
					required: false,
				},
				locale: {
					type: String,
					required: false,
				},
				frame: {
					type: String,
					required: false,
					default: 'auto',
					matches: ['auto', 'code', 'terminal', 'none'],
				},
				preserveIndent: {
					type: Boolean,
					required: false,
					default: true,
				},
				title: {
					type: String,
					required: false,
				},
				useDiffSyntax: {
					type: Boolean,
					required: false,
					default: false,
				},
				wrap: {
					type: Boolean,
					required: false,
					default: false,
				},
				/**
				 * `mark`, `ins`, `del`, and the label syntax are not supported as the Markdoc attribute
				 * validation syntax does not allow to describe properly all the possible values.
				 * Users should use the `meta` attribute instead.
				 *
				 * @see https://expressive-code.com/key-features/code-component/#mark--ins--del
				 * @see https://expressive-code.com/key-features/code-component/#meta
				 */
			},
		},
		filetree: {
			render: component('@astrojs/starlight/components', 'FileTree'),
			attributes: {},
		},
		icon: {
			render: component('@astrojs/starlight/components', 'Icon'),
			attributes: {
				class: {
					type: String,
					required: false,
				},
				color: {
					type: String,
					required: false,
				},
				label: {
					type: String,
					required: false,
				},
				name: {
					type: String,
					required: true,
				},
				size: {
					type: String,
					required: false,
				},
			},
		},
		linkbutton: {
			render: component('@astrojs/starlight/components', 'LinkButton'),
			attributes: {
				...WellKnownAnchorAttributes,
				href: {
					type: String,
					required: true,
				},
				icon: {
					type: String,
					required: false,
				},
				iconPlacement: {
					type: String,
					required: false,
					default: 'end',
					matches: ['start', 'end'],
				},
				variant: {
					type: String,
					required: false,
					default: 'primary',
					matches: ['primary', 'secondary', 'minimal'],
				},
			},
		},
		linkcard: {
			render: component('@astrojs/starlight/components', 'LinkCard'),
			attributes: {
				...WellKnownAnchorAttributes,
				description: {
					type: String,
					required: false,
				},
				href: {
					type: String,
					required: true,
				},
				title: {
					type: String,
					required: true,
				},
			},
		},
		steps: {
			render: component('@astrojs/starlight/components', 'Steps'),
			attributes: {},
		},
		tabitem: {
			render: component('@astrojs/starlight/components', 'TabItem'),
			attributes: {
				icon: {
					type: String,
					required: false,
				},
				label: {
					type: String,
					required: true,
				},
			},
		},
		tabs: {
			render: component('@astrojs/starlight/components', 'Tabs'),
			attributes: {
				syncKey: {
					type: String,
					required: false,
				},
			},
		},
	},
};

/**
 * Markdoc preset that configures Starlight’s built-in components.
 * @return {import('@astrojs/markdoc/config').AstroMarkdocConfig}
 */
export default function starlightMarkdoc({ headingLinks = true } = {}) {
	return {
		...StarlightMarkdocPreset,
		nodes: {
			...StarlightMarkdocPreset.nodes,
			...(headingLinks
				? {
						heading: {
							...nodes.heading,
							render: component('@astrojs/starlight-markdoc/components', 'Heading'),
						},
					}
				: {}),
		},
	};
}


================================================
FILE: packages/markdoc/package.json
================================================
{
  "name": "@astrojs/starlight-markdoc",
  "version": "0.6.0",
  "description": "Markdoc preset for the Starlight documentation theme for Astro",
  "author": "Chris Swithinbank <swithinbank@gmail.com>",
  "license": "MIT",
  "repository": {
    "type": "git",
    "url": "https://github.com/withastro/starlight",
    "directory": "packages/markdoc"
  },
  "bugs": "https://github.com/withastro/starlight/issues",
  "homepage": "https://starlight.astro.build",
  "type": "module",
  "exports": {
    ".": "./index.mjs",
    "./components": "./components.ts"
  },
  "devDependencies": {
    "@astrojs/markdoc": "^1.0.0",
    "@astrojs/starlight": "workspace:*",
    "vitest": "^4.1.0"
  },
  "peerDependencies": {
    "@astrojs/markdoc": "^1.0.0",
    "@astrojs/starlight": ">=0.38.0"
  },
  "publishConfig": {
    "provenance": true
  }
}


================================================
FILE: packages/starlight/.gitignore
================================================
# Astro generates this during tests, but we want to ignore it.
env.d.ts
__tests__/**/types.d.ts
.astro


================================================
FILE: packages/starlight/.npmignore
================================================
# Vitest
__coverage__/
__tests__/
__e2e__/
vitest.*
playwright.config.ts
# Astro generates this during tests, but we want to ignore it.
src/env.d.ts


================================================
FILE: packages/starlight/CHANGELOG.md
================================================
# @astrojs/starlight

## 0.38.2

### Patch Changes

- [#3759](https://github.com/withastro/starlight/pull/3759) [`f24ce99`](https://github.com/withastro/starlight/commit/f24ce99a1a859920152e177f73afddce5c11902e) Thanks [@MilesChou](https://github.com/MilesChou)! - Fixes an issue where monolingual sites using a region-specific locale (e.g., `zh-TW`) as the default would incorrectly display base language translations (e.g., `zh` Simplified Chinese) instead of the region-specific ones (e.g., `zh-TW` Traditional Chinese).

- [#3768](https://github.com/withastro/starlight/pull/3768) [`a4c6c20`](https://github.com/withastro/starlight/commit/a4c6c20e67c76caf1dfdb0c67b0fa1df15ef52b7) Thanks [@delucis](https://github.com/delucis)! - Improves performance of sidebar generation for sites with very large sidebars

## 0.38.1

### Patch Changes

- [#3751](https://github.com/withastro/starlight/pull/3751) [`fb955ff`](https://github.com/withastro/starlight/commit/fb955ff39c3244edf808495c557fb84ce2aab260) Thanks [@pyxelr](https://github.com/pyxelr)! - Fixes a regression causing global `tableOfContents` config to be ignored

## 0.38.0

### Minor Changes

- [#3644](https://github.com/withastro/starlight/pull/3644) [`0d2e7ed`](https://github.com/withastro/starlight/commit/0d2e7ed74a604b028fcab0c81b4c35c0c9365343) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds support for Astro v6, drops support for Astro v5.

  #### Upgrade Astro and dependencies

  ⚠️ **BREAKING CHANGE:** Astro v5 is no longer supported. Make sure you [update Astro](https://docs.astro.build/en/guides/upgrade-to/v6/) and any other official integrations at the same time as updating Starlight:

  ```sh
  npx @astrojs/upgrade
  ```

  _Community Starlight plugins and Astro integrations may also need to be manually updated to work with Astro v6. If you encounter any issues, please reach out to the plugin or integration author to see if it is a known issue or if an updated version is being worked on._

  #### Update your collections

  ⚠️ **BREAKING CHANGE:** Drops support for content collections backwards compatibility.

  In Astro 5.x, projects could delay upgrading to the new Content Layer API introduced for content collections because of some existing automatic backwards compatibility that was not previously behind a flag. This meant that it was possible to upgrade from Astro 4 to Astro 5 without updating your content collections, even if you had not enabled the `legacy.collections` flag. Projects would continue to build, and no errors or warnings would be displayed.

  Astro v6.0 now removes this automatic legacy content collections support, along with the `legacy.collections` flag.

  If you experience content collections errors after updating to v6, [check your project for any removed legacy features](https://docs.astro.build/en/guides/upgrade-to/v6/#if-you-have) that may need updating to the Content Layer API. See [the Starlight v0.30.0 upgrade guide](https://github.com/withastro/starlight/blob/main/packages/starlight/CHANGELOG.md#0300) for detailed instructions on upgrading legacy collections to the new Content Layer API.

  If you are unable to make any changes to your collections at this time, including Starlight's default `docs` and `i18n` collections, you can enable the [`legacy.collectionsBackwardsCompat` flag](https://docs.astro.build/en/reference/legacy-flags/#collectionsbackwardscompat) to upgrade to v6 without updating your collections. This temporary flag preserves some legacy v4 content collections features, and will allow you to keep your collections in their current state until the legacy flag is no longer supported.

- [#3704](https://github.com/withastro/starlight/pull/3704) [`375edcc`](https://github.com/withastro/starlight/commit/375edccde7f8d18e0ce2140de0632c2ad72e3ff8) Thanks [@florian-lefebvre](https://github.com/florian-lefebvre)! - Fixes autocomplete for components exported from `@astrojs/starlight/components/*`

  **⚠️ Potentially breaking change:** This change moves some files used in Starlight’s component internals out of the `components/` directory. Direct use of these files was not and is not officially supported. If you previously imported `TableOfContents/starlight-toc.ts`, `TableOfContents/TableOfContentsList.astro`, `Icons.ts`, or `SidebarPersistState.ts`, please review your code when updating.

- [#3729](https://github.com/withastro/starlight/pull/3729) [`3642625`](https://github.com/withastro/starlight/commit/3642625db19a37abb535e00036414c84e1c16933) Thanks [@delucis](https://github.com/delucis)! - Improves Starlight’s default body font stack to better support languages such as Chinese, Japanese, and Korean on Windows.
  For most users there should be no visible change.

  If you would prefer to keep the previous font stack, you can add the following custom CSS to your site:

  ```css
  :root {
    --sl-font-system: ui-sans-serif, system-ui, 'Segoe UI', Roboto,
      'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji',
      'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
  }
  ```

- [#3598](https://github.com/withastro/starlight/pull/3598) [`fff38d5`](https://github.com/withastro/starlight/commit/fff38d58b637c78b0563f6b02e44a41c13106cdb) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Makes hover styles consistent in Starlight’s navigation bar

  Previously, the social icon links and language/theme switchers in Starlight’s navigation bar, dimmed on hover.
  After this change, they now increase in contrast on hover instead.
  This matches hover behavior elsewhere, for example in the sidebar, table of contents, or search button.

  ⚠️ **Potentially breaking change:** this is a subtle change to the hover style colors.
  If you want to preserve the previous styling, you can add the following [custom CSS](https://starlight.astro.build/guides/css-and-tailwind/#custom-css-styles) to your site:

  ```css
  starlight-theme-select label,
  starlight-lang-select label {
    color: var(--sl-color-gray-1);

    &:hover {
      color: var(--sl-color-white);
    }
  }

  .social-icons a:hover {
    color: var(--sl-color-text-accent);
    opacity: 0.66;
  }
  ```

## 0.37.7

### Patch Changes

- [#3726](https://github.com/withastro/starlight/pull/3726) [`8a09b60`](https://github.com/withastro/starlight/commit/8a09b60b03ae2b99d3418f41e984ffa46468e3a2) Thanks [@delucis](https://github.com/delucis)! - Fixes an issue using components containing scripts inside Starlight’s steps component in versions of Astro >= 5.16.9

## 0.37.6

### Patch Changes

- [#3645](https://github.com/withastro/starlight/pull/3645) [`a562096`](https://github.com/withastro/starlight/commit/a562096380287fa7fa925664d04071a5831f274b) Thanks [@mschoeffmann](https://github.com/mschoeffmann)! - Adds icons for Chrome, Edge, Firefox, and Safari

## 0.37.5

### Patch Changes

- [#3675](https://github.com/withastro/starlight/pull/3675) [`0ba556d`](https://github.com/withastro/starlight/commit/0ba556d7d49dd4904f8aa8524c105bf1ceeec85c) Thanks [@controversial](https://github.com/controversial)! - Excludes the accessible labels for heading anchor links from Pagefind results

## 0.37.4

### Patch Changes

- [#3534](https://github.com/withastro/starlight/pull/3534) [`703fab0`](https://github.com/withastro/starlight/commit/703fab085b99303c0c01325c9bb869ea7e1418c4) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes support for running builds when `npx` is unavailable.

  Previously, Starlight would spawn a process to run the Pagefind search indexing binary using `npx`. On platforms where `npx` isn’t available, this could cause issues. Starlight now runs Pagefind using its Node.js API to avoid a separate process. As a side effect, you may notice that logging during builds is now less verbose.

- [#3656](https://github.com/withastro/starlight/pull/3656) [`a0e6368`](https://github.com/withastro/starlight/commit/a0e636838092d30cb6b8f80e5535ad842e52d759) Thanks [@delucis](https://github.com/delucis)! - Fixes several edge cases in highlighting the current page heading in Starlight’s table of contents

- [#3663](https://github.com/withastro/starlight/pull/3663) [`00cbf00`](https://github.com/withastro/starlight/commit/00cbf001fee4fd59f351c7a6c0f8c353c7c41f13) Thanks [@lines-of-codes](https://github.com/lines-of-codes)! - Adds Thai language support

- [#3658](https://github.com/withastro/starlight/pull/3658) [`ac79329`](https://github.com/withastro/starlight/commit/ac793290f0dbd21f9b9a5d6f60aa315043815227) Thanks [@delucis](https://github.com/delucis)! - Avoids adding redundant `aria-current="false"` attributes to sidebar entries

- [#3382](https://github.com/withastro/starlight/pull/3382) [`db295c2`](https://github.com/withastro/starlight/commit/db295c2a3d75aad71a41702f33001195d89de5d2) Thanks [@trueberryless](https://github.com/trueberryless)! - Fixes an issue where the mobile table of contents is unable to find the first heading when a page has a tall banner.

## 0.37.3

### Patch Changes

- [#3648](https://github.com/withastro/starlight/pull/3648) [`292666c`](https://github.com/withastro/starlight/commit/292666cdcb9d81da2ee32ab5a3e83b2c44cea5cd) Thanks [@maxchang3](https://github.com/maxchang3)! - Prevents unwanted font size adjustments on iOS after orientation changes.

## 0.37.2

### Patch Changes

- [#3647](https://github.com/withastro/starlight/pull/3647) [`9f4efc3`](https://github.com/withastro/starlight/commit/9f4efc3c59ee41038b7c0550230a10bb35ad0e50) Thanks [@gerstenbergit](https://github.com/gerstenbergit)! - Adds Greek language support

## 0.37.1

### Patch Changes

- [#3603](https://github.com/withastro/starlight/pull/3603) [`30f6e7f`](https://github.com/withastro/starlight/commit/30f6e7fa83ca0a248b1b59d616f55a6f933334a2) Thanks [@delucis](https://github.com/delucis)! - Fixes support for providing an absolute URL to Starlight’s `favicon` configuration option

## 0.37.0

### Minor Changes

- [#3491](https://github.com/withastro/starlight/pull/3491) [`28810f0`](https://github.com/withastro/starlight/commit/28810f085faf017f3fedd1407e741bdf6c232848) Thanks [@JusticeMatthew](https://github.com/JusticeMatthew)! - Changes text overflow styling in Markdown content

  ⚠️ **Potentially breaking change:** This release switches the [`overflow-wrap`](https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-wrap) CSS style for common elements to `break-word`. In most cases, there should be little visual impact, but this change can impact how layouts with implicit sizing (such as tables) look, improving legibility in how words wrap.

  If you want to preserve the previous styling, you can add the following [custom CSS](https://starlight.astro.build/guides/css-and-tailwind/#custom-css-styles) to your site:

  ```css
  p,
  h1,
  h2,
  h3,
  h4,
  h5,
  h6,
  code {
    overflow-wrap: anywhere;
  }
  ```

- [#3351](https://github.com/withastro/starlight/pull/3351) [`239698c`](https://github.com/withastro/starlight/commit/239698c53625f5411792e314994d20c20f9ede77) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Ensures that Starlight CSS layer order is predictable in custom pages using the `<StarlightPage>` component.

  Previously, due to how [import order](https://docs.astro.build/en/guides/styling/#import-order) works in Astro, the `<StarlightPage>` component had to be the first import in custom pages to set up [cascade layers](https://starlight.astro.build/guides/css-and-tailwind/#cascade-layers) used internally by Starlight to manage the order of its styles.

  With this change, this restriction no longer applies and Starlight’s styles will be applied correctly regardless of the import order of the `<StarlightPage>` component.

- [#3521](https://github.com/withastro/starlight/pull/3521) [`ca7b771`](https://github.com/withastro/starlight/commit/ca7b771e5bd4da3fe500bbad562e69d5880690ea) Thanks [@shubham-padia](https://github.com/shubham-padia)! - Fixes an issue where a vertical scrollbar could be displayed on the Starlight `<Tabs>` component when zooming the page

  ⚠️ **Potentially breaking change:** The `<Tabs>` component no longer uses `margin-bottom` and `border-bottom` to highlight the current tab. This is now done with a `box-shadow`. If you have custom styling for your tabs, you may need to update it.

  If you want to preserve the previous styling, you can add the following custom CSS to your site:

  ```css
  starlight-tabs .tab {
    margin-bottom: -2px;
  }

  starlight-tabs .tab > [role='tab'] {
    border-bottom: 2px solid var(--sl-color-gray-5);
    box-shadow: none;
  }

  starlight-tabs .tab [role='tab'][aria-selected='true'] {
    border-color: var(--sl-color-text-accent);
  }
  ```

- [#3549](https://github.com/withastro/starlight/pull/3549) [`1cf50eb`](https://github.com/withastro/starlight/commit/1cf50ebb18c0232be581cf0aff0c192e4c421e55) Thanks [@jacobdalamb](https://github.com/jacobdalamb)! - Updates the default sans-serif system font stack, dropping support for the `-apple-system` and `BlinkMacSystemFont` font names used in older browsers. These are no longer needed in [browsers officially supported by Starlight](https://browsersl.ist/#q=%3E+0.5%25%2C+not+dead%2C+Chrome+%3E%3D+105%2C+Edge+%3E%3D+105%2C+Firefox+%3E%3D+121%2C+Safari+%3E%3D+15.4%2C+iOS+%3E%3D+15.4%2C+not+op_mini+all).

  If you still need to support older browsers, you can add the following custom CSS to your site:

  ```css
  :root {
    --sl-font-system: ui-sans-serif, system-ui, -apple-system,
      BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial,
      'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji',
      'Segoe UI Symbol', 'Noto Color Emoji';
  }
  ```

- [#3332](https://github.com/withastro/starlight/pull/3332) [`f61f99d`](https://github.com/withastro/starlight/commit/f61f99dc09c59d26761ffebc611969e20b866191) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds a new [`markdown.processedDirs`](https://starlight.astro.build/reference/configuration/#processeddirs) configuration option to specify additional directories where files should be processed by Starlight’s Markdown pipeline.

  By default, Starlight’s processing only applies to Markdown and MDX content loaded using Starlight’s `docsLoader()`. This new option allows to extend this processing to other directories, which can be useful if you are rendering content from a custom content collection using the `<StarlightPage>` component and expect Starlight’s Markdown processing to be applied to that content as well.

## 0.36.3

### Patch Changes

- [#3555](https://github.com/withastro/starlight/pull/3555) [`547dc30`](https://github.com/withastro/starlight/commit/547dc30558b388bfc0505ab0fd8269cecaed462a) Thanks [@Its-Just-Nans](https://github.com/Its-Just-Nans)! - Improves the error message thrown when using a file in the `public/` directory with Starlight’s `customCss` configuration option

- [#3496](https://github.com/withastro/starlight/pull/3496) [`b78fda4`](https://github.com/withastro/starlight/commit/b78fda45be17be7a260309251e82504f9ac8e97a) Thanks [@delucis](https://github.com/delucis)! - Fixes invalid `<head>` output when configuration is missing:

  - Omits `<meta property="og:description" />` if Starlight’s `description` option is unset
  - Omits `<link rel="canonical" />` and `<meta property="og:url" />` if Astro’s `site` option is unset

- [#3511](https://github.com/withastro/starlight/pull/3511) [`8727df1`](https://github.com/withastro/starlight/commit/8727df1a1b1c82f1303613226000afd53ffe4e36) Thanks [@astrobot-houston](https://github.com/astrobot-houston)! - Updates the `seti:gitlab` icon to match latest version from Seti UI Icons

## 0.36.2

### Patch Changes

- [#3500](https://github.com/withastro/starlight/pull/3500) [`7700456`](https://github.com/withastro/starlight/commit/770045663c8ca3cc44983dd0d444955eba441243) Thanks [@delucis](https://github.com/delucis)! - This is the first release published with OIDC trusted publishing.

- [#3484](https://github.com/withastro/starlight/pull/3484) [`620fb38`](https://github.com/withastro/starlight/commit/620fb3857e40a37a2f8bdf2d0430b106e8f80cdb) Thanks [@gboubeta-uvigo](https://github.com/gboubeta-uvigo)! - Improves Spanish UI translations

## 0.36.1

### Patch Changes

- [#3479](https://github.com/withastro/starlight/pull/3479) [`2fec483`](https://github.com/withastro/starlight/commit/2fec4833d4867db35b77079ce3026b79ba1e0441) Thanks [@gboubeta-uvigo](https://github.com/gboubeta-uvigo)! - Updates Galician UI translations

- [#3457](https://github.com/withastro/starlight/pull/3457) [`c6c0c51`](https://github.com/withastro/starlight/commit/c6c0c5114a659b22ffcc4c2085ad8c1fc4f43a5d) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Deduplicates sitemap link tags in the head.

  When [enabling sitemap](https://starlight.astro.build/guides/customization/#enable-sitemap) in Starlight, a `<link rel="sitemap" href="/sitemap-index.xml">` tag is automatically added to the head of each page. Manually specifying sitemap link tags using the Starlight [`head` configuration option](https://starlight.astro.build/reference/configuration/#head) or the [`head` frontmatter field](https://starlight.astro.build/reference/frontmatter/#head) will now override the default sitemap link tag added by Starlight.

  This change ensures that users manually adding the `@astrojs/sitemap` integration to the Astro `integrations` array for more fine-grained control over sitemap generation and also using the [`filenameBase` integration option](https://docs.astro.build/en/guides/integrations-guide/sitemap/#filenamebase) can customize the sitemap link tag in the head.

- [#3448](https://github.com/withastro/starlight/pull/3448) [`1fc7501`](https://github.com/withastro/starlight/commit/1fc7501d16218c7f156c5e90df25ae6fbb8abfea) Thanks [@dionysuzx](https://github.com/dionysuzx)! - Enlarges the Farcaster icon to better match other social icons

- [#3473](https://github.com/withastro/starlight/pull/3473) [`07204dd`](https://github.com/withastro/starlight/commit/07204dd7b8b6ee71bf24ff9c7d70fc7306bf2076) Thanks [@gboubeta](https://github.com/gboubeta)! - Fixes a typo in Galician table of contents label

## 0.36.0

### Minor Changes

- [#3427](https://github.com/withastro/starlight/pull/3427) [`c3b2d0f`](https://github.com/withastro/starlight/commit/c3b2d0fc37bb9b7b6abc6c11b760a4114690ccd4) Thanks [@delucis](https://github.com/delucis)! - Fixes styling of labels that wrap across multiple lines in `<Tabs>` component

  ⚠️ **Potentially breaking change:** Tab labels now have a narrower line-height and additional vertical padding. If you have custom CSS targeting the `<Tabs>` component, you may want to double check the visual appearance of your tabs when updating.

  If you want to preserve the previous styling, you can add the following custom CSS to your site:

  ```css
  .tab > [role='tab'] {
    line-height: var(--sl-line-height);
    padding-block: 0;
  }
  ```

- [#3380](https://github.com/withastro/starlight/pull/3380) [`3364af3`](https://github.com/withastro/starlight/commit/3364af31e535d62ee7b045e6d9cf97c7e58df981) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Makes head entry parsing stricter in Starlight config and content frontmatter.

  **⚠️ Potentially breaking change:** Previously Starlight would accept a head entry for a `meta` tag defining some `content` which generates invalid HTML as `<meta>` is a void element which cannot have any child nodes. Now, it is an error to define a `meta` tag including some `content`.

  If you see errors after updating, look for head entries in the Starlight configuration in the `astro.config.mjs` file or in the frontmatter of your content files that include a `content` property for a `meta` tag. To fix the error, move the `content` property to the `attrs` object with at least an additional attribute to identify the kind of metadata it represents:

  ```diff
  head: {
    tag: 'meta',
  - content: 'foo',
    attrs: {
      name: 'my-meta',
  +   content: 'foo',
    },
  },
  ```

- [#3340](https://github.com/withastro/starlight/pull/3340) [`2018c31`](https://github.com/withastro/starlight/commit/2018c31b0f559d51478bfbf9f12cfba76b4e74fc) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds missing vertical spacing between Markdown content and UI Framework components using [client directives](https://docs.astro.build/en/reference/directives-reference/#client-directives).

  **⚠️ Potentially breaking change:** By default, Starlight applies some vertical spacing (`--sl-content-gap-y`) between Markdown content blocks. This change introduces similar spacing between Markdown content blocks and UI Framework components using client directives which was not present before.

  If you were relying on the previous behavior, you can manually override the spacing by manually specifying the top margin on the component using [custom CSS](https://starlight.astro.build/guides/css-and-tailwind/#custom-css-styles), e.g. by relying on a CSS class to target the component.

  ```css
  .my-custom-component {
    margin-top: 0;
  }
  ```

### Patch Changes

- [#3423](https://github.com/withastro/starlight/pull/3423) [`a0d0670`](https://github.com/withastro/starlight/commit/a0d0670bce5827b90fd0102fa3517814367760e7) Thanks [@andersk](https://github.com/andersk)! - Fixes HTML validity in sidebar groups by ensuring `<summary>` is the first child of `<details>`

## 0.35.3

### Patch Changes

- [#3416](https://github.com/withastro/starlight/pull/3416) [`fcc0633`](https://github.com/withastro/starlight/commit/fcc0633ab14fc602f5c540972446e22c79746042) Thanks [@randomguy-2650](https://github.com/randomguy-2650)! - Updates German UI translations to be more idiomatic.

- [#1640](https://github.com/withastro/starlight/pull/1640) [`d1b3828`](https://github.com/withastro/starlight/commit/d1b3828cdfe8114884ab65049581e37624422ac4) Thanks [@hippotastic](https://github.com/hippotastic)! - Refactors various internal systems, improving code quality and maintainability.

- [#3421](https://github.com/withastro/starlight/pull/3421) [`97e8103`](https://github.com/withastro/starlight/commit/97e8103c5793d583931575dbe17924ef88a5b6fd) Thanks [@andersk](https://github.com/andersk)! - Removes an invalid `value` attribute from the language and theme selectors

- [#3422](https://github.com/withastro/starlight/pull/3422) [`9200fac`](https://github.com/withastro/starlight/commit/9200fac71ebe6e7bbbecee3d1893e744db01dc6e) Thanks [@andersk](https://github.com/andersk)! - Refactors collapsible sidebar sections and “on this page” dropdown to use `<span>` instead of `<div>`

## 0.35.2

### Patch Changes

- [#3341](https://github.com/withastro/starlight/pull/3341) [`10f6fe2`](https://github.com/withastro/starlight/commit/10f6fe22a981247293ee4de106736f1a6ae24b6a) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Prevents potential build issues with the Astro Cloudflare adapter due to the dependency on Node.js builtins.

- [#3327](https://github.com/withastro/starlight/pull/3327) [`bf58c60`](https://github.com/withastro/starlight/commit/bf58c60b9c3d5f5efdafbdba83cefa0566a367dc) Thanks [@delucis](https://github.com/delucis)! - Fixes a routing bug for docs pages with a slug authored with non-normalized composition. This could occur for filenames containing diacritics in some circumstances, causing 404s.

## 0.35.1

### Patch Changes

- [#3325](https://github.com/withastro/starlight/pull/3325) [`4cf28f2`](https://github.com/withastro/starlight/commit/4cf28f2afd50fb2a3f8c9149a824aaac47c12af6) Thanks [@mniinio](https://github.com/mniinio)! - Adds Finnish language support

## 0.35.0

### Minor Changes

- [#2261](https://github.com/withastro/starlight/pull/2261) [`778b743`](https://github.com/withastro/starlight/commit/778b743cdb832551ed576c745728358d8bbf9d7a) Thanks [@shubham-padia](https://github.com/shubham-padia)! - Adds support for using any of Starlight’s built-in icons in asides.

- [#3272](https://github.com/withastro/starlight/pull/3272) [`e7fe267`](https://github.com/withastro/starlight/commit/e7fe26720b7527c39e3aab42ea9fd0468f92167c) Thanks [@delucis](https://github.com/delucis)! - Adds a new `generateId` option to Starlight’s `docsLoader()`

  This enables overriding the default sluggifier used to convert content filenames to URLs.

- [#3276](https://github.com/withastro/starlight/pull/3276) [`3917b20`](https://github.com/withastro/starlight/commit/3917b206da26522f73bbe0c1120de9acae5972c5) Thanks [@delucis](https://github.com/delucis)! - Excludes banner content from search results

  Previously, content set in [`banner`](https://starlight.astro.build/reference/frontmatter/#banner) in page frontmatter was indexed by Starlight’s default search provider Pagefind. This could cause unexpected search results, especially for sites setting a common banner content on multiple pages. Starlight’s default `Banner` component is now excluded from search indexing.

  This change does not impact `Banner` overrides using custom components.

- [#3266](https://github.com/withastro/starlight/pull/3266) [`1161af0`](https://github.com/withastro/starlight/commit/1161af0c2fe26485da6123f8fd7205c53b0e45e5) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds support for custom HTML attributes on autogenerated sidebar links using the [`autogenerate.attrs`](https://starlight.astro.build/guides/sidebar/#custom-html-attributes-for-autogenerated-links) option.

- [#3274](https://github.com/withastro/starlight/pull/3274) [`80ccff7`](https://github.com/withastro/starlight/commit/80ccff7c542794e04a4d2abb17227a076fa57c5d) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes an issue where some Starlight remark and rehype plugins were transforming Markdown and MDX content in non-Starlight pages.

  ⚠️ **BREAKING CHANGE:**

  Previously, some of Starlight’s remark and rehype plugins, most notably the plugin transforming Starlight's custom Markdown syntax for [rendering asides](https://starlight.astro.build/guides/authoring-content/#asides), were applied to all Markdown and MDX content. This included content from [individual Markdown pages](https://docs.astro.build/en/guides/markdown-content/#individual-markdown-pages) and content from [content collections](https://docs.astro.build/en/guides/content-collections/) other than the `docs` collection used by Starlight.

  This change restricts the application of Starlight’s remark and rehype plugins to only Markdown and MDX content loaded using Starlight's [`docsLoader()`](https://starlight.astro.build/reference/configuration/#docsloader). If you were relying on this behavior, please let us know about your use case in the dedicated `#starlight` channel in the [Astro Discord](https://astro.build/chat/) or by [opening an issue](https://github.com/withastro/starlight/issues/new?template=---01-bug-report.yml).

### Patch Changes

- [#3266](https://github.com/withastro/starlight/pull/3266) [`1161af0`](https://github.com/withastro/starlight/commit/1161af0c2fe26485da6123f8fd7205c53b0e45e5) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Ensures invalid sidebar group configurations using the `attrs` option are properly reported as a type error.

  Previously, invalid sidebar group configurations using the `attrs` option were not reported as a type error but only surfaced at runtime. This change is only a type-level change and does not affect the runtime behavior of Starlight which does not support the `attrs` option for sidebar groups.

- [#3274](https://github.com/withastro/starlight/pull/3274) [`80ccff7`](https://github.com/withastro/starlight/commit/80ccff7c542794e04a4d2abb17227a076fa57c5d) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Prevents Starlight remark and rehype plugins from transforming Markdown and MDX content when using the Astro [`renderMarkdown()`](https://docs.astro.build/en/reference/content-loader-reference/#rendermarkdown) content loader API.

## 0.34.8

### Patch Changes

- [#3306](https://github.com/withastro/starlight/pull/3306) [`21fcd94`](https://github.com/withastro/starlight/commit/21fcd944d528557b89fc8b351579beabdcc06ff6) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes a regression in Starlight version `0.34.5` that caused multilingual sites with a default locale explicitly set to `root` to report a configuration error.

## 0.34.7

### Patch Changes

- [#3298](https://github.com/withastro/starlight/pull/3298) [`7bd02e3`](https://github.com/withastro/starlight/commit/7bd02e37650da59ed6cdfe275473ae2dac6a2d48) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes a potential issue with [`absolutePathToLang()`](https://starlight.astro.build/reference/plugins/#absolutepathtolang) plugin API not handling paths with spaces correctly.

## 0.34.6

### Patch Changes

- [#3293](https://github.com/withastro/starlight/pull/3293) [`88f0d34`](https://github.com/withastro/starlight/commit/88f0d349ee4e8c42bd38adc01031edf4c7b92342) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes an issue preventing to override the slug of a page with the [`slug` frontmatter property](https://starlight.astro.build/reference/frontmatter/#slug) using the `/` value.

## 0.34.5

### Patch Changes

- [#3282](https://github.com/withastro/starlight/pull/3282) [`7680e87`](https://github.com/withastro/starlight/commit/7680e878fc55eba3fe0cf90e793970d3b72d166a) Thanks [@alvinometric](https://github.com/alvinometric)! - Moves padding of `<main>` element to a `--sl-main-pad` CSS custom property to simplify setting custom values

- [#3288](https://github.com/withastro/starlight/pull/3288) [`131371e`](https://github.com/withastro/starlight/commit/131371e0c897f9c7ea673d93e8f405200d04d312) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes a potential configuration issue for multilingual sites with a default language including a regional subtag.

## 0.34.4

### Patch Changes

- [#3205](https://github.com/withastro/starlight/pull/3205) [`95d124a`](https://github.com/withastro/starlight/commit/95d124ae99f207afd83f305943fa29df32cbbfc9) Thanks [@sgalcheung](https://github.com/sgalcheung)! - Fixes an issue preventing to use the `<StarlightPage>` component when the `docs` content collection that Starlight uses does not exist.

- [#3206](https://github.com/withastro/starlight/pull/3206) [`e6ea584`](https://github.com/withastro/starlight/commit/e6ea5848b20afbb654fd6684956336491b974dc7) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes a text selection issue for heading with a clickable anchor link when using double click to select text in Chrome and Safari.

- [#3233](https://github.com/withastro/starlight/pull/3233) [`3064c40`](https://github.com/withastro/starlight/commit/3064c40b54227b6309b35b6e44e397fae8f284a4) Thanks [@torn4dom4n](https://github.com/torn4dom4n)! - Updates Vietnamese UI translations.

- [#3248](https://github.com/withastro/starlight/pull/3248) [`16c1239`](https://github.com/withastro/starlight/commit/16c1239b36346e84b794fab819d6ad7a9854a244) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Prevents [icons in the `<Card>` component](https://starlight.astro.build/components/cards/#add-icons-to-cards) from being shrunk in some narrow viewports.

- [#3225](https://github.com/withastro/starlight/pull/3225) [`21b93b8`](https://github.com/withastro/starlight/commit/21b93b8ac1894c5ada99a641e516086ebee6ea37) Thanks [@randomguy-2650](https://github.com/randomguy-2650)! - Updates German UI translations

## 0.34.3

### Patch Changes

- [#3058](https://github.com/withastro/starlight/pull/3058) [`274cc06`](https://github.com/withastro/starlight/commit/274cc06112824384771b944f504ab0faab45e2b9) Thanks [@techfg](https://github.com/techfg)! - Fixes display of focus indicator around site title

- [#3181](https://github.com/withastro/starlight/pull/3181) [`449c822`](https://github.com/withastro/starlight/commit/449c8229effaab19ece3c0a34e32595809c33cc8) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes an issue where all headings in Markdown and MDX content were rendered with a [clickable anchor link](https://starlight.astro.build/reference/configuration/#headinglinks), even in non-Starlight pages.

- [#3168](https://github.com/withastro/starlight/pull/3168) [`ca693fe`](https://github.com/withastro/starlight/commit/ca693feb4b6aa9f26b3d536d284288773b788ac6) Thanks [@jsparkdev](https://github.com/jsparkdev)! - Updates Korean language support with improvements and missing translations

## 0.34.2

### Patch Changes

- [#3153](https://github.com/withastro/starlight/pull/3153) [`ea31f46`](https://github.com/withastro/starlight/commit/ea31f46be4d43339417dac7fc135d2be97080c58) Thanks [@SuperKXT](https://github.com/SuperKXT)! - Fixes hover styles for highlighted directory in FileTree component.

- [#2905](https://github.com/withastro/starlight/pull/2905) [`b5232bc`](https://github.com/withastro/starlight/commit/b5232bcd201c2e3904bde2d7717fe6cfa06d6c82) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes a potential issue for projects with dynamic routes added by an user, an Astro integration, or a Starlight plugin where some styles could end up being missing.

- [#3165](https://github.com/withastro/starlight/pull/3165) [`80a7871`](https://github.com/withastro/starlight/commit/80a7871ccad17aef8567a416a419669de6d5d3fd) Thanks [@KianNH](https://github.com/KianNH)! - Increases `maxBuffer` for an internal `spawnSync()` call to support larger Git commit histories when using Starlight's [`lastUpdated`](https://starlight.astro.build/reference/configuration/#lastupdated) feature.

- [#3158](https://github.com/withastro/starlight/pull/3158) [`d1f3c8b`](https://github.com/withastro/starlight/commit/d1f3c8b6583b93968af3c568f7af44b1b10326ec) Thanks [@heisenberg0924](https://github.com/heisenberg0924)! - Adds Hungarian language support

## 0.34.1

### Patch Changes

- [#3140](https://github.com/withastro/starlight/pull/3140) [`f6eb1d5`](https://github.com/withastro/starlight/commit/f6eb1d5a776b007bec0f4b5fd7b160851daac9fc) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes a text selection issue for heading with a clickable anchor link when using double or triple click to select text.

- [#3148](https://github.com/withastro/starlight/pull/3148) [`dc8b6d5`](https://github.com/withastro/starlight/commit/dc8b6d5561eb90be9d31396ed1dc8f8258c9cbf7) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes a regression of the Starlight icon color when using the [`credits`](https://starlight.astro.build/reference/configuration/#credits) configuration option.

## 0.34.0

### Minor Changes

- [#2322](https://github.com/withastro/starlight/pull/2322) [`f14eb0c`](https://github.com/withastro/starlight/commit/f14eb0cd7baa0391d6124379f6c5df4b9ab7cc44) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Groups all of Starlight's CSS declarations into a single `starlight` [cascade layer](https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Styling_basics/Cascade_layers).

  This change allows for easier customization of Starlight's CSS as any custom unlayered CSS will override the default styles. If you are using cascade layers in your custom CSS, you can use the [`@layer`](https://developer.mozilla.org/en-US/docs/Web/CSS/@layer) CSS at-rule to define the order of precedence for different layers including the ones used by Starlight.

  We recommend checking your site’s appearance when upgrading to make sure there are no style regressions caused by this change.

- [#3122](https://github.com/withastro/starlight/pull/3122) [`3a087d8`](https://github.com/withastro/starlight/commit/3a087d8fbcd946336f8a0423203967e53e5678fe) Thanks [@delucis](https://github.com/delucis)! - Removes default `attrs` and `content` values from head entries parsed using Starlight’s schema.

  Previously when adding `head` metadata via frontmatter or user config, Starlight would automatically add values for `attrs` and `content` if not provided. Now, these properties are left `undefined`.

  This makes it simpler to add tags in route middleware for example as you no longer need to provide empty values for `attrs` and `content`:

  ```diff
  head.push({
    tag: 'style',
    content: 'div { color: red }'
  - attrs: {},
  });
  head.push({
    tag: 'link',
  - content: ''
    attrs: { rel: 'me', href: 'https://example.com' },
  });
  ```

  This is mostly an internal API but if you are overriding Starlight’s `Head` component or processing head entries in some way, you may wish to double check your handling of `Astro.locals.starlightRoute.head` is compatible with `attrs` and `content` potentially being `undefined`.

- [#3033](https://github.com/withastro/starlight/pull/3033) [`8c19678`](https://github.com/withastro/starlight/commit/8c19678e57c0270d3d80d4678f23a6fc287ebf12) Thanks [@delucis](https://github.com/delucis)! - Adds support for generating clickable anchor links for headings.

  By default, Starlight now renders an anchor link beside headings in Markdown and MDX content. A new `<AnchorHeading>` component is available to achieve the same thing in custom pages built using `<StarlightPage>`.

  If you want to disable this new Markdown processing set the `markdown.headingLinks` option in your Starlight config to `false`:

  ```js
  starlight({
    title: 'My docs',
    markdown: {
      headingLinks: false,
    },
  }),
  ```

  ⚠️ **BREAKING CHANGE:** The minimum supported version of Astro is now v5.5.0.

  Please update Starlight and Astro together:

  ```sh
  npx @astrojs/upgrade
  ```

- [#2322](https://github.com/withastro/starlight/pull/2322) [`f14eb0c`](https://github.com/withastro/starlight/commit/f14eb0cd7baa0391d6124379f6c5df4b9ab7cc44) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Removes Shiki `css-variables` theme fallback.

  ⚠️ **BREAKING CHANGE:**

  Previously, Starlight used to automatically provide a fallback theme for Shiki, the default syntax highlighter built into Astro if the configured Shiki theme was not `github-dark`.

  This fallback was only relevant when the default Starlight code block renderer, Expressive Code, was disabled and Shiki was used. Starlight no longer provides this fallback.

  If you were relying on this behavior, you now manually need to update your Astro configuration to use the Shiki `css-variables` theme to match the previous behavior.

  ```diff
  import { defineConfig } from 'astro/config';

  export default defineConfig({
  + markdown: {
  +   shikiConfig: {
  +     theme: 'css-variables',
  +   },
  + },
  });
  ```

  Additionally, you can use [custom CSS](https://starlight.astro.build/guides/css-and-tailwind/#custom-css-styles) to control the appearance of the code blocks. Here are the previously used CSS variables for the fallback theme:

  ```css
  :root {
    --astro-code-foreground: var(--sl-color-white);
    --astro-code-background: var(--sl-color-gray-6);
    --astro-code-token-constant: var(--sl-color-blue-high);
    --astro-code-token-string: var(--sl-color-green-high);
    --astro-code-token-comment: var(--sl-color-gray-2);
    --astro-code-token-keyword: var(--sl-color-purple-high);
    --astro-code-token-parameter: var(--sl-color-red-high);
    --astro-code-token-function: var(--sl-color-red-high);
    --astro-code-token-string-expression: var(--sl-color-green-high);
    --astro-code-token-punctuation: var(--sl-color-gray-2);
    --astro-code-token-link: var(--sl-color-blue-high);
  }
  ```

### Patch Changes

- [#3118](https://github.com/withastro/starlight/pull/3118) [`77a1104`](https://github.com/withastro/starlight/commit/77a110461dffacd1d3ee3b8934fd48b20111f3c4) Thanks [@delucis](https://github.com/delucis)! - Fixes passing imported SVGs to the `frontmatter` prop of the `<StarlightPage>` component in Astro ≥5.7.0

## 0.33.2

### Patch Changes

- [#3090](https://github.com/withastro/starlight/pull/3090) [`fc3ffa8`](https://github.com/withastro/starlight/commit/fc3ffa8e27a3113a8eb70a3d8e7bf69c2bb214e5) Thanks [@delucis](https://github.com/delucis)! - Updates internal `@astrojs/mdx`, `@astrojs/sitemap`, and `astro-expressive-code` dependencies

- [#3109](https://github.com/withastro/starlight/pull/3109) [`b5cc1b4`](https://github.com/withastro/starlight/commit/b5cc1b4d4ee7dc737616c6ada893369b13ddb9c6) Thanks [@dhruvkb](https://github.com/dhruvkb)! - Updates Expressive Code to v0.41.1

## 0.33.1

### Patch Changes

- [#3088](https://github.com/withastro/starlight/pull/3088) [`1885049`](https://github.com/withastro/starlight/commit/18850491905fc1bf9e467b1d65c7f1709daf3c30) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes a regression in Starlight version `0.33.0` that caused the description and links to language alternates for multilingual websites to be missing from the` <head>` of the page.

- [#3065](https://github.com/withastro/starlight/pull/3065) [`463adf5`](https://github.com/withastro/starlight/commit/463adf53b263a963736cb441bc1dd515f3c81894) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Updates the `social` configuration option TSDoc example to match the shape of the expected value.

## 0.33.0

### Minor Changes

- [#3026](https://github.com/withastro/starlight/pull/3026) [`82deb84`](https://github.com/withastro/starlight/commit/82deb847418aedb9c01e05bb9de4b9bd10a1a885) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes a potential list styling issue if the last element of a list item is a `<script>` tag.

  ⚠️ **BREAKING CHANGE:**

  This release drops official support for Chromium-based browsers prior to version 105 (released 30 August 2022) and Firefox-based browsers prior to version 121 (released 19 December 2023). You can find a list of currently supported browsers and their versions using this [browserslist query](https://browsersl.ist/#q=%3E+0.5%25%2C+not+dead%2C+Chrome+%3E%3D+105%2C+Edge+%3E%3D+105%2C+Firefox+%3E%3D+121%2C+Safari+%3E%3D+15.4%2C+iOS+%3E%3D+15.4%2C+not+op_mini+all).

  With this release, Starlight-generated sites will still work fine on those older browsers except for this small detail in list item styling, but future releases may introduce further breaking changes for impacted browsers, including in patch releases.

- [#3025](https://github.com/withastro/starlight/pull/3025) [`f87e9ac`](https://github.com/withastro/starlight/commit/f87e9acbf5090a31858c1cde568cc798140f1366) Thanks [@delucis](https://github.com/delucis)! - Makes `social` configuration more flexible.

  ⚠️ **BREAKING CHANGE:** The `social` configuration option has changed syntax. You will need to update this in `astro.config.mjs` when upgrading.

  Previously, a limited set of platforms were supported using a shorthand syntax with labels built in to Starlight. While convenient, this approach was less flexible and required dedicated code for each social platform added.

  Now, you must specify the icon and label for each social link explicitly and you can use any of [Starlight’s built-in icons](https://starlight.astro.build/reference/icons/) for social links.

  The following example shows updating the old `social` syntax to the new:

  ```diff
  - social: {
  -   github: 'https://github.com/withastro/starlight',
  -   discord: 'https://astro.build/chat',
  - },
  + social: [
  +   { icon: 'github', label: 'GitHub', href: 'https://github.com/withastro/starlight' },
  +   { icon: 'discord', label: 'Discord', href: 'https://astro.build/chat' },
  + ],
  ```

- [#2927](https://github.com/withastro/starlight/pull/2927) [`c46904c`](https://github.com/withastro/starlight/commit/c46904c4a16cf1c7f4f895e42cb164474b2301b3) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds the [`head`](https://starlight.astro.build/reference/route-data/#head) route data property which contains an array of all tags to include in the `<head>` of the current page.

  Previously, the [`<Head>`](https://starlight.astro.build/reference/overrides/#head-1) component was responsible for generating a list of tags to include in the `<head>` of the current page and rendering them.
  This data is now available as `Astro.locals.starlightRoute.head` instead and can be modified using [route data middleware](https://starlight.astro.build/guides/route-data/#customizing-route-data).
  The `<Head>` component now only renders the tags provided in `Astro.locals.starlightRoute.head`.

- [#2924](https://github.com/withastro/starlight/pull/2924) [`6a56d1b`](https://github.com/withastro/starlight/commit/6a56d1b80d9d67e63e930177cf085a25864e1952) Thanks [@HiDeoo](https://github.com/HiDeoo)! - ⚠️ **BREAKING CHANGE:** Ensures that the `<Badge>` and `<Icon>` components no longer render with a trailing space.

  In Astro, components that include styles render with a trailing space which can prevent some use cases from working as expected, e.g. when using such components inlined with text. This change ensures that the `<Badge>` and `<Icon>` components no longer render with a trailing space.

  If you were previously relying on that implementation detail, you may need to update your code to account for this change. For example, considering the following code:

  ```mdx
  <Badge text="New" />
  Feature
  ```

  The rendered text would previously include a space between the badge and the text due to the trailing space automatically added by the component:

  ```
  New Feature
  ```

  Such code will now render the badge and text without a space:

  ```
  NewFeature
  ```

  To fix this, you can add a space between the badge and the text:

  ```diff
  - <Badge text="New" />Feature
  + <Badge text="New" /> Feature
  ```

- [#2727](https://github.com/withastro/starlight/pull/2727) [`7c8fa30`](https://github.com/withastro/starlight/commit/7c8fa30f0ac2459c83b71a8a7b705b16dcf98d6f) Thanks [@techfg](https://github.com/techfg)! - Updates mobile menu toggle styles to display a close icon while the menu is open

### Patch Changes

- [#2927](https://github.com/withastro/starlight/pull/2927) [`c46904c`](https://github.com/withastro/starlight/commit/c46904c4a16cf1c7f4f895e42cb164474b2301b3) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes an issue where overriding the [canonical URL](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel#canonical) of a page using the [`head` configuration option](https://starlight.astro.build/reference/configuration/#head) or [`head` frontmatter field](https://starlight.astro.build/reference/frontmatter/#head) would strip any other `<link>` tags from the `<head>`.

- [#2927](https://github.com/withastro/starlight/pull/2927) [`c46904c`](https://github.com/withastro/starlight/commit/c46904c4a16cf1c7f4f895e42cb164474b2301b3) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes an issue where generated [canonical URLs](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel#canonical) would include a trailing slash when using the [`trailingSlash` Astro option](https://docs.astro.build/en/reference/configuration-reference/#trailingslash) is set to `'never'`.

- [#3025](https://github.com/withastro/starlight/pull/3025) [`f87e9ac`](https://github.com/withastro/starlight/commit/f87e9acbf5090a31858c1cde568cc798140f1366) Thanks [@delucis](https://github.com/delucis)! - Fixes Starlight’s autogenerated `<meta name="twitter:site">` tags when a Twitter link is set in `social` config. Previously these incorrectly rendered `content="/username"` and now correctly render `content="@username"`.

## 0.32.6

### Patch Changes

- [#3030](https://github.com/withastro/starlight/pull/3030) [`5bdf139`](https://github.com/withastro/starlight/commit/5bdf139191a20f19458b027617877c1063b46724) Thanks [@trueberryless](https://github.com/trueberryless)! - Updates the type of the `isFallback` field in route data from `true` to `boolean`, keeping it optional but allowing `false` as a possible value.

- [#3018](https://github.com/withastro/starlight/pull/3018) [`188b8cf`](https://github.com/withastro/starlight/commit/188b8cfa8ad8761365b8b557c4b9fea671050ed6) Thanks [@trueberryless](https://github.com/trueberryless)! - Adds validation for user config `routeMiddleware` so it does not conflict with [Astro's middleware](https://docs.astro.build/en/guides/middleware/).

## 0.32.5

### Patch Changes

- [#3021](https://github.com/withastro/starlight/pull/3021) [`e3f881e`](https://github.com/withastro/starlight/commit/e3f881ec23019689b821c638b8f0863b8ced6908) Thanks [@jsparkdev](https://github.com/jsparkdev)! - Updates Korean language support

- [#3020](https://github.com/withastro/starlight/pull/3020) [`58e3e84`](https://github.com/withastro/starlight/commit/58e3e84662167e43c4a8b707453898e047aa18fc) Thanks [@ayoayco](https://github.com/ayoayco)! - Add SourceHut social icon

- [#3013](https://github.com/withastro/starlight/pull/3013) [`5b599dd`](https://github.com/withastro/starlight/commit/5b599dd6190d3b57f61ae48c8614395dda23ef13) Thanks [@oluwatobiss](https://github.com/oluwatobiss)! - Adds Substack icon to social links list

## 0.32.4

### Patch Changes

- [#2994](https://github.com/withastro/starlight/pull/2994) [`ca4ec8b`](https://github.com/withastro/starlight/commit/ca4ec8bc30b8e627bbc946736869ba67a2f4a6c6) Thanks [@XREvo](https://github.com/XREvo)! - Fixes default ranking of merged indexes when using multi-site search

- [#2969](https://github.com/withastro/starlight/pull/2969) [`4682c7a`](https://github.com/withastro/starlight/commit/4682c7a4f248f53073a64ada671548709be49cd7) Thanks [@webpro](https://github.com/webpro)! - Add npm social icon

## 0.32.3

### Patch Changes

- [#2955](https://github.com/withastro/starlight/pull/2955) [`77b6a41`](https://github.com/withastro/starlight/commit/77b6a412c9daba8e6b856f3640204a1ca61c93b9) Thanks [@trueberryless](https://github.com/trueberryless)! - Adds 5 new icons: `figma`, `sketch`, `vim`, `vscode`, and `zed`.

- [#2961](https://github.com/withastro/starlight/pull/2961) [`da57fab`](https://github.com/withastro/starlight/commit/da57fab3027048825e048384fe4aa773b5db3ebf) Thanks [@ematipico](https://github.com/ematipico)! - Adds 1 new icon: `jetbrains`.

## 0.32.2

### Patch Changes

- [#2926](https://github.com/withastro/starlight/pull/2926) [`c0170fd`](https://github.com/withastro/starlight/commit/c0170fd240a89ba4d0d4dd09817257903743dbe8) Thanks [@resoltico](https://github.com/resoltico)! - Adds Latvian language support

- [#2918](https://github.com/withastro/starlight/pull/2918) [`790c000`](https://github.com/withastro/starlight/commit/790c000c4761f68b2782f1eef74568f210d4c619) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes a trailing slash inconsistency in generated sidebar links when using the [`trailingSlash: 'ignore'`](https://docs.astro.build/en/reference/configuration-reference/#trailingslash) Astro option (the default) between [internal](https://starlight.astro.build/guides/sidebar/#internal-links) and [auto-generated](https://starlight.astro.build/guides/sidebar/#autogenerated-groups) links. Starlight behavior for this configuration value is to use a trailing slash as many common hosting providers redirect to URLs with a trailing slash by default.

## 0.32.1

### Patch Changes

- [#2904](https://github.com/withastro/starlight/pull/2904) [`ec5ca59`](https://github.com/withastro/starlight/commit/ec5ca5953e62b6ad2de78996d37e08522aa4aa76) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes an issue preventing the use of [rewrites](https://docs.astro.build/en/guides/routing/#rewrites).

## 0.32.0

### Minor Changes

- [#2390](https://github.com/withastro/starlight/pull/2390) [`f493361`](https://github.com/withastro/starlight/commit/f493361d7b64a3279980e0f046c3a52196ab94e0) Thanks [@delucis](https://github.com/delucis)! - Moves route data to `Astro.locals` instead of passing it down via component props

  ⚠️ **Breaking change:**
  Previously, all of Starlight’s templating components, including user or plugin overrides, had access to a data object for the current route via `Astro.props`.
  This data is now available as `Astro.locals.starlightRoute` instead.

  To update, refactor any component overrides you have:

  - Remove imports of `@astrojs/starlight/props`, which is now deprecated.
  - Update code that accesses `Astro.props` to use `Astro.locals.starlightRoute` instead.
  - Remove any spreading of `{...Astro.props}` into child components, which is no longer required.

  In the following example, a custom override for Starlight’s `LastUpdated` component is updated for the new style:

  ```diff
  ---
  import Default from '@astrojs/starlight/components/LastUpdated.astro';
  - import type { Props } from '@astrojs/starlight/props';

  - const { lastUpdated } = Astro.props;
  + const { lastUpdated } = Astro.locals.starlightRoute;

  const updatedThisYear = lastUpdated?.getFullYear() === new Date().getFullYear();
  ---

  {updatedThisYear && (
  -   <Default {...Astro.props}><slot /></Default>
  +   <Default><slot /></Default>
  )}
  ```

  _Community Starlight plugins may also need to be manually updated to work with Starlight 0.32. If you encounter any issues, please reach out to the plugin author to see if it is a known issue or if an updated version is being worked on._

- [#2578](https://github.com/withastro/starlight/pull/2578) [`f895f75`](https://github.com/withastro/starlight/commit/f895f75b17f36c826cc871ba1826e5ae1dff44ca) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Deprecates the Starlight plugin `setup` hook in favor of the new `config:setup` hook which provides the same functionality.

  ⚠️ **BREAKING CHANGE:**

  The Starlight plugin `setup` hook is now deprecated and will be removed in a future release. Please update your plugins to use the new `config:setup` hook instead.

  ```diff
  export default {
    name: 'plugin-with-translations',
    hooks: {
  -   'setup'({ config }) {
  +   'config:setup'({ config }) {
        // Your plugin configuration setup code
      },
    },
  };
  ```

- [#2578](https://github.com/withastro/starlight/pull/2578) [`f895f75`](https://github.com/withastro/starlight/commit/f895f75b17f36c826cc871ba1826e5ae1dff44ca) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Exposes the built-in localization system in the Starlight plugin `config:setup` hook.

  ⚠️ **BREAKING CHANGE:**

  This addition changes how Starlight plugins add or update translation strings used in Starlight’s localization APIs.
  Plugins previously using the [`injectTranslations()`](https://starlight.astro.build/reference/plugins/#injecttranslations) callback function from the plugin [`config:setup`](https://starlight.astro.build/reference/plugins/#configsetup) hook should now use the same function available in the [`i18n:setup`](https://starlight.astro.build/reference/plugins/#i18nsetup) hook.

  ```diff
  export default {
    name: 'plugin-with-translations',
    hooks: {
  -   'config:setup'({ injectTranslations }) {
  +   'i18n:setup'({ injectTranslations }) {
        injectTranslations({
          en: {
            'myPlugin.doThing': 'Do the thing',
          },
          fr: {
            'myPlugin.doThing': 'Faire le truc',
          },
        });
      },
    },
  };
  ```

- [#2858](https://github.com/withastro/starlight/pull/2858) [`2df9d05`](https://github.com/withastro/starlight/commit/2df9d05fe7b61282809aa85a1d77662fdd3b748f) Thanks [@XREvo](https://github.com/XREvo)! - Adds support for Pagefind’s multisite search features

- [#2578](https://github.com/withastro/starlight/pull/2578) [`f895f75`](https://github.com/withastro/starlight/commit/f895f75b17f36c826cc871ba1826e5ae1dff44ca) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds a new [`HookParameters`](https://starlight.astro.build/reference/plugins/#hooks) utility type to get the type of a plugin hook’s arguments.

- [#2578](https://github.com/withastro/starlight/pull/2578) [`f895f75`](https://github.com/withastro/starlight/commit/f895f75b17f36c826cc871ba1826e5ae1dff44ca) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds a new [`useTranslations()`](https://starlight.astro.build/reference/plugins/#usetranslations) callback function to the Starlight plugin `config:setup` hook to generate a utility function to access UI strings for a given language.

- [#2578](https://github.com/withastro/starlight/pull/2578) [`f895f75`](https://github.com/withastro/starlight/commit/f895f75b17f36c826cc871ba1826e5ae1dff44ca) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds a new [`absolutePathToLang()`](https://starlight.astro.build/reference/plugins/#absolutepathtolang) callback function to the Starlight plugin `config:setup` to get the language for a given absolute file path.

### Patch Changes

- [#2848](https://github.com/withastro/starlight/pull/2848) [`9b32ba9`](https://github.com/withastro/starlight/commit/9b32ba967c5741354bc99ba0bcff3f454b8117ad) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes styling of [filter](https://pagefind.app/docs/filtering/) and [metadata](https://pagefind.app/docs/metadata/) elements in Pagefind search UI.

## 0.31.1

### Patch Changes

- [#2805](https://github.com/withastro/starlight/pull/2805) [`ed6f9fd`](https://github.com/withastro/starlight/commit/ed6f9fd77334c02a75240087d0800ef32f159583) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Exposes the [`StarlightIcon`](https://starlight.astro.build/reference/icons/#starlighticon-type) TypeScript type referencing the names of Starlight’s built-in icons.

## 0.31.0

### Minor Changes

- [#2777](https://github.com/withastro/starlight/pull/2777) [`88f4214`](https://github.com/withastro/starlight/commit/88f42145888f3a04f20898fcb700c1e65be48bb2) Thanks [@hippotastic](https://github.com/hippotastic)! - Updates `astro-expressive-code` dependency to the latest version (0.40).

  This includes an update to the latest Shiki version (1.26.1), providing access to all current Shiki themes and syntax highlighting languages, and adding the config options `shiki.engine`, `shiki.bundledLangs`, `shiki.langAlias` and `removeUnusedThemes`. It also adds new style variants to the optional collapsible sections plugin.

  See the [Expressive Code release notes](https://expressive-code.com/releases/#0400) for full details.

- [#2736](https://github.com/withastro/starlight/pull/2736) [`29a885b`](https://github.com/withastro/starlight/commit/29a885be43f29150d6abd905f3ef7e1dccb99c98) Thanks [@delucis](https://github.com/delucis)! - ⚠️ **BREAKING CHANGE:** The minimum supported version of Astro is now 5.1.5

  Please update Astro and Starlight together:

  ```sh
  npx @astrojs/upgrade
  ```

- [#2728](https://github.com/withastro/starlight/pull/2728) [`e187383`](https://github.com/withastro/starlight/commit/e1873834d4a4328084a9ac056a089ee5b8f13103) Thanks [@delucis](https://github.com/delucis)! - Updates minimum Pagefind dependency to v1.3.0, sets new defaults for Pagefind’s ranking options, and adds support for manually configuring the ranking options

  The new ranking option defaults have been evaluated against Starlight’s own docs to improve the quality of search results. See [“Customize Pagefind's result ranking”](https://pagefind.app/docs/ranking/) for more details about how they work.

- [#157](https://github.com/withastro/starlight/pull/157) [`23bf960`](https://github.com/withastro/starlight/commit/23bf960aed36445600b6ccecb2138a5b461e2929) Thanks [@tony-sull](https://github.com/tony-sull)! - Adds a print stylesheet to improve the appearance of Starlight docs pages when printed

- [#2728](https://github.com/withastro/starlight/pull/2728) [`e187383`](https://github.com/withastro/starlight/commit/e1873834d4a4328084a9ac056a089ee5b8f13103) Thanks [@delucis](https://github.com/delucis)! - Fixes Pagefind logging to respect the Astro log level. When using Astro’s `--verbose` or `--silent` CLI flags, these are now respected by Pagefind as well.

### Patch Changes

- [#2792](https://github.com/withastro/starlight/pull/2792) [`412effb`](https://github.com/withastro/starlight/commit/412effb5a63c6026ea4faa0d09bcbd4a3c9fad4d) Thanks [@dhruvkb](https://github.com/dhruvkb)! - Uses semantic `var(--sl-color-hairline)` for the page sidebar border instead of `var(--sl-color-gray-6)`. This is visually the same as previously but makes it easier to override the hairline color consistently across a site.

- [#2736](https://github.com/withastro/starlight/pull/2736) [`29a885b`](https://github.com/withastro/starlight/commit/29a885be43f29150d6abd905f3ef7e1dccb99c98) Thanks [@delucis](https://github.com/delucis)! - Updates internal dependencies `@astrojs/sitemap` and `@astrojs/mdx` to the latest versions

- [#2782](https://github.com/withastro/starlight/pull/2782) [`d9d415b`](https://github.com/withastro/starlight/commit/d9d415b4558c7995319299e9c9e1520c87c3078e) Thanks [@delucis](https://github.com/delucis)! - Fixes a documentation link in the JSDoc comment for the `StarlightExpressiveCodeOptions` type

- [#2708](https://github.com/withastro/starlight/pull/2708) [`442c819`](https://github.com/withastro/starlight/commit/442c8194dbcbe58e155d4c1f8d897a04605666e5) Thanks [@delucis](https://github.com/delucis)! - Fixes colour contrast correction in code blocks

## 0.30.6

### Patch Changes

- [#2722](https://github.com/withastro/starlight/pull/2722) [`0b206d3`](https://github.com/withastro/starlight/commit/0b206d3a23f0876146dc17f5e507984362917696) Thanks [@techfg](https://github.com/techfg)! - Fixes display of long site title on mobile

- [#2762](https://github.com/withastro/starlight/pull/2762) [`7ab1576`](https://github.com/withastro/starlight/commit/7ab157639da62fdc6b444b0280ad4c9d5ee4872f) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Prevents the header title from being translated by automatic translation systems.

## 0.30.5

### Patch Changes

- [#2757](https://github.com/withastro/starlight/pull/2757) [`e7b0e74`](https://github.com/withastro/starlight/commit/e7b0e742dffb7c4a8f4619297e4bd6e5a8015edb) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes a UI string translation issue for languages with a region subtag.

- [#2760](https://github.com/withastro/starlight/pull/2760) [`aec9edd`](https://github.com/withastro/starlight/commit/aec9edd14827a45fbc92d82db83dd713571e0c2d) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds 5 new icons: `left-caret`, `up-arrow`, `down-arrow`, `download`, and `cloud-download`.

## 0.30.4

### Patch Changes

- [#2747](https://github.com/withastro/starlight/pull/2747) [`474c27e`](https://github.com/withastro/starlight/commit/474c27e28d79794ac78d36e3384f0c0da6f2dfed) Thanks [@bbag](https://github.com/bbag)! - Ensures `<Tab>` component toggling is stable when smooth scrolling is enabled via custom CSS

- [#2740](https://github.com/withastro/starlight/pull/2740) [`0e169c9`](https://github.com/withastro/starlight/commit/0e169c9fd9fbfc16d86225db6b00448edf39ffad) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes an issue preventing Pagefind to be disabled using the `pagefind` frontmatter field.

- [#2732](https://github.com/withastro/starlight/pull/2732) [`a10b466`](https://github.com/withastro/starlight/commit/a10b46680810882b029dd1d578cc86e22bc97af5) Thanks [@Sidnioulz](https://github.com/Sidnioulz)! - Adds Storybook, Confluence and Jira social icons

## 0.30.3

### Patch Changes

- [#2717](https://github.com/withastro/starlight/pull/2717) [`c5fcbb3`](https://github.com/withastro/starlight/commit/c5fcbb33a7a0511ac372f5d006a69f4195d1e266) Thanks [@delucis](https://github.com/delucis)! - Fixes a list item spacing issue where line break elements (`<br>`) could receive a margin, breaking layout in Firefox

- [#2724](https://github.com/withastro/starlight/pull/2724) [`02d7ac6`](https://github.com/withastro/starlight/commit/02d7ac66a0bdca3f26001f556de070027d4e0faf) Thanks [@dionysuzx](https://github.com/dionysuzx)! - Adds social link support for Farcaster

- [#2635](https://github.com/withastro/starlight/pull/2635) [`ec4b851`](https://github.com/withastro/starlight/commit/ec4b85154ea301d9144ff49f3abd009e3a929387) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes an issue where the language picker in multilingual sites could display the wrong language when navigating between pages with the browser back/forward buttons.

- [#2726](https://github.com/withastro/starlight/pull/2726) [`e54ebd5`](https://github.com/withastro/starlight/commit/e54ebd5c879deb3fdff2180426b377181773b85f) Thanks [@techfg](https://github.com/techfg)! - Adds icon for phone

## 0.30.2

### Patch Changes

- [#2702](https://github.com/withastro/starlight/pull/2702) [`02d16f3`](https://github.com/withastro/starlight/commit/02d16f3638db609501897c5e3647cc20eb5ec142) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes an issue with autogenerated sidebars when using Starlight with Astro's new Content Layer API with directories containing spaces or special characters.

- [#2704](https://github.com/withastro/starlight/pull/2704) [`fd16470`](https://github.com/withastro/starlight/commit/fd164704b25ec5c000a2765eb0930b87e9a4e61e) Thanks [@delucis](https://github.com/delucis)! - Fixes display of focus indicator around site title

## 0.30.1

### Patch Changes

- [#2688](https://github.com/withastro/starlight/pull/2688) [`5c6996c`](https://github.com/withastro/starlight/commit/5c6996cd248e9da735a14e7fcaf638b51f2796bc) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes an issue with autogenerated sidebars when using Starlight with Astro's new Content Layer API where group names would be sluggified.

## 0.30.0

### Minor Changes

- [#2612](https://github.com/withastro/starlight/pull/2612) [`8d5a4e8`](https://github.com/withastro/starlight/commit/8d5a4e8000d9e3a4bb9ca8178767cf3d8bc48773) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds support for Astro v5, drops support for Astro v4.

  #### Upgrade Astro and dependencies

  ⚠️ **BREAKING CHANGE:** Astro v4 is no longer supported. Make sure you [update Astro](https://docs.astro.build/en/guides/upgrade-to/v5/) and any other official integrations at the same time as updating Starlight:

  ```sh
  npx @astrojs/upgrade
  ```

  _Community Starlight plugins and Astro integrations may also need to be manually updated to work with Astro v5. If you encounter any issues, please reach out to the plugin or integration author to see if it is a known issue or if an updated version is being worked on._

  #### Update your collections

  ⚠️ **BREAKING CHANGE:** Starlight's internal [content collections](https://docs.astro.build/en/guides/content-collections/), which organize, validate, and render your content, have been updated to use Astro's new Content Layer API and require configuration changes in your project.

  1. **Move the content config file.** This file no longer lives within the `src/content/config.ts` folder and should now exist at `src/content.config.ts`.
  1. **Edit the collection definition(s).** To update the `docs` collection, a `loader` is now required:

     ```diff
      // src/content.config.ts
      import { defineCollection } from "astro:content";
     +import { docsLoader } from "@astrojs/starlight/loaders";
      import { docsSchema } from "@astrojs/starlight/schema";

      export const collections = {
     -  docs: defineCollection({ schema: docsSchema() }),
     +  docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
      };
     ```

     If you are using the [`i18n` collection](https://starlight.astro.build/guides/i18n/#translate-starlights-ui) to provide translations for additional languages you support or override our default labels, you will need to update the collection definition in a similar way and remove the collection `type` which is no longer available:

     ```diff
      // src/content.config.ts
      import { defineCollection } from "astro:content";
     +import { docsLoader, i18nLoader } from "@astrojs/starlight/loaders";
      import { docsSchema, i18nSchema } from "@astrojs/starlight/schema";

      export const collections = {
     -  docs: defineCollection({ schema: docsSchema() }),
     +  docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
     -  i18n: defineCollection({ type: 'data', schema: i18nSchema() }),
     +  i18n: defineCollection({ loader: i18nLoader(), schema: i18nSchema() }),
      };
     ```

  1. **Update other collections.** To update any other collections you may have, follow the [“Updating existing collections”](https://docs.astro.build/en/guides/upgrade-to/v5/#updating-existing-collections) section in the Astro 5 upgrade guide.

  If you are unable to make any changes to your collections at this time, including Starlight's default `docs` and `i18n` collections, you can enable the [`legacy.collections` flag](https://docs.astro.build/en/reference/legacy-flags/) to upgrade to v5 without updating your collections. This legacy flag exists to provide temporary backwards compatibility, and will allow you to keep your collections in their current state until the legacy flag is no longer supported.

### Patch Changes

- [#2669](https://github.com/withastro/starlight/pull/2669) [`310df7d`](https://github.com/withastro/starlight/commit/310df7d6b01f5c4a56540bdba9243fb60dace323) Thanks [@aaronperezaguilera](https://github.com/aaronperezaguilera)! - Adds Catalan UI translations

- [#2664](https://github.com/withastro/starlight/pull/2664) [`62ff007`](https://github.com/withastro/starlight/commit/62ff0074d9a3f82e46f5c62db85c04d87ff5e931) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Publishes provenance containing verifiable data to link a package back to its source repository and the specific build instructions used to publish it.

- [#2670](https://github.com/withastro/starlight/pull/2670) [`0223b42`](https://github.com/withastro/starlight/commit/0223b425249f8d1fa468e367c632467276c9c208) Thanks [@aaronperezaguilera](https://github.com/aaronperezaguilera)! - Adds Spanish UI translations for the Pagefind search modal

## 0.29.3

### Patch Changes

- [#2642](https://github.com/withastro/starlight/pull/2642) [`12750ae`](https://github.com/withastro/starlight/commit/12750ae1bc303f2c53efd25adf01428e54aced90) Thanks [@dragomano](https://github.com/dragomano)! - Updates Russian UI translations

- [#2656](https://github.com/withastro/starlight/pull/2656) [`4d543be`](https://github.com/withastro/starlight/commit/4d543bec280f3b5e00e21727d78f25756a1ced75) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Improves error message when an invalid configuration or no configuration is provided to the Starlight integration.

- [#2645](https://github.com/withastro/starlight/pull/2645) [`cf12beb`](https://github.com/withastro/starlight/commit/cf12beb91b4cb2f212dbcc0cc1ed56e79d055ff0) Thanks [@techfg](https://github.com/techfg)! - Fixes support for favicon URLs that contain a search query and/or hash

- [#2650](https://github.com/withastro/starlight/pull/2650) [`38db4ec`](https://github.com/withastro/starlight/commit/38db4ecfdb572b1f6362aca544f72f5128f5fe08) Thanks [@raviqqe](https://github.com/raviqqe)! - Moves `@types/js-yaml` package to non-dev dependencies

- [#2633](https://github.com/withastro/starlight/pull/2633) [`5adb720`](https://github.com/withastro/starlight/commit/5adb720afd354d99b3682d045b9dc8729a1ff274) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes a VoiceOver issue with Safari where the content of a `<script>` element could be read before the sidebar content.

- [#2663](https://github.com/withastro/starlight/pull/2663) [`34755f9`](https://github.com/withastro/starlight/commit/34755f9c5f2fa451e8a56aecf3ff5a6ff499767b) Thanks [@astrobot-houston](https://github.com/astrobot-houston)! - Adds a new `seti:vite` icon for Vite configuration files in the `<FileTree>` component

## 0.29.2

### Patch Changes

- [#2616](https://github.com/withastro/starlight/pull/2616) [`128cc51`](https://github.com/withastro/starlight/commit/128cc51b416a1a934eabb1989c04b76517e77a04) Thanks [@delucis](https://github.com/delucis)! - Fixes an edge case to correctly avoid a trailing slash when navigating from a root locale homepage to another language via Starlight’s language switcher when `trailingSlash: 'never'` is set

## 0.29.1

### Patch Changes

- [#2611](https://github.com/withastro/starlight/pull/2611) [`6059d96`](https://github.com/withastro/starlight/commit/6059d961a6b31fd7848b0c59411fc6370e62abab) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes a UI string type issue in projects with multiple data content collections.

- [#2606](https://github.com/withastro/starlight/pull/2606) [`10b15a7`](https://github.com/withastro/starlight/commit/10b15a7fcda4805dda622f893b6671b96a349161) Thanks [@delucis](https://github.com/delucis)! - Makes `<CardGrid>` more resilient to complex child content on smaller viewports

- [#2605](https://github.com/withastro/starlight/pull/2605) [`ec7ab4f`](https://github.com/withastro/starlight/commit/ec7ab4f1df83052aa00c5f560adf7e7b8d61c9db) Thanks [@brianzelip](https://github.com/brianzelip)! - Exposes `SidebarPersister` component in package exports for use in custom overrides

- [#2614](https://github.com/withastro/starlight/pull/2614) [`9a31980`](https://github.com/withastro/starlight/commit/9a319807c698f65b461f456c54c413081ab551f0) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes an issue with custom pages using the `<StarlightPage />` component and a custom sidebar missing highlighting for the active page and navigation links.

- [#2600](https://github.com/withastro/starlight/pull/2600) [`49aef17`](https://github.com/withastro/starlight/commit/49aef173811d05ae132729c92c3920a142ceeb7d) Thanks [@jdevega](https://github.com/jdevega)! - Adds Backstage social icon

- [#2613](https://github.com/withastro/starlight/pull/2613) [`a73780f`](https://github.com/withastro/starlight/commit/a73780fb280feb5b96ffa94539633b2930bd8e76) Thanks [@delucis](https://github.com/delucis)! - Fixes support for `sidebar` frontmatter options in sidebar entries using `slug` or the string shorthand for internal links

## 0.29.0

### Minor Changes

- [#2551](https://github.com/withastro/starlight/pull/2551) [`154c8e3`](https://github.com/withastro/starlight/commit/154c8e337819c7d7ebf4ff4dd55db0d10607620b) Thanks [@hippotastic](https://github.com/hippotastic)! - Updates the `astro-expressive-code` dependency to the latest version (0.38).

  The new version allows using `ec.config.mjs` to selectively override individual Expressive Code styles and settings provided by Starlight themes and plugins, speeds up Shiki language loading, and adds the config option `expressiveCode.shiki.injectLangsIntoNestedCodeBlocks`. See the [Expressive Code release notes](https://expressive-code.com/releases/#0380) for full details.

- [#2252](https://github.com/withastro/starlight/pull/2252) [`6116db0`](https://github.com/withastro/starlight/commit/6116db03a4157c0f0caa210690ef0dcdd001a287) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Improves build performance for sites with large sidebars

  This release adds a caching layer to Starlight’s sidebar generation logic, reducing the number of times sidebars need to be regenerated while building a site. Some benchmarks for projects with a complex sidebar saw builds complete more than 35% faster with this change.

- [#2503](https://github.com/withastro/starlight/pull/2503) [`a4c8edd`](https://github.com/withastro/starlight/commit/a4c8eddc53993068c0f60159fecc123013827ef0) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Improves the accessibility of asides and tabs by removing some unnecessary HTML landmarks.

### Patch Changes

- [#2579](https://github.com/withastro/starlight/pull/2579) [`241966b`](https://github.com/withastro/starlight/commit/241966bd0523a2e82891d622b2a97b2f3646bc41) Thanks [@RafidMuhymin](https://github.com/RafidMuhymin)! - Adds social link icon for Nostr

## 0.28.6

### Patch Changes

- [#2565](https://github.com/withastro/starlight/pull/2565) [`236467b`](https://github.com/withastro/starlight/commit/236467bb745cea7a284ae3d398874d3edbcd846e) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes an issue with custom UI strings defined in YAML files not being loaded in some contexts.

## 0.28.5

### Patch Changes

- [#2546](https://github.com/withastro/starlight/pull/2546) [`bf42300`](https://github.com/withastro/starlight/commit/bf42300e76241a2df888dc458c59a7478a8b2d61) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes an issue where i18n content collection related errors, e.g. malformed JSON or YAML, would not be reported.

- [#2548](https://github.com/withastro/starlight/pull/2548) [`07673c8`](https://github.com/withastro/starlight/commit/07673c80114021a269065e451e660337237f76e1) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes a URL localization edge case. In projects without a root locale configured, slugs without a locale prefix did not fall back to the default locale as expected.

- [#2547](https://github.com/withastro/starlight/pull/2547) [`91e1dd7`](https://github.com/withastro/starlight/commit/91e1dd731a06657890a68b2d474199455df2756f) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes a Firefox Markdown content rendering issue for text sentences separated by a line break.

- [#2524](https://github.com/withastro/starlight/pull/2524) [`1b46783`](https://github.com/withastro/starlight/commit/1b4678325fb10714fc3508bd87a7563b10a0f803) Thanks [@jsparkdev](https://github.com/jsparkdev)! - Fixes a broken link to Astro’s Docs in an error message

## 0.28.4

### Patch Changes

- [#2444](https://github.com/withastro/starlight/pull/2444) [`d585b3e`](https://github.com/withastro/starlight/commit/d585b3e0485dd55b2ffab985a6c06d267d22fe51) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes a UI string translation issue for languages with a region subtag.

- [#2518](https://github.com/withastro/starlight/pull/2518) [`0f69db8`](https://github.com/withastro/starlight/commit/0f69db8b806833a7160570a469ddcdc8c0dec5e0) Thanks [@morinokami](https://github.com/morinokami)! - Updates Japanese UI translations

- [#2507](https://github.com/withastro/starlight/pull/2507) [`bd6ced5`](https://github.com/withastro/starlight/commit/bd6ced5bc46310b217c7bfe83a0f68ba4a03da45) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes a table of contents highlighting issue after resizing the window.

- [#2444](https://github.com/withastro/starlight/pull/2444) [`d585b3e`](https://github.com/withastro/starlight/commit/d585b3e0485dd55b2ffab985a6c06d267d22fe51) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Refactors various components to use the new built-in localization system to access translated UI strings.

## 0.28.3

### Patch Changes

- [#2408](https://github.com/withastro/starlight/pull/2408) [`0b4823d`](https://github.com/withastro/starlight/commit/0b4823d534abe517fac5efd97f6febb5965714fe) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes a link formatting issue when using the Astro `build.format` option set to `file` with a `base`.

- [#2380](https://github.com/withastro/starlight/pull/2380) [`7b451cf`](https://github.com/withastro/starlight/commit/7b451cff6979bef1c817f3a84392221ac884ba3d) Thanks [@delucis](https://github.com/delucis)! - Loosen Starlight’s i18n schema to pass through unknown keys

- [#2388](https://github.com/withastro/starlight/pull/2388) [`6bba3d8`](https://github.com/withastro/starlight/commit/6bba3d8e02b95ecee7f9c945b6ee33b4c4ba755d) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes a potential type-checking issue in Starlight projects.

- [#2443](https://github.com/withastro/starlight/pull/2443) [`a0f40b3`](https://github.com/withastro/starlight/commit/a0f40b3c3c7ab0cb9f0f5f11b94e3679547f6ab4) Thanks [@kevinzunigacuellar](https://github.com/kevinzunigacuellar)! - Fixes CSS issue where bottom padding is not applied in the search dialog.

## 0.28.2

### Patch Changes

- [#2377](https://github.com/withastro/starlight/pull/2377) [`a257b83`](https://github.com/withastro/starlight/commit/a257b83f1e5704ff41bcbe85482ac81a1a61ce1f) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes an issue with synced `<Tabs>` components containing nested `<Tabs>` causing tab panels to not render correctly.

## 0.28.1

### Patch Changes

- [#2334](https://github.com/withastro/starlight/pull/2334) [`79b9ade`](https://github.com/withastro/starlight/commit/79b9ade194cf704dad79267715a6970e0d7a7277) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes an issue with Expressive Code UI labels not displaying correctly.

## 0.28.0

### Minor Changes

- [#1923](https://github.com/withastro/starlight/pull/1923) [`5269aad`](https://github.com/withastro/starlight/commit/5269aad928773ae08b35ba8e19c0f2832d0d2c89) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Overhauls the built-in localization system which is now powered by the [`i18next`](https://www.i18next.com/) library and available to use anywhere in your documentation website.

  See the [“Using UI translations”](https://starlight.astro.build/guides/i18n/#using-ui-translations) guide to learn more about how to access built-in UI labels or your own custom strings in your project. Plugin authors can also use the new [`injectTranslations()`](https://starlight.astro.build/reference/plugins/#injecttranslations) helper to add or update translation strings.

  ⚠️ **BREAKING CHANGE:** The `Astro.props.labels` props has been removed from the props passed down to custom component overrides.

  If you are relying on `Astro.props.labels` (for example to read a built-in UI label), you will need to update your code to use the new [`Astro.locals.t()`](https://starlight.astro.build/guides/i18n/#using-ui-translations) helper instead.

  ```astro
  ---
  import type { Props } from '@astrojs/starlight/props';
  // The `search.label` UI label for this page’s language:
  const searchLabel = Astro.locals.t('search.label');
  ---
  ```

- [#2285](https://github.com/withastro/starlight/pull/2285) [`7286220`](https://github.com/withastro/starlight/commit/728622037602999ed67dedc2757ca5654236feb8) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds support for translating sidebar badges.

- [#1923](https://github.com/withastro/starlight/pull/1923) [`5269aad`](https://github.com/withastro/starlight/commit/5269aad928773ae08b35ba8e19c0f2832d0d2c89) Thanks [@HiDeoo](https://github.com/HiDeoo)! - ⚠️ **BREAKING CHANGE:** The minimum supported version of Astro is now 4.14.0

  Please update Astro and Starlight together:

  ```sh
  npx @astrojs/upgrade
  ```

### Patch Changes

- [#2327](https://github.com/withastro/starlight/pull/2327) [`d7a295e`](https://github.com/withastro/starlight/commit/d7a295e5f63171c7eee9fc11333157d8c7e6c803) Thanks [@tritao](https://github.com/tritao)! - Fixes restoration of remark directives for nodes with custom data attached.

## 0.27.1

### Patch Changes

- [#2303](https://github.com/withastro/starlight/pull/2303) [`f92791a`](https://github.com/withastro/starlight/commit/f92791aa1d1ec3d5498e445a078f7143fef60553) Thanks [@delucis](https://github.com/delucis)! - Fixes resolution for the internal module Git virtual module in projects with special characters in the file path

## 0.27.0

### Minor Changes

- [#1255](https://github.com/withastro/starlight/pull/1255) [`6f3202b`](https://github.com/withastro/starlight/commit/6f3202b3eb747de8a1cfcba001ab618d5fdee44a) Thanks [@Fryuni](https://github.com/Fryuni)! - Adds support for server-rendered Starlight pages.

  When building a project with `hybrid` or `server` output mode, a new `prerender` option on Starlight config can be set to `false` to make all Starlight pages be rendered on-demand:

  ```ts
  export default defineConfig({
    output: 'server',
    integrations: [
      starlight({
        prerender: false,
      }),
    ],
  });
  ```

### Patch Changes

- [#2242](https://github.com/withastro/starlight/pull/2242) [`756e85e`](https://github.com/withastro/starlight/commit/756e85e8e814657c42c4a6f9c299b5bef32aee22) Thanks [@delucis](https://github.com/delucis)! - Refactors the logic for persisting and restoring sidebar state across navigations for better performance on slow or busy devices

- [#1255](https://github.com/withastro/starlight/pull/1255) [`6f3202b`](https://github.com/withastro/starlight/commit/6f3202b3eb747de8a1cfcba001ab618d5fdee44a) Thanks [@Fryuni](https://github.com/Fryuni)! - Improves performance of computing the last updated times from Git history.

  Instead of executing `git` for each docs page, it is now executed twice regardless of the number of pages.

- [#1255](https://github.com/withastro/starlight/pull/1255) [`6f3202b`](https://github.com/withastro/starlight/commit/6f3202b3eb747de8a1cfcba001ab618d5fdee44a) Thanks [@Fryuni](https://github.com/Fryuni)! - Fixes last updated times on projects with custom `srcDir`

## 0.26.4

### Patch Changes

- [#2288](https://github.com/withastro/starlight/pull/2288) [`b15f725`](https://github.com/withastro/starlight/commit/b15f725ead981387f80f089d0523d9c2748b184e) Thanks [@matthewp](https://github.com/matthewp)! - Safely handle Zod errors

  Prevents bugs where errors without the `.received` props would through and cause builds to fail unnecessarily.

## 0.26.3

### Patch Changes

- [#2281](https://github.com/withastro/starlight/pull/2281) [`5062d30`](https://github.com/withastro/starlight/commit/5062d30c08f6ede9e6c39174537bb61280e7c23d) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes a potential text rendering issue that could include extra whitespaces for text containing colons.

- [#2279](https://github.com/withastro/starlight/pull/2279) [`62d59e2`](https://github.com/withastro/starlight/commit/62d59e29d2621d834c28c764a02c58b1e1b49243) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes an issue with frontmatter schemas containing collection references used with the `<StarlightPage />` component and an Astro version greater than `4.14.0`.

## 0.26.2

### Patch Changes

- [#2273](https://github.com/withastro/starlight/pull/2273) [`746e0cd`](https://github.com/withastro/starlight/commit/746e0cd301f4ac4a182e8c45b36865c61d208b77) Thanks [@delucis](https://github.com/delucis)! - Fixes type error when using Starlight with Astro v4.15

- [#2265](https://github.com/withastro/starlight/pull/2265) [`25b661e`](https://github.com/withastro/starlight/commit/25b661e238cdc6c08ef79504fa5507d879c0f62d) Thanks [@SeraphicRav](https://github.com/SeraphicRav)! - Adds TikTok social icon

- [#2272](https://github.com/withastro/starlight/pull/2272) [`d1969dd`](https://github.com/withastro/starlight/commit/d1969dde2ea8ece6ce9d439eae12d9c63c2201d7) Thanks [@o-az](https://github.com/o-az)! - Adds new icon: `jsr`

- [#2250](https://github.com/withastro/starlight/pull/2250) [`c0a6166`](https://github.com/withastro/starlight/commit/c0a6166bb280e2d70060b68cdf6ee166812c82d2) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Removes internal E2E tests from the package published to the npm registry.

- [#2253](https://github.com/withastro/starlight/pull/2253) [`72bc76a`](https://github.com/withastro/starlight/commit/72bc76a28f5c1b050d8125d80c6146526b699600) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes an issue preventing to use the `class` attribute in hero action link buttons.

## 0.26.1

### Patch Changes

- [#2219](https://github.com/withastro/starlight/pull/2219) [`74d4716`](https://github.com/withastro/starlight/commit/74d4716f6a70fbef486e1057b81d2280c40251df) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes a sidebar persistence issue when navigating between pages with different sidebar content.

## 0.26.0

### Minor Changes

- [#1784](https://github.com/withastro/starlight/pull/1784) [`68f56a7`](https://github.com/withastro/starlight/commit/68f56a7ffd314b760443a057db9ed1a982dbe191) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds `<LinkButton>` component for visually distinct and emphasized call to action links

- [#2150](https://github.com/withastro/starlight/pull/2150) [`9368494`](https://github.com/withastro/starlight/commit/9368494210dbcd80ada5b410340814fe36c4eb6c) Thanks [@delucis](https://github.com/delucis)! - Adds state persistence across page navigations to the main site sidebar

- [#2087](https://github.com/withastro/starlight/pull/2087) [`caa84ea`](https://github.com/withastro/starlight/commit/caa84eaa7dc653d27d539fd3a93df346a9f0f149) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds persistence to synced `<Tabs>` so that a user's choices are reflected across page navigations.

- [#2051](https://github.com/withastro/starlight/pull/2051) [`ec3b579`](https://github.com/withastro/starlight/commit/ec3b5794cac55a5755620fa5e205f0d54c9e343b) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds a guideline to the last step of the `<Steps>` component.

  If you want to preserve the previous behaviour and hide the guideline on final steps, you can add the following custom CSS to your site:

  ```css
  /* Hide the guideline for the final step in <Steps> lists. */
  .sl-steps > li:last-of-type::after {
    background: transparent;
  }
  ```

- [#1784](https://github.com/withastro/starlight/pull/1784) [`68f56a7`](https://github.com/withastro/starlight/commit/68f56a7ffd314b760443a057db9ed1a982dbe191) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Changes the hero component action button default [variant](https://starlight.astro.build/reference/frontmatter/#heroconfig) from `minimal` to `primary`.

  ⚠️ **BREAKING CHANGE:** If you want to preserve the previous appearance, hero component action buttons previously declared without a `variant` will need to be updated to include the `variant` property with the value `minimal`.

  ```diff
  hero:
    actions:
      - text: View on GitHub
        link: https://github.com/astronaut/my-project
        icon: external
  +     variant: minimal
  ```

- [#2168](https://github.com/withastro/starlight/pull/2168) [`e044fee`](https://github.com/withastro/starlight/commit/e044feeae9a336a87db526107e5772b54ddc567f) Thanks [@HiDeoo](https://github.com/HiDeoo)! - ⚠️ **BREAKING CHANGE:** Updates the `<StarlightPage />` component `sidebar` prop to accept an array of [`SidebarItem`](https://starlight.astro.build/reference/configuration/#sidebaritem)s like the main Starlight `sidebar` configuration in `astro.config.mjs`.

  This change simplifies the definition of sidebar items in the `<StarlightPage />` component, allows for shared sidebar configuration between the global `sidebar` option and `<StarlightPage />` component, and also enables the usage of autogenerated sidebar groups with the `<StarlightPage />` component.
  If you are using the `<StarlightPage />` component with a custom `sidebar` configuration, you will need to update the `sidebar` prop to an array of [`SidebarItem`](https://starlight.astro.build/reference/configuration/#sidebaritem) objects.

  For example, the following custom page with a custom `sidebar` configuration defines a “Resources” group with a “New” badge, a link to the “Showcase” page which is part of the `docs` content collection, and a link to the Starlight website:

  ```astro
  ---
  // src/pages/custom-page/example.astro
  ---

  <StarlightPage
    frontmatter={{ title: 'My custom page' }}
    sidebar={[
      {
        type: 'group',
        label: 'Resources',
        badge: { text: 'New' },
        items: [
          { type: 'link', label: 'Showcase', href: '/showcase/' },
          {
            type: 'link',
            label: 'Starlight',
            href: 'https://starlight.astro.build/',
          },
        ],
      },
    ]}
  >
    <p>This is a custom page with a custom component.</p>
  </StarlightPage>
  ```

  This configuration will now need to be updated to the following:

  ```astro
  ---
  // src/pages/custom-page/example.astro
  ---

  <StarlightPage
    frontmatter={{ title: 'My custom page' }}
    sidebar={[
      {
        label: 'Resources',
        badge: { text: 'New' },
        items: [
          'showcase',
          { label: 'Starlight', link: 'https://starlight.astro.build/' },
        ],
      },
    ]}
  >
    <p>This is a custom page with a custom component.</p>
  </StarlightPage>
  ```

  See the [“Sidebar Navigation”](https://starlight.astro.build/guides/sidebar/) guide to learn more about the available options for customizing the sidebar.

## 0.25.5

### Patch Changes

- [#2171](https://github.com/withastro/starlight/pull/2171) [`c8258d7`](https://github.com/withastro/starlight/commit/c8258d7ef9264a0f85710d463a83d16013dc1934) Thanks [@delucis](https://github.com/delucis)! - Improves build performance slightly for bigger sites

- [#2199](https://github.com/withastro/starlight/pull/2199) [`91557fd`](https://github.com/withastro/starlight/commit/91557fd73a43ab596f0fefb7c9aa0218b9a0b208) Thanks [@connorjs](https://github.com/connorjs)! - Adds Azure DevOps (`azureDevOps`) icon for use in social links.

## 0.25.4

### Patch Changes

- [#2155](https://github.com/withastro/starlight/pull/2155) [`8bed886`](https://github.com/withastro/starlight/commit/8bed88674c732040cf66d392372386a8917a2eeb) Thanks [@delucis](https://github.com/delucis)! - Improves page load performance on slower devices

- [#2167](https://github.com/withastro/starlight/pull/2167) [`9ac7725`](https://github.com/withastro/starlight/commit/9ac7725dbe84f3fab9b191452471d8eaffd55048) Thanks [@delucis](https://github.com/delucis)! - Fixes an issue detecting the built-in locale when running Starlight in a web container environment on Firefox

- [#2166](https://github.com/withastro/starlight/pull/2166) [`4f12049`](https://github.com/withastro/starlight/commit/4f120490e914fb308e909b97890a11bb95ae964c) Thanks [@delucis](https://github.com/delucis)! - Updates `@astrojs/mdx`, `@astrojs/sitemap`, `astro-expressive-code`, `unified`, and `vfile` dependencies to the latest version

## 0.25.3

### Patch Changes

- [#2154](https://github.com/withastro/starlight/pull/2154) [`0b381d5`](https://github.com/withastro/starlight/commit/0b381d53f23c31492cf415057d960f9a5eaa2f3d) Thanks [@mktbsh](https://github.com/mktbsh)! - Updates `<head>` logic to deduplicate `<link rel="canonical">` tags. This means that custom canonicals set via frontmatter now override the default canonical generated by Starlight.

- [#2157](https://github.com/withastro/starlight/pull/2157) [`6757d97`](https://github.com/withastro/starlight/commit/6757d97b0ae789e0c61a776ad9af742858c663b0) Thanks [@astrobot-houston](https://github.com/astrobot-houston)! - Updates file tree icon mapping to correctly map `.cjs` and `.mjs` extensions in several contexts

- [#2156](https://github.com/withastro/starlight/pull/2156) [`904ad47`](https://github.com/withastro/starlight/commit/904ad47ea9588c0b1d8c583f3f04e4ae199474d9) Thanks [@delucis](https://github.com/delucis)! - Fixes builds for projects with a space in their pathname

- [#2137](https://github.com/withastro/starlight/pull/2137) [`703903b`](https://github.com/withastro/starlight/commit/703903bb782c3fabd3fe914e40494c00f12ec945) Thanks [@cevdetardaharan](https://github.com/cevdetardaharan)! - Removes `twitter:title` and `twitter:description` meta tags from `<head>`

## 0.25.2

### Patch Changes

- [#2126](https://github.com/withastro/starlight/pull/2126) [`ada51ee`](https://github.com/withastro/starlight/commit/ada51ee1500d07c1819059f57e97dc6e97b4d2ba) Thanks [@essential-randomness](https://github.com/essential-randomness)! - Adds support for markdown formatting in aside titles

- [#2135](https://github.com/withastro/starlight/pull/2135) [`9bbb969`](https://github.com/withastro/starlight/commit/9bbb9690616f79a80f3d286082b2500457bbcae9) Thanks [@oluwatobiss](https://github.com/oluwatobiss)! - Adds Pinterest social icon

## 0.25.1

### Patch Changes

- [#2122](https://github.com/withastro/starlight/pull/2122) [`359a642`](https://github.com/withastro/starlight/commit/359a64219288795936f18fd50fb5f195c412a748) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes an i18n configuration issue for multilingual sites when using Astro’s `i18n` config with `prefixDefaultLocale` set to `false`.

- [#2107](https://github.com/withastro/starlight/pull/2107) [`61e223b`](https://github.com/withastro/starlight/commit/61e223b153cb10958f3fbaa77acf6ac07d982944) Thanks [@sanabel-al-firdaws](https://github.com/sanabel-al-firdaws)! - Updates Arabic UI translations

- [#2105](https://github.com/withastro/starlight/pull/2105) [`81f8a2c`](https://github.com/withastro/starlight/commit/81f8a2c9580ec07dd17e2f596b9b1b50fae8237a) Thanks [@delucis](https://github.com/delucis)! - Fixes an edge case in custom pagination link processing

  Custom link values for `prev`/`next` in page frontmatter are now always used as authored.
  Previously this was not the case in some edge cases such as for the first and final pages in the sidebar.

- [#2119](https://github.com/withastro/starlight/pull/2119) [`464685a`](https://github.com/withastro/starlight/commit/464685a3ce33e7ccc8d1d7365935732c87ba95e9) Thanks [@evadecker](https://github.com/evadecker)! - Improves styling of `<hr>`, `<blockquote>`, and `<code>` within asides

## 0.25.0

### Minor Changes

- [#2025](https://github.com/withastro/starlight/pull/2025) [`47f32c1`](https://github.com/withastro/starlight/commit/47f32c196c5d840a6a45799ddf123d17c77274b0) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Removes the `/` search shortcut for [accessibility reasons](https://www.w3.org/WAI/WCAG21/Understanding/character-key-shortcuts.html).

  ⚠️ **Potentially breaking change:** The `search.shortcutLabel` UI string has been removed. If you were using this string in your custom UI, you will need to update your code.

- [#2064](https://github.com/withastro/starlight/pull/2064) [`c5b47cb`](https://github.com/withastro/starlight/commit/c5b47cbe1242f0b29b9212db72fe26590ab57d88) Thanks [@SnowDingo](https://github.com/SnowDingo)! - Improves styling of Markdown tables to work better in different contexts, including against different background colours like when used in asides.

- [#2031](https://github.com/withastro/starlight/pull/2031) [`2bab648`](https://github.com/withastro/starlight/commit/2bab648be9ddc6bfe05562650b773f5158a9ed42) Thanks [@delucis](https://github.com/delucis)! - Makes sidebar entry parsing stricter in Starlight config

  **⚠️ Potentially breaking change:** Previously Starlight would accept a sidebar entry that matched one of its expected shapes, even if it included additional properties. For example, including both `link` and `items` was considered valid, with `items` being ignored. Now, it is an error to include more than one of `link`, `items`, or `autogenerate` in a sidebar entry.

  If you see errors after updating, look for sidebar entries in the Starlight configuration in `astro.config.mjs` that include too many keys and remove the one that was previously ignored.

- [#1874](https://github.com/withastro/starlight/pull/1874) [`eeba06e`](https://github.com/withastro/starlight/commit/eeba06ea7df962e8f0520e145d28b8c17cd32c18) Thanks [@lorenzolewis](https://github.com/lorenzolewis)! - Adds a new syntax for specifying sidebar link items for internal links

  You can now specify an internal page using only its slug, either as a string, or as an object with a `slug` property:

  ```js
  starlight({
    title: 'Docs with easier sidebars',
    sidebar: ['getting-started', { slug: 'guides/installation' }],
  });
  ```

  Starlight will use the linked page’s frontmatter to configure the sidebar link.

### Patch Changes

- [#2081](https://github.com/withastro/starlight/pull/2081) [`f0181d2`](https://github.com/withastro/starlight/commit/f0181d2689248a46ff3eb6fc604bfcd95d4cb1aa) Thanks [@andrii-bodnar](https://github.com/andrii-bodnar)! - Updates the Ukrainian UI translations

## 0.24.5

### Patch Changes

- [#2062](https://github.com/withastro/starlight/pull/2062) [`5ac0ac6`](https://github.com/withastro/starlight/commit/5ac0ac6614e3c45d810a1594a2009d3febfa2793) Thanks [@evadecker](https://github.com/evadecker)! - Increase theme and language select inline padding

- [#2056](https://github.com/withastro/starlight/pull/2056) [`87e9ad0`](https://github.com/withastro/starlight/commit/87e9ad029c9730fca8df66e35828b57cd0872a61) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes an issue preventing remark plugins injected by Starlight plugins to handle Markdown text and leaf directives.

- [#2063](https://github.com/withastro/starlight/pull/2063) [`3ee1a94`](https://github.com/withastro/starlight/commit/3ee1a9404db25f5776a3c1ecd248614f64db46ae) Thanks [@delucis](https://github.com/delucis)! - Translate `fileTree.directory` and `aside.*` UI string into Norwegian (Bokmål).

- [#2054](https://github.com/withastro/starlight/pull/2054) [`dbfd3ee`](https://github.com/withastro/starlight/commit/dbfd3eeccacb5f5b77d75213dac3b30dc0be6deb) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes an issue when using the `<StarlightPage>` component in a custom page with a user-defined `srcDir` configuration.

## 0.24.4

### Patch Changes

- [#2038](https://github.com/withastro/starlight/pull/2038) [`87f3f92`](https://github.com/withastro/starlight/commit/87f3f925be6f9897b71b09a3041ec6d54be483b2) Thanks [@dragomano](https://github.com/dragomano)! - Updates Russian UI translations

- [#2043](https://github.com/withastro/starlight/pull/2043) [`53f4cd4`](https://github.com/withastro/starlight/commit/53f4cd443cf31b6135ff16eb74b5f26ee93ee2d5) Thanks [@playmr365](https://github.com/playmr365)! - Updates Czech UI translations

- [#2041](https://github.com/withastro/starlight/pull/2041) [`8af5a60`](https://github.com/withastro/starlight/commit/8af5a60ab14f4dae7f5a5e4ee535ae927273368b) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes `<Steps>` numbering bug caused by Chrome v126 CSS counter rewrite

## 0.24.3

### Patch Changes

- [#2028](https://github.com/withastro/starlight/pull/2028) [`af81ad3`](https://github.com/withastro/starlight/commit/af81ad38fd26c375c0372718fd3e152b7f1a0fa6) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes a search dialog height issue in Safari.

- [#2022](https://github.com/withastro/starlight/pull/2022) [`80f82b1`](https://github.com/withastro/starlight/commit/80f82b15afae1366676e0c25e674210a19606df5) Thanks [@playmr365](https://github.com/playmr365)! - Updates Czech UI translations

## 0.24.2

### Patch Changes

- [#2008](https://github.com/withastro/starlight/pull/2008) [`40359c7`](https://github.com/withastro/starlight/commit/40359c7b73d9c7d60f0b44a870dbc93ba941228f) Thanks [@vnepogodin](https://github.com/vnepogodin)! - Add Slovak language UI translation.

- [#2004](https://github.com/withastro/starlight/pull/2004) [`0aa2f06`](https://github.com/withastro/starlight/commit/0aa2f06d3a35a3c5182b4d461c8f3489ac145301) Thanks [@liruifengv](https://github.com/liruifengv)! - Removes an outdated export in `package.json`

- [#2007](https://github.com/withastro/starlight/pull/2007) [`44ca490`](https://github.com/withastro/starlight/commit/44ca490f36ecd6789d0865dd2506e5ea03dfa0fb) Thanks [@delucis](https://github.com/delucis)! - Updates internal dependencies

- [#1993](https://github.com/withastro/starlight/pull/1993) [`60165b2`](https://github.com/withastro/starlight/commit/60165b20c9d11a08c4c4793615778e045b41b7de) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes an i18n configuration issue when using a single root locale.

## 0.24.1

### Patch Changes

- [#1978](https://github.com/withastro/starlight/pull/1978) [`a5ab8cd6`](https://github.com/withastro/starlight/commit/a5ab8cd6a0095cb48b65b9784054714f87bd7e4d) Thanks [@kylewlacy](https://github.com/kylewlacy)! - Add new social icon for Zulip

- [#1962](https://github.com/withastro/starlight/pull/1962) [`2ef19a94`](https://github.com/withastro/starlight/commit/2ef19a947c54c7d2c085bf8820c862737e2ab08b) Thanks [@torn4dom4n](https://github.com/torn4dom4n)! - Updates Vietnamese UI translations

- [#1976](https://github.com/withastro/starlight/pull/1976) [`5a61f73c`](https://github.com/withastro/starlight/commit/5a61f73c198a33b27342c9b0371dd5fd22da2190) Thanks [@jsparkdev](https://github.com/jsparkdev)! - Updates Korean UI translations

- [#1987](https://github.com/withastro/starlight/pull/1987) [`0b8a8439`](https://github.com/withastro/starlight/commit/0b8a843936bd8506ac228608b07c54a76a7add19) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes issues with the locale text direction detection mechanism in some environments like WebContainers or Bun.

## 0.24.0

### Minor Changes

- [#1841](https://github.com/withastro/starlight/pull/1841) [`ee0cd38a`](https://github.com/withastro/starlight/commit/ee0cd38a1fae31717fe820e779baeabe693cd67a) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds support for `Astro.currentLocale` and Astro’s i18n routing.

  ⚠️ **Potentially breaking change:** Starlight now configures Astro’s `i18n` option for you based on its `locales` config.

  If you are currently using Astro’s `i18n` option as well as Starlight’s `locales` option, you will need to remove one of these.
  In general we recommend using Starlight’s `locales`, but if you have a more advanced configuration you may choose to keep Astro’s `i18n` config instead.

- [#1958](https://github.com/withastro/starlight/pull/1958) [`081d1a96`](https://github.com/withastro/starlight/commit/081d1a969462633e41ca95a18a1ec121cb4af5d2) Thanks [@delucis](https://github.com/delucis)! - Allows users to opt into displaying a “Built with Starlight” link in the site footer

- [#1530](https://github.com/withastro/starlight/pull/1530) [`dd64836a`](https://github.com/withastro/starlight/commit/dd64836af45f33df4a99ab864eabb91fc9b8e204) Thanks [@kevinzunigacuellar](https://github.com/kevinzunigacuellar)! - Adds a new `<Badge>` component

## 0.23.4

### Patch Changes

- [#1955](https://github.com/withastro/starlight/pull/1955) [`15ef1f4b`](https://github.com/withastro/starlight/commit/15ef1f4bdbf7174134121f4bbdf82ca3903c802a) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Reverts a [change](https://github.com/withastro/starlight/pull/1948) to prevent a numbering issue with the `<Steps>` component in future versions of Chrome.

## 0.23.3

### Patch Changes

- [#1948](https://github.com/withastro/starlight/pull/1948) [`68c0c077`](https://github.com/withastro/starlight/commit/68c0c077a9ca5ec2a8206e99b70236043a74c3b8) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes a `<Steps>` component numbering issue with the next Chrome stable version when a step contains a nested list.

- [#1909](https://github.com/withastro/starlight/pull/1909) [`c98c7088`](https://github.com/withastro/starlight/commit/c98c7088ee3ecd43522dac0916fd41c417693f65) Thanks [@joshka](https://github.com/joshka)! - Adds Discourse to social icons

## 0.23.2

### Patch Changes

- [#1913](https://github.com/withastro/starlight/pull/1913) [`7ebe8f75`](https://github.com/withastro/starlight/commit/7ebe8f7599d473cdd22c80bb0fe115fe6120cab7) Thanks [@delucis](https://github.com/delucis)! - Fixes support for Astro’s `build: { format: 'preserve' }` configuration option

- [#1941](https://github.com/withastro/starlight/pull/1941) [`2f3240c9`](https://github.com/withastro/starlight/commit/2f3240c91c09dfc411d93a71eeb75ad6d704e14b) Thanks [@astrobot-houston](https://github.com/astrobot-houston)! - Adds icon support for `.otf` files in `<FileTree>`

## 0.23.1

### Patch Changes

- [#1892](https://github.com/withastro/starlight/pull/1892) [`01de9be8`](https://github.com/withastro/starlight/commit/01de9be89c85bcd0022e87465182ee1aba501687) Thanks [@delucis](https://github.com/delucis)! - Internal refactor: simplify some CSS for the `<details>` element

## 0.23.0

### Minor Changes

- [#1846](https://github.com/withastro/starlight/pull/1846) [`2de67039`](https://github.com/withastro/starlight/commit/2de6703971908cfc0df2915ebf89a63e0141f954) Thanks [@delucis](https://github.com/delucis)! - Updates `@astrojs/mdx` to v3 and enables MDX optimization by default

  ⚠️ **Potentially breaking change:** MDX optimization speeds up builds (Starlight’s docs are building ~40% faster for example), but restricts some advanced MDX features. See full details in the [MDX optimization documentation](https://docs.astro.build/en/guides/integrations-guide/mdx/#optimize).

  Most Starlight users should be unaffected, but if you are using MDX files outside of Starlight pages with the `components` prop, you may see issues. You can disable optimization by adding MDX manually to your `integrations` array in `astro.config.mjs`:

  ```diff
  import { defineConfig } from 'astro/config';
  + import mdx from '@astrojs/mdx';
  import starlight from '@astrojs/starlight';

  // https://astro.build/config
  export default defineConfig({
  	integrations: [
  		starlight({
  			title: 'My docs',
  			// ...
  		}),
  +		mdx(),
  	],
  });
  ```

- [#1735](https://github.com/withastro/starlight/pull/1735) [`1a9ab50d`](https://github.com/withastro/starlight/commit/1a9ab50d458d6274994ffe66a23fe7a30681337a) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds custom styles for `<details>` and `<summary>` elements in Markdown content.

- [#1846](https://github.com/withastro/starlight/pull/1846) [`2de67039`](https://github.com/withastro/starlight/commit/2de6703971908cfc0df2915ebf89a63e0141f954) Thanks [@delucis](https://github.com/delucis)! - ⚠️ **BREAKING CHANGE:** The minimum supported version of Astro is now 4.8.6

  Please update Astro and Starlight together:

  ```sh
  npx @astrojs/upgrade
  ```

## 0.22.4

### Patch Changes

- [#1871](https://github.com/withastro/starlight/pull/1871) [`03bb126b`](https://github.com/withastro/starlight/commit/03bb126b74d9adaba1be2f0df3f34566815dd77f) Thanks [@delucis](https://github.com/delucis)! - Adds a `blueSky` icon and social link option

- [#1873](https://github.com/withastro/starlight/pull/1873) [`13f33b81`](https://github.com/withastro/starlight/commit/13f33b81fd51d18165eb52f2a0c02b890084e4bd) Thanks [@ekfuhrmann](https://github.com/ekfuhrmann)! - Adds 1 new icon: `alpine`

- [#1857](https://github.com/withastro/starlight/pull/1857) [`32cdfaf0`](https://github.com/withastro/starlight/commit/32cdfaf0155e65ff6fbe9c0cfacd6969ab0015d9) Thanks [@tarikcoskun](https://github.com/tarikcoskun)! - Updates Turkish UI translations

- [#1736](https://github.com/withastro/starlight/pull/1736) [`cfa94a34`](https://github.com/withastro/starlight/commit/cfa94a346ef10804b90db28d217be175e1c1d5ed) Thanks [@julien-deramond](https://github.com/julien-deramond)! - Prevent list items from overflowing Markdown content

## 0.22.3

### Patch Changes

- [#1838](https://github.com/withastro/starlight/pull/1838) [`9fe84754`](https://github.com/withastro/starlight/commit/9fe847544f1edb85bf5b25cd81db39227814335e) Thanks [@delucis](https://github.com/delucis)! - Adds extra information to the errors thrown by the `<Steps>` component to help locate misformatted code

- [#1863](https://github.com/withastro/starlight/pull/1863) [`50be60bb`](https://github.com/withastro/starlight/commit/50be60bbc5cbc42db42e868b9e8f128b4dcbd6a5) Thanks [@torn4dom4n](https://github.com/torn4dom4n)! - Update Vietnamese translation

- [#1837](https://github.com/withastro/starlight/pull/1837) [`a33a1223`](https://github.com/withastro/starlight/commit/a33a12231772c1dc4b7cc2db3477a6802f3ef53e) Thanks [@delucis](https://github.com/delucis)! - Adds three new icons: `comment`, `comment-alt`, `heart`

- [#1842](https://github.com/withastro/starlight/pull/1842) [`c7838636`](https://github.com/withastro/starlight/commit/c7838636edb8d60a2422ce76a2db511b9cebbb70) Thanks [@delucis](https://github.com/delucis)! - Moves the `href` used in the site title link to Starlight’s route data object. This makes it possible for overrides to change the title link while reusing Starlight’s default component implementation.

- [#1840](https://github.com/withastro/starlight/pull/1840) [`cb85563c`](https://github.com/withastro/starlight/commit/cb85563c9a3d4eb2925ad884e6a4e8698a15381b) Thanks [@MiahaCybersec](https://github.com/MiahaCybersec)! - Adds 1 new icon: `hackerone`

## 0.22.2

### Patch Changes

- [#1811](https://github.com/withastro/starlight/pull/1811) [`fe06aa13`](https://github.com/withastro/starlight/commit/fe06aa1307208ef9f5b249181ec29837f96940c2) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes a `<Tabs>` sync issue when inconsistently using the `icon` prop or not on `<TabItem>` components.

- [#1826](https://github.com/withastro/starlight/pull/1826) [`52ea7381`](https://github.com/withastro/starlight/commit/52ea7381e131338a03cffb3499ba1699951cea1e) Thanks [@dragomano](https://github.com/dragomano)! - Updates Russian UI translations

## 0.22.1

### Patch Changes

- [`1c0fc384`](https://github.com/withastro/starlight/commit/1c0fc3849771713d5a3e7a572bdbf1483ae5551b) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes an issue where the `siteTitle` property would not be set when using the `<StarlightPage />` component.

## 0.22.0

### Minor Changes

- [#640](https://github.com/withastro/starlight/pull/640) [`7dc503ea`](https://github.com/withastro/starlight/commit/7dc503ea7993123a4aeff453d08de41cac887353) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds support for syncing multiple sets of tabs on the same page.

- [#1620](https://github.com/withastro/starlight/pull/1620) [`ca0678ca`](https://github.com/withastro/starlight/commit/ca0678ca556d739bda9648edc1b79c764fdea851) Thanks [@emjio](https://github.com/emjio)! - Adds support for translating the site title

  ⚠️ **Potentially breaking change:** The shape of the `title` field on Starlight’s internal config object has changed. This used to be a string, but is now an object.

  If you are relying on `config.title` (for example in a custom `<SiteTitle>` or `<Head>` component), you will need to update your code. We recommend using the new [`siteTitle` prop](https://starlight.astro.build/reference/overrides/#sitetitle) available to component overrides:

  ```astro
  ---
  import type { Props } from '@astrojs/starlight/props';

  // The site title for this page’s language:
  const { siteTitle } = Astro.props;
  ---
  ```

- [#1613](https://github.com/withastro/starlight/pull/1613) [`61493e55`](https://github.com/withastro/starlight/commit/61493e55f1a80362af13f98d665018376e987439) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds new `draft` frontmatter option to exclude a page from production builds.

- [#640](https://github.com/withastro/starlight/pull/640) [`7dc503ea`](https://github.com/withastro/starlight/commit/7dc503ea7993123a4aeff453d08de41cac887353) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Updates the default `line-height` from `1.8` to `1.75`. This change avoids having a line height with a fractional part which can cause scripts accessing dimensions involving the line height to get an inconsistent rounded value in various browsers.

  If you want to preserve the previous `line-height`, you can add the following custom CSS to your site:

  ```css
  :root {
    --sl-line-height: 1.8;
  }
  ```

- [#1720](https://github.com/withastro/starlight/pull/1720) [`749ddf85`](https://github.com/withastro/starlight/commit/749ddf85a21d8ed1bfedbe60dee676cdd8784e96) Thanks [@jacobdalamb](https://github.com/jacobdalamb)! - Updates `astro-expressive-code` dependency to the latest minor release (0.35) and exposes a new `@astrojs/starlight/expressive-code/hast` module for users who need to use Expressive Code’s version of `hast`.

  This includes a potentially breaking change if you use custom Expressive Code plugins. See the [Expressive Code release notes](https://expressive-code.com/releases/#0340) for full details.

- [#1769](https://github.com/withastro/starlight/pull/1769) [`bd5f1cbd`](https://github.com/withastro/starlight/commit/bd5f1cbd5aef9e2d78e7f7187eb07deee87399d0) Thanks [@ncjones](https://github.com/ncjones)! - Adds support for [accessing frontmatter data as a variable](https://docs.astro.build/en/guides/integrations-guide/markdoc/#access-frontmatter-from-your-markdoc-content) when using Markdoc

### Patch Changes

- [#1788](https://github.com/withastro/starlight/pull/1788) [`681a4273`](https://github.com/withastro/starlight/commit/681a427366755fec71ba65d45e36f7d1267cf387) Thanks [@dragomano](https://github.com/dragomano)! - Adds Russian translations for Expressive Code labels

- [#1780](https://github.com/withastro/starlight/pull/1780) [`4db6025a`](https://github.com/withastro/starlight/commit/4db6025a1c5c56cac2e3a98bd2e13124402445c7) Thanks [@MiahaCybersec](https://github.com/MiahaCybersec)! - Adds 1 new icon: `signal`

- [#1785](https://github.com/withastro/starlight/pull/1785) [`65009c9c`](https://github.com/withastro/starlight/commit/65009c9cf8b0570303ecb87713e1c2968a704437) Thanks [@dreyfus92](https://github.com/dreyfus92)! - Adds 5 new icons: `node`, `cloudflare`, `vercel`, `netlify` and `deno`

- [#1786](https://github.com/withastro/starlight/pull/1786) [`d05d693a`](https://github.com/withastro/starlight/commit/d05d693afcf1771b8269dfe2ccc94f8952c643e8) Thanks [@delucis](https://github.com/delucis)! - Fixes type inference for i18n strings added by extending the default schema

- [#1777](https://github.com/withastro/starlight/pull/1777) [`6949404b`](https://github.com/withastro/starlight/commit/6949404b24a1c8254fd32d75122fdfbaf896fe29) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes an issue where TypeScript could fail to serialize the frontmatter schema when configured to emit declaration files

- [#1734](https://github.com/withastro/starlight/pull/1734) [`4493dcfa`](https://github.com/withastro/starlight/commit/4493dcfac5171f839b1b0e39444a15ce696adee4) Thanks [@delucis](https://github.com/delucis)! - Refactors `<ThemeSelect>` custom element logic to improve performance

- [#1731](https://github.com/withastro/starlight/pull/1731) [`f08b0dff`](https://github.com/withastro/starlight/commit/f08b0dff9638bbe7704ac2ba2e855d8d1464ba76) Thanks [@techfg](https://github.com/techfg)! - Fixes responding to system color scheme changes when theme is `auto`

- [#1793](https://github.com/withastro/starlight/pull/1793) [`2616f0c7`](https://github.com/withastro/starlight/commit/2616f0c7acf39a99c9f92b3db4108cae81120034) Thanks [@Mrahmani71](https://github.com/Mrahmani71)! - Updates the Farsi UI translations

## 0.21.5

### Patch Changes

- [#1728](https://github.com/withastro/starlight/pull/1728) [`0a75680d`](https://github.com/withastro/starlight/commit/0a75680ddd2f3325ab9ad7ac910f7c884b89a9ed) Thanks [@delucis](https://github.com/delucis)! - Adds 1 new icon: `pkl`

- [#1709](https://github.com/withastro/starlight/pull/1709) [`c5cd1811`](https://github.com/withastro/starlight/commit/c5cd181186b42422f3e47052bf8182cb490bda6b) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes a UI strings translation issue for sites configured with a single non-root language different from English.

- [#1723](https://github.com/withastro/starlight/pull/1723) [`3b29b3ab`](https://github.com/withastro/starlight/commit/3b29b3ab824f538f27e20310cb08786a92c7bd65) Thanks [@OliverSpeir](https://github.com/OliverSpeir)! - Fixes accessibility by using `aria-selected="false"` for inactive tabs instead of removing `aria-selected="true"` in the tablist of Starlight’s `<Tabs>` component

- [#1706](https://github.com/withastro/starlight/pull/1706) [`f171ac4d`](https://github.com/withastro/starlight/commit/f171ac4d6396eb2538598d85957670df50938b6a) Thanks [@jorenbroekema](https://github.com/jorenbroekema)! - Fixes some minor type errors

## 0.21.4

### Patch Changes

- [#1703](https://github.com/withastro/starlight/pull/1703) [`b26238f2`](https://github.com/withastro/starlight/commit/b26238f22990dcf8ba002bea6a50c66f20ad5786) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes aside custom titles rendering for nested asides.

- [#1708](https://github.com/withastro/starlight/pull/1708) [`a72cb966`](https://github.com/withastro/starlight/commit/a72cb96600798c1fbc7558f8fd24556ca442d312) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes translation issues with Expressive Code when using a default language other than English

## 0.21.3

### Patch Changes

- [#1622](https://github.com/withastro/starlight/pull/1622) [`3a074bad`](https://github.com/withastro/starlight/commit/3a074bad6c139bb9d6169d95ec79bc0fc1ecbdfe) Thanks [@SamuelLHuber](https://github.com/SamuelLHuber)! - Adds 1 new icon: `farcaster`

- [#1616](https://github.com/withastro/starlight/pull/1616) [`a86f9b71`](https://github.com/withastro/starlight/commit/a86f9b71b795fb6dcd0409ca568e43d25525b964) Thanks [@dragomano](https://github.com/dragomano)! - Updates Russian UI strings

- [#1698](https://github.com/withastro/starlight/pull/1698) [`67b892fd`](https://github.com/withastro/starlight/commit/67b892fd5290dfd0eeb95f4e60b6427bdc82110f) Thanks [@liruifengv](https://github.com/liruifengv)! - Adds 1 new icon: `starlight`

- [#1687](https://github.com/withastro/starlight/pull/1687) [`6fa9ea7e`](https://github.com/withastro/starlight/commit/6fa9ea7e8d4d601cf8f49b61dafb1ebb557d1718) Thanks [@mingjunlu](https://github.com/mingjunlu)! - Translates `fileTree.directory` UI string into Traditional Chinese.

## 0.21.2

### Patch Changes

- [#1628](https://github.com/withastro/starlight/pull/1628) [`24c0823c`](https://github.com/withastro/starlight/commit/24c0823c61b1e9850575766876f2e1035541cfd1) Thanks [@o-az](https://github.com/o-az)! - Adds 1 new icon: `nix`

- [#1614](https://github.com/withastro/starlight/pull/1614) [`78fc9042`](https://github.com/withastro/starlight/commit/78fc90426d58d6c36dcb8215e3181476d0702f50) Thanks [@kpodurgiel](https://github.com/kpodurgiel)! - Adds Polish UI translations

- [#1596](https://github.com/withastro/starlight/pull/1596) [`13ed30cd`](https://github.com/withastro/starlight/commit/13ed30cd335798177dfe24a27851d2c14d2fe80a) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds support for toggling the built-in search modal using the `Ctrl+k` keyboard shortcut.

- [#1608](https://github.com/withastro/starlight/pull/1608) [`4096e1b7`](https://github.com/withastro/starlight/commit/4096e1b77b3464338e5489d00cec4c29a1cd3c32) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Removes nested CSS from the `<FileTree>` component to prevent a potential warning when using Tailwind CSS.

- [#1626](https://github.com/withastro/starlight/pull/1626) [`67459cb4`](https://github.com/withastro/starlight/commit/67459cb4021859f4a45d50a5f993d2c849f340a3) Thanks [@hippotastic](https://github.com/hippotastic)! - Fixes a bundling issue that caused imports from `@astrojs/starlight/components` to fail when using the config setting `expressiveCode: false`.

## 0.21.1

### Patch Changes

- [#1584](https://github.com/withastro/starlight/pull/1584) [`8851d5cd`](https://github.com/withastro/starlight/commit/8851d5cd0d8f8439320ef729ca57a59418db52b9) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds 2 new icons: `apple` and `linux`.

- [#1577](https://github.com/withastro/starlight/pull/1577) [`0ba77890`](https://github.com/withastro/starlight/commit/0ba77890e0dcf54a849c735efd870327c10972aa) Thanks [@morinokami](https://github.com/morinokami)! - Translates `fileTree.directory` UI string into Japanese.

- [#1593](https://github.com/withastro/starlight/pull/1593) [`fa7ed245`](https://github.com/withastro/starlight/commit/fa7ed2458caf6261d16c5f43365cedbcb8572a48) Thanks [@liruifengv](https://github.com/liruifengv)! - Translates `fileTree.directory` UI string into simplified Chinese.

- [#1585](https://github.com/withastro/starlight/pull/1585) [`bd4e278f`](https://github.com/withastro/starlight/commit/bd4e278f7fe7d7335494602db29a63002fd45059) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Translates `fileTree.directory` UI string into French.

- [#1587](https://github.com/withastro/starlight/pull/1587) [`c5794260`](https://github.com/withastro/starlight/commit/c5794260251ed414a396089782a1788539c92dd3) Thanks [@Eveeifyeve](https://github.com/Eveeifyeve)! - Adds 1 new icon: `homebrew`.

## 0.21.0

### Minor Changes

- [#1568](https://github.com/withastro/starlight/pull/1568) [`5f99a71d`](https://github.com/withastro/starlight/commit/5f99a71ddfe92568b1cd3c0bfe5ebfd139797c1a) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds support for optionally setting an icon on a `<TabItem>` component to make it easier to visually distinguish between tabs.

- [#1308](https://github.com/withastro/starlight/pull/1308) [`9a918a5b`](https://github.com/withastro/starlight/commit/9a918a5b4902f43729f4d023257772710af3a12b) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds `<FileTree>` component to display the structure of a directory.

- [#1308](https://github.com/withastro/starlight/pull/1308) [`9a918a5b`](https://github.com/withastro/starlight/commit/9a918a5b4902f43729f4d023257772710af3a12b) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds 144 new file-type icons from the [Seti UI icon set](https://github.com/jesseweed/seti-ui#current-icons), available with the `seti:` prefix, e.g. `seti:javascript`.

- [#1564](https://github.com/withastro/starlight/pull/1564) [`d880065e`](https://github.com/withastro/starlight/commit/d880065e29a632823a08adcb6158a59fd9557270) Thanks [@delucis](https://github.com/delucis)! - Adds a `<Steps>` component for styling more complex guided tasks.

- [#1308](https://github.com/withastro/starlight/pull/1308) [`9a918a5b`](https://github.com/withastro/starlight/commit/9a918a5b4902f43729f4d023257772710af3a12b) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds 5 new icons: `astro`, `biome`, `bun`, `mdx`, and `pnpm`.

## 0.20.1

### Patch Changes

- [#1553](https://github.com/withastro/starlight/pull/1553) [`8e091147`](https://github.com/withastro/starlight/commit/8e09114755d37322d6e97b0dc90a5dfd781de8cc) Thanks [@hippotastic](https://github.com/hippotastic)! - Updates Expressive Code to v0.33.4 to fix potential race condition bug in Shiki.

## 0.20.0

### Minor Changes

- [#1541](https://github.com/withastro/starlight/pull/1541) [`1043052f`](https://github.com/withastro/starlight/commit/1043052f3890a577a73276472f3773924909406b) Thanks [@hippotastic](https://github.com/hippotastic)! - Updates `astro-expressive-code` dependency to the latest minor release (0.33).

  This unlocks support for [word wrap](https://expressive-code.com/key-features/word-wrap/) and [line numbers](https://expressive-code.com/plugins/line-numbers/), as well as updating the syntax highlighter to the latest Shiki release, which includes new and updated language grammars.

  See the [Expressive Code release notes](https://expressive-code.com/releases/) for more information including details of potentially breaking changes.

### Patch Changes

- [#1542](https://github.com/withastro/starlight/pull/1542) [`b3b7a606`](https://github.com/withastro/starlight/commit/b3b7a6069952d5f27a49b2fd097aa4db065e1718) Thanks [@delucis](https://github.com/delucis)! - Improves error messages shown by Starlight for configuration errors.

- [#1544](https://github.com/withastro/starlight/pull/1544) [`65dc6586`](https://github.com/withastro/starlight/commit/65dc6586ef7c1754875db1d48c49e709051a0b13) Thanks [@torn4dom4n](https://github.com/torn4dom4n)! - Update Vietnamese UI translations

## 0.19.1

### Patch Changes

- [#1527](https://github.com/withastro/starlight/pull/1527) [`163bc84`](https://github.com/withastro/starlight/commit/163bc848e173eecca92d1cb034045fdb42aa4ff1) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Exports the `StarlightPageProps` TypeScript type representing the props expected by the `<StarlightPage />` component.

- [#1504](https://github.com/withastro/starlight/pull/1504) [`fc83a05`](https://github.com/withastro/starlight/commit/fc83a05235b74be2bfe6ba8e7f95a8a5a618ead3) Thanks [@mingjunlu](https://github.com/mingjunlu)! - Adds Traditional Chinese UI translations

- [#1534](https://github.com/withastro/starlight/pull/1534) [`aada680`](https://github.com/withastro/starlight/commit/aada6805abc0068f07393585b86978ef5200439c) Thanks [@delucis](https://github.com/delucis)! - Improves DX of the `sidebar` prop used by the new `<StarlightPage>` component.

## 0.19.0

### Minor Changes

- [#1485](https://github.com/withastro/starlight/pull/1485) [`2cb3578`](https://github.com/withastro/starlight/commit/2cb35782dace67c7c418a31005419fa95493b3d3) Thanks [@timokoessler](https://github.com/timokoessler)! - Add support for setting html attributes of hero action links

- [#1175](https://github.com/withastro/starlight/pull/1175) [`dd11b95`](https://github.com/withastro/starlight/commit/dd11b9538abdf4b5ba2ef70e07c0edda03e95add) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds a new `<StarlightPage>` component to use the Starlight layout in custom pages.

  To learn more about this new feature, check out the new [“Using Starlight’s design in custom pages” guide](https://starlight.astro.build/guides/pages/#using-starlights-design-in-custom-pages).

- [#1499](https://github.com/withastro/starlight/pull/1499) [`97bf523`](https://github.com/withastro/starlight/commit/97bf523923fb9678c12f58fcdbe36757f0e56ceb) Thanks [@delucis](https://github.com/delucis)! - Adds a new `<Aside>` component

  The new component is in addition to the existing custom Markdown syntax.

## 0.18.1

### Patch Changes

- [#1487](https://github.com/withastro/starlight/pull/1487) [`6a72bda`](https://github.com/withastro/starlight/commit/6a72bda8c5569e2eda68fdf258ae9b1dc8b320d6) Thanks [@NavyStack](https://github.com/NavyStack)! - Improves Korean UI translations

- [#1489](https://github.com/withastro/starlight/pull/1489) [`b0d36de`](https://github.com/withastro/starlight/commit/b0d36de3398d4895603a787b612b1f0747defbdc) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fixes a potential text rendering issue with text containing colons.

## 0.18.0

### Minor Changes

- [#1454](https://github.com/withastro/starlight/pull/1454) [`1d9ef56`](https://github.com/withastro/starlight/commit/1d9ef567907bed7210e75ab3460f536c0768a87f) Thanks [@Fryuni](https://github.com/Fryuni)! - Makes Starlight compatible with [on-demand server rendering](https://docs.astro.build/en/guides/server-side-rendering/) (sometimes referred to as server-side rendering or SSR).

  Starlight pages are always prerendered, even when using `output: 'server'`.

- [#1454](https://github.com/withastro/starlight/pull/1454) [`1d9ef56`](https://github.com/withastro/starlight/commit/1d9ef567907bed7210e75ab3460f536c0768a87f) Thanks [@Fryuni](https://github.com/Fryuni)! - Enables Astro’s [`experimental.globalRoutePriority`](https://docs.astro.build/en/reference/configuration-reference/#experimentalglobalroutepriority) option and bumps the minimum required Astro version.

  ⚠️ **BREAKING CHANGE** The minimum supported Astro version is now 4.2.7. Upgrade Astro and Starlight together:

  ```sh
  npx @astrojs/upgrade
  ```

## 0.17.4

### Patch Changes

- [#1473](https://github.com/withastro/starlight/pull/1473) [`29da505`](https://github.com/withastro/starlight/commit/29da505474174fefaec4e27a2c2c3e90e3f68a31) Thanks [@delucis](https://github.com/delucis)! - Fixes a CSS bug for users with JavaScript disabled

- [#1465](https://github.com/withastro/starlight/pull/1465) [`ce3108c`](https://github.com/withastro/starlight/commit/ce3108cf6ecb77d12db973485d21e0fc7fd63ca6) Thanks [@delucis](https://github.com/delucis)! - Updates internal MDX, sitemap, and Expressive Code dependencies to the latest versions

## 0.17.3

### Patch Changes

- [#1461](https://github.com/withastro/starlight/pull/1461) [`2e17880`](https://github.com/withastro/starlight/commit/2e17880957d1aae2a84c77500afa9b66e5292a6a) Thanks [@liruifengv](https://github.com/liruifengv)! - Improves the table of contents title translation in Simplified Chinese

- [#1462](https://github.com/withastro/starlight/pull/1462) [`4741ccc`](https://github.com/withastro/starlight/commit/4741cccc8adbef500bcaf95416a1c61a90761c06) Thanks [@delucis](https://github.com/delucis)! - Fixes overflow of very long site titles on narrow viewports

- [#1459](https://github.com/withastro/starlight/pull/1459) [`9a8e0ec`](https://github.com/withastro/starlight/commit/9a8e0ec59cba0e088512ea9b6d17224085f3a178) Thanks [@delucis](https://github.com/delucis)! - Fixes a bug where table of contents highlighting could break given very specific combinations of content and viewport size

- [#1458](https://github.com/withastro/starlight/pull/1458) [`8c88642`](https://github.com/withastro/starlight/commit/8c88642875e8344396074a780e28fb0860b249f8) Thanks [@delucis](https://github.com/delucis)! - Silences i18n content collection warnings for projects without custom translations.

## 0.17.2

### Patch Changes

- [#1442](https://github.com/withastro/starlight/pull/1442) [`1a642e4`](https://github.com/withastro/starlight/commit/1a642e4d74ee4c30e85bce37b41888b1eae0544a) Thanks [@delucis](https://github.com/delucis)! - Fixes URLs in language picker for sites with `build.format: 'file'`

- [#1440](https://github.com/withastro/starlight/pull/1440) [`2ea1e88`](https://github.com/withastro/starlight/commit/2ea1e883186660b48f0ea8c4da7fead5fb74e313) Thanks [@hippotastic](https://github.com/hippotastic)! - Adds JS support to the `@astrojs/starlight/expressive-code` export to allow importing from non-TS environments.

## 0.17.1

### Patch Changes

- [#1437](https://github.com/withastro/starlight/pull/1437) [`655aed4`](https://github.com/withastro/starlight/commit/655aed4840cae59e9abd64b4b585e60f1cfab209) Thanks [@hippotastic](https://github.com/hippotastic)! - Adds Starlight-specific types to `defineEcConfig` function and exports `StarlightExpressiveCodeOptions`.

  This provides Starlight types and IntelliSense support for your Expressive Code configuration options inside an `ec.config.mjs` file. See the [Expressive Code documentation](https://expressive-code.com/key-features/code-component/#using-an-ecconfigmjs-file) for more information.

- [#1420](https://github.com/withastro/starlight/pull/1420) [`275f87f`](https://github.com/withastro/starlight/commit/275f87fd7fc676b9ab323354078c06894e0832c7) Thanks [@abdelhalimjean](https://github.com/abdelhalimjean)! - Fix rare `font-family` issue if users have a font installed with a name of `""`

- [#1365](https://github.com/withastro/starlight/pull/1365) [`a0af7cc`](https://github.com/withastro/starlight/commit/a0af7cc696da987a76edab96cdd2329779e87724) Thanks [@kevinzunigacuellar](https://github.com/kevinzunigacuellar)! - Correctly format Pagefind search result links when `trailingSlash: 'never'` is used

## 0.17.0

### Minor Changes

- [#1389](https://github.com/withastro/starlight/pull/1389) [`21b3620`](https://github.com/withastro/starlight/commit/21b36201aa1e01c8395d0f24b2fa4e32b90550bb) Thanks [@connor-baer](https://github.com/connor-baer)! - Adds new `disable404Route` config option to disable injection of Astro’s default 404 route

- [#1395](https://github.com/withastro/starlight/pull/1395) [`ce05dfb`](https://github.com/withastro/starlight/commit/ce05dfb4b1e9b90fad057d5d4328e4445f986b3b) Thanks [@hippotastic](https://github.com/hippotastic)! - Adds a new [`<Code>` component](https://starlight.astro.build/guides/components/#code) to render dynamic code strings with Expressive Code

## 0.16.0

### Minor Changes

- [#1383](https://github.com/withastro/starlight/pull/1383) [`490c6ef`](https://github.com/withastro/starlight/commit/490c6eff34ab408c4f55777b7b0caa16787dd3d4) Thanks [@delucis](https://github.com/delucis)! - Refactors Starlight’s internal virtual module system for components to avoid circular references

  This is a change to an internal API.
  If you were importing the internal `virtual:starlight/components` module, this no longer exists.
  Update your imports to use the individual virtual modules now available for each component, for example `virtual:starlight/components/EditLink`.

- [#1151](https://github.com/withastro/starlight/pull/1151) [`134292d`](https://github.com/withastro/starlight/commit/134292ddd89683007d7de25545d39738a82c626c) Thanks [@kevinzunigacuellar](https://github.com/kevinzunigacuellar)! - Fixes sidebar auto-generation issue when a file and a directory, located at the same level, have identical names.

  For example, `src/content/docs/guides.md` and `src/content/docs/guides/example.md` will now both be included and `src/content/docs/guides.md` is treated in the same way a `src/content/docs/guides/index.md` file would be.

- [#1386](https://github.com/withastro/starlight/pull/1386) [`0163634`](https://github.com/withastro/starlight/commit/0163634abb8578ce7a3d7ceea36432e98ea70e78) Thanks [@delucis](https://github.com/delucis)! - Tightens `line-height` on `<LinkCard>` titles to fix regression from original design

  If you want to preserve the previous `line-height`, you can add the following custom CSS to your site:

  ```css
  .sl-link-card a {
    line-height: 1.6;
  }
  ```

- [#1376](https://github.com/withastro/starlight/pull/1376) [`8398432`](https://github.com/withastro/starlight/commit/8398432aa4a0f38e2dd4452dfcdf7033c5713334) Thanks [@delucis](https://github.com/delucis)! - Tweaks vertical spacing in Markdown content styles.

  This is a subtle change to Starlight’s default content styling that should improve most sites:

  - Default vertical spacing between content items is reduced from `1.5rem` to `1rem`.
  - Spacing before headings is now relative to font size, meaning higher-level headings have slightly more spacing and lower-level headings slightly less.

  The overall impact is to tighten up content that belongs together and improve the visual hierarchy of headings to break up sections.

  Although this is a subtle change, we recommend visually inspecting your site in case this impacts layout of any custom CSS or components.

  If you want to preserve the previous spacing, you can add the following custom CSS to your site:

  ```css
  /* Restore vertical spacing to match Starlight v0.15 and below. */
  .sl-markdown-content
    :not(a, strong, em, del, span, input, code)
    + :not(a, strong, em, del, span, input, code, :where(.not-content *)) {
    margin-top: 1.5rem;
  }
  .sl-markdown-content
    :not(h1, h2, h3, h4, h5, h6)
    + :is(h1, h2, h3, h4, h5, h6):not(:where(.not-content *)) {
    margin-top: 2.5rem;
  }
  ```

- [#1372](https://github.com/withastro/starlight/pull/1372) [`773880d`](https://github.com/withastro/starlight/commit/773880de87b79bf3107dbc32df29a86dd11e4e6f) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Updates the table of contents highlighting styles to prevent UI shifts when scrolling through a page.

  If you want to preserve the previous, buggy styling, you can add the following custom CSS to your site:

  ```css
  starlight-toc a[aria-current='true'],
  starlight-toc a[aria-current='true']:hover,
  starlight-toc a[aria-current='true']:focus {
    font-weight: 600;
    color: var(--sl-color-text-invert);
    background-color: var(--sl-color-text-accent);
  }
  ```

## 0.15.4

### Patch Changes

- [#1378](https://github.com/withastro/starlight/pull/1378) [`0f4a31d`](https://github.com/withastro/starlight/commit/0f4a31da4b6d384c569e8556dcc559dc8bfbfebd) Thanks [@delucis](https://github.com/delucis)! - Updates dependencies: `@astrojs/mdx`, `@astrojs/sitemap`, and `astro-expressive-code`

## 0.15.3

### Patch Changes

- [#1303](https://github.com/withastro/starlight/pull/1303) [`3eefd21`](https://github.com/withastro/starlight/commit/3eefd21f2267648b17bc2d6874350fd5dd8bbcb2) Thanks [@lilnasy](https://github.com/lilnasy)! - chore: fix type errors in Starlight internals

- [#1351](https://github.com/withastro/starlight/pull/1351) [`932c022`](https://github.com/withastro/starlight/commit/932c0229d7d8d55f30161ccc36c908140c1f252a) Thanks [@roberto-butti](https://github.com/roberto-butti)! - Adds Italian translation for `search.devWarning` UI

- [#1298](https://github.com/withastro/starlight/pull/1298) [`c7e995c`](https://github.com/withastro/starlight/commit/c7e995cb018179789b5ee45bae5fdd9c20309945) Thanks [@kevinzunigacuellar](https://github.com/kevinzunigacuellar)! - Fixes incorrect sorting behavior for some autogenerated sidebars

- [#1347](https://github.com/withastro/starlight/pull/1347) [`8994d00`](https://github.com/withastro/starlight/commit/8994d007266e0bd8e6116b306ccd9e24c9710411) Thanks [@kevinzunigacuellar](https://github.com/kevinzunigacuellar)! - Refactor `getLastUpdated` to use `node:child_process` instead of `execa`.

- [#1353](https://github.com/withastro/starlight/pull/1353) [`90fe8da`](https://github.com/withastro/starlight/commit/90fe8da15c8eb227817c2232345ac359aef6bab5) Thanks [@delucis](https://github.com/delucis)! - Fixes sidebar scrollbar hiding behind navbar

## 0.15.2

### Patch Changes

- [#1254](https://github.com/withastro/starlight/pull/1254) [`e9659e8`](https://github.com/withastro/starlight/commit/e9659e869cd0c9ad0b7388397b0fff8e2a9db27a) Thanks [@Pukimaa](https://github.com/Pukimaa)! - Adds Open Collective social link icon

- [#1295](https://github.com/withastro/starlight/pull/1295) [`c3732a9`](https://github.com/withastro/starlight/commit/c3732a9bb5cb7907f00a3ed5e65534f48a5ff6b9) Thanks [@juchym](https://github.com/juchym)! - Improve Ukrainian UI translations

## 0.15.1

### Patch Changes

- [#1273](https://github.com/withastro/starlight/pull/1273) [`ae53155`](https://github.com/withastro/starlight/commit/ae531557aa4d42bd27c15f8f08bb3ca8242c9beb) Thanks [@natemoo-re](https://github.com/natemoo-re)! - Updates `<SocialIcon />` styling for improved accessibility. Specifically, the component now meets the [Target Size (Minimum)](https://www.w3.org/WAI/WCAG22/Understanding/target-size-minimum.html) success criteria defined by [Web Content Accessibility Guidelines (WCAG) 2.2](https://www.w3.org/TR/WCAG22/).

- [#1289](https://github.com/withastro/starlight/pull/1289) [`9bd343f`](https://github.com/withastro/starlight/commit/9bd343fb1efab90a0aa03a95b1928a53c1674000) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds French translations for Expressive Code UI

- [#1280](https://github.com/withastro/starlight/pull/1280) [`6b1693d`](https://github.com/withastro/starlight/commit/6b1693d55552a48316a31d986e1cbaf695f10a61) Thanks [@kevinzunigacuellar](https://github.com/kevinzunigacuellar)! - Adds Spanish translations for Expressive Code UI

- [#1276](https://github.com/withastro/starlight/pull/1276) [`667f23d`](https://github.com/withastro/starlight/commit/667f23d615742b44bb18ace39d981f8797b8ac55) Thanks [@hippotastic](https://github.com/hippotastic)! - Updates `astro-expressive-code` dependency to the latest version

- [#1266](https://github.com/withastro/starlight/pull/1266) [`c9edf30`](https://github.com/withastro/starlight/commit/c9edf30b16f66757797dcaa5161b4afc18027476) Thanks [@alex-way](https://github.com/alex-way)! - Removes redundant subprocess calls in git last-updated time utility to improve performance

- [#1278](https://github.com/withastro/starlight/pull/1278) [`e88abb0`](https://github.com/withastro/starlight/commit/e88abb0cc8b329500c15bc77aaed3907ec7dc507) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Exports the `StarlightUserConfig` TypeScript type representing the user's Starlight configuration received by plugins.

## 0.15.0

### Minor Changes

- [#1238](https://github.com/withastro/starlight/pull/1238) [`02a808e`](https://github.com/withastro/starlight/commit/02a808e4a0b9ac2383576e3495f6a766b663d773) Thanks [@delucis](https://github.com/delucis)! - Add support for Astro v4, drop support for Astro v3

  ⚠️ **BREAKING CHANGE** Astro v3 is no longer supported. Make sure you [update Astro](https://docs.astro.build/en/guides/upgrade-to/v4/) and any other integrations at the same time as updating Starlight.

  Use the new `@astrojs/upgrade` command to upgrade Astro and Starlight together:

  ```sh
  npx @astrojs/upgrade
  ```

- [#1242](https://github.com/withastro/starlight/pull/1242) [`d8fc9e1`](https://github.com/withastro/starlight/commit/d8fc9e15bd2ae4c945b5a3856a6ce3b5629e8b29) Thanks [@delucis](https://github.com/delucis)! - Enables link prefetching on hover by default

  Astro v4’s [prefetch](https://docs.astro.build/en/guides/prefetch) support is now enabled by default. If `prefetch` is not set in `astro.config.mjs`, Starlight will use `prefetch: { prefetchAll: true, defaultStrategy: 'hover' }` by default.

  If you want to preserve previous behaviour, disable link prefetching in `astro.config.mjs`:

  ```js
  import { defineConfig } from 'astro/config';
  import starlight from '@astrojs/starlight';

  export default defineConfig({
    // Disable link prefetching:
    prefetch: false,

    integrations: [
      starlight({
        // ...
      }),
    ],
  });
  ```

### Patch Changes

- [#1226](https://github.com/withastro/starlight/pull/1226) [`909afa2`](https://github.com/withastro/starlight/commit/909afa2d468099e237bfbd25eda56270b7b00082) Thanks [@tlandmangh](https://github.com/tlandmangh)! - Add Dutch translations of default aside labels

- [#1243](https://github.com/withastro/starlight/pull/1243) [`ee234eb`](https://github.com/withastro/starlight/commit/ee234ebddcba8d07e2c879f33e38631c8955ffcf) Thanks [@khajimatov](https://github.com/khajimatov)! - Fix typo in Russian untranslated content notice

- [#1170](https://github.com/withastro/starlight/pull/1170) [`bcc2301`](https://github.com/withastro/starlight/commit/bcc2301c06796edec3923c666078e82eaf5a1990) Thanks [@tmcw](https://github.com/tmcw)! - Fix timezone-reliance in LastUpdated

- [#1203](https://github.com/withastro/starlight/pull/1203) [`4601449`](https://github.com/withastro/starlight/commit/4601449894bbbd619e4149788113090b67697fe1) Thanks [@orhun](https://github.com/orhun)! - Adds Matrix social link icon

## 0.14.0

### Minor Changes

- [#1144](https://github.com/withastro/starlight/pull/1144) [`7c0b8cb`](https://github.com/withastro/starlight/commit/7c0b8cb334c501678f7ab87cce372cddfdde34ed) Thanks [@delucis](https://github.com/delucis)! - Adds a configuration option to disable site indexing with Pagefind and the default search UI

- [#942](https://github.com/withastro/starlight/pull/942) [`efd7fdc`](https://github.com/withastro/starlight/commit/efd7fdcb55b39988f157c1a4b2c368c86a39520f) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Adds plugin API

  See the [plugins reference](https://starlight.astro.build/reference/plugins/) to learn more about creating plugins for Starlight using this new API.

- [#1135](https://github.com/withastro/starlight/pull/1135) [`e5a863a`](https://github.com/withastro/starlight/commit/e5a863a98b2e5335e122ca440dcb84e9426939b4) Thanks [@delucis](https://github.com/delucis)! - Exposes localized UI strings in route data

  Component overrides can now access a `labels` object in their props which includes all the localized UI strings for the current page.

- [#1162](https://github.com/withastro/starlight/pull/1162) [`00d101b`](https://github.com/withastro/starlight/commit/00d101b159bfa4bb307a66ccae53dd417d9564e0) Thanks [@delucis](https://github.com/delucis)! - Adds support for extending Starlight’s content collection schemas

## 0.13.1

### Patch Changes

- [#1111](https://github.com/withastro/starlight/pull/1111) [`cb19d07`](https://github.com/withastro/starlight/commit/cb19d07d6192ffb732ac6fcf9df04d4f098bfc1f) Thanks [@at-the-vr](https://github.com/at-the-vr)! - Fix minor punctuation typo in Hindi UI string

- [#1156](https://github.com/withastro/starlight/pull/1156) [`631c5ae`](https://github.com/withastro/starlight/commit/631c5aeccba60254ff649712f93ba30495775edf) Thanks [@votemike](https://github.com/votemike)! - Updates `@astrojs/sitemap` dependency to the latest version

- [#1109](https://github.com/withastro/starlight/pull/1109) [`0c25c1f`](https://github.com/withastro/starlight/commit/0c25c1f33bbfe311724784530c30ada44eb5de19) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Internal: fix import issue with expressive-code

## 0.13.0

### Minor Changes

- [#1023](https://github.com/withastro/starlight/pull/1023) [`a3b80f7`](https://github.com/withastro/starlight/commit/a3b80f71037504f2b8d7f1a641924215091122bb) Thanks [@kevinzunigacuellar](https://github.com/kevinzunigacuellar)! - Respect the `trailingSlash` and `build.format` Astro options when creating Starlight navigation links.

  ⚠️ **Potentially breaking change:**
  This change will cause small changes in link formatting for most sites.
  These are unlikely to break anything, but if you care about link formatting, you may want to change some Astro settings.

  If you want to preserve Starlight’s previous behavior, set `trailingSlash: 'always'` in your `astro.config.mjs`:

  ```js
  import { defineConfig } from 'astro/config';
  import starlight from '@astrojs/starlight';

  export default defineConfig({
    trailingSlash: 'always',
    integrations: [
      starlight({
        // ...
      }),
    ],
  });
  ```

- [#742](https://github.com/withastro/starlight/pull/742) [`c6a4bcb`](https://github.com/withastro/starlight/commit/c6a4bcb7982c54c513f20c96a9b2aaf9ac09094b) Thanks [@hippotastic](https://github.com/hippotastic)! - Adds Expressive Code as Starlight’s default code block renderer

  ⚠️ **Potentially breaking change:**
  This addition changes how Markdown code blocks are rendered. By default, Starlight will now use [Expressive Code](https://github.com/expressive-code/expressive-code/tree/main/packages/astro-expressive-code).
  If you were already customizing how code blocks are rendered and don't want to use the [features provided by Expressive Code](https://starlight.astro.build/guides/authoring-content/#expressive-code-features), you can preserve the previous behavior by setting the new config option `expressiveCode` to `false`.

  If you had previously added Expressive Code manually to your Starlight project, you can now remove the manual set-up in `astro.config.mjs`:

  - Move your configuration to Starlight’s new `expressiveCode` option.
  - Remove the `astro-expressive-code` integration.

  For example:

  ```diff
  import starlight from '@astrojs/starlight';
  import { defineConfig } from 'astro/config';
  - import expressiveCode from 'astro-expressive-code';

  export default defineConfig({
    integrations: [
  -   expressiveCode({
  -     themes: ['rose-pine'],
  -   }),
      starlight({
        title: 'My docs',
  +     expressiveCode: {
  +       themes: ['rose-pine'],
  +     },
      }),
    ],
  });
  ```

  Note that the built-in Starlight version of Expressive Code sets some opinionated defaults that are different from the `astro-expressive-code` defaults. You may need to set some `styleOverrides` if you wish to keep styles exactly the same.

- [#517](https://github.com/withastro/starlight/pull/517) [`5b549cb`](https://github.com/withastro/starlight/commit/5b549cb634f51d28bf9a7f92ad0d82c1671e788a) Thanks [@liruifengv](https://github.com/liruifengv)! - Add i18n support for default aside labels

### Patch Changes

- [#1088](https://github.com/withastro/starlight/pull/1088) [`4fe5537`](https://github.com/withastro/starlight/commit/4fe553749a6708fdb119b12a2dbc6b10a980bde1) Thanks [@Lootjs](https://github.com/Lootjs)! - i18n(ru): added Russian aside labels translation

- [#1083](https://github.com/withastro/starlight/pull/1083) [`e03a653`](https://github.com/withastro/starlight/commit/e03a65313365b7dbe6095727b28b4e639c446f68) Thanks [@at-the-vr](https://github.com/at-the-vr)! - i18n(hi): Add Hindi language support

- [#1075](https://github.com/withastro/starlight/pull/1075) [`2f2adf2`](https://github.com/withastro/starlight/commit/2f2adf29f2a13d5ff0f1577207210745a5ae7405) Thanks [@russbiggs](https://github.com/russbiggs)! - Add Slack social link icon

- [#1065](https://github.com/withastro/starlight/pull/1065) [`2d72ed6`](https://github.com/withastro/starlight/commit/2d72ed67c666b26eae44649e70aecef3db815d19) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Ignore search keyboard shortcuts for elements with contents that are editable

- [#1081](https://github.com/withastro/starlight/pull/1081) [`f27f781`](https://github.com/withastro/starlight/commit/f27f781556d37e73d0b1d902de745b67f8e4f24d) Thanks [@farisphp](https://github.com/farisphp)! - i18n(id): Add Indonesian aside labels translation

- [#1082](https://github.com/withastro/starlight/pull/1082) [`ce27486`](https://github.com/withastro/starlight/commit/ce27486fabd3884ed4bca9372ebd72a0597ab765) Thanks [@bogdaaamn](https://github.com/bogdaaamn)! - i18n(ro): Add Romanian UI translations

## 0.12.1

### Patch Changes

- [#1069](https://github.com/withastro/starlight/pull/1069) [`b86f360`](https://github.com/withastro/starlight/commit/b86f3608f03be9455ec1d5ba11820c9bf601ad1e) Thanks [@Genteure](https://github.com/Genteure)! - Fix sidebar highlighting and navigation buttons for pages with path containing non-ASCII characters

- [#1025](https://github.com/withastro/starlight/pull/1025) [`0d1e75e`](https://github.com/withastro/starlight/commit/0d1e75e17269ddac3eb15b7dfb4480da1bb01c6c) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Internal: fix import issue in translation string loading mechanism

- [#1044](https://github.com/withastro/starlight/pull/1044) [`a5a9754`](https://github.com/withastro/starlight/commit/a5a9754f111b97abfd277d99759e9857aa0fb22b) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fix last updated dates for pages displaying fallback content

- [#1049](https://github.com/withastro/starlight/pull/1049) [`c27495d`](https://github.com/withastro/starlight/commit/c27495da61f9376236519ed3f08a169f245a189c) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Expose Markdown content styles in `@astrojs/starlight/style/markdown.css`

## 0.12.0

### Minor Changes

- [#995](https://github.com/withastro/starlight/pull/995) [`5bf4457`](https://github.com/withastro/starlight/commit/5bf44577634935b9fa6d50b040abcd680035075f) Thanks [@kevinzunigacuellar](https://github.com/kevinzunigacuellar)! - Adds support for adding sidebar badges to group headings

- [#988](https://github.com/withastro/starlight/pull/988) [`977fe13`](https://github.com/withastro/starlight/commit/977fe135a74661300589898abe98aec73cad9ed3) Thanks [@magicDGS](https://github.com/magicDGS)! - Include social icon links in mobile menu

- [#280](https://github.com/withastro/starlight/pull/280) [`72cca2d`](https://github.com/withastro/starlight/commit/72cca2d07644f00595da6ebf7d603adb282f359d) Thanks [@cbontems](https://github.com/cbontems)! - Support light & dark variants of the hero image.

  ⚠️ **Potentially breaking change:** The `hero.image` schema is now slightly stricter than previously.

  The `hero.image.html` property can no longer be used alongside the `hero.image.alt` or `hero.image.file` properties.
  Previously, `html` was ignored when used with `file` and `alt` was ignored when used with `html`.
  Now, those combinations will throw errors.
  If you encounter errors, remove the `image.hero` property that is not in use.

### Patch Changes

- [#1004](https://github.com/withastro/starlight/pull/1004) [`7f92213`](https://github.com/withastro/starlight/commit/7f92213a0b93de5a844816841a6bc9cdd371de0c) Thanks [@nunhes](https://github.com/nunhes)! - Add Galician language support

- [#1003](https://github.com/withastro/starlight/pull/1003) [`f1fdb50`](https://github.com/withastro/starlight/commit/f1fdb50daebe79548c7789d3f7dd968b261d2da7) Thanks [@delucis](https://github.com/delucis)! - Internal: refactor translation string loading to make translations available to Starlight integration code

## 0.11.2

### Patch Changes

- [#944](https://github.com/withastro/starlight/pull/944) [`7a6446e`](https://github.com/withastro/starlight/commit/7a6446ebc61ba9cc36d1dcfd13db15c1533751ab) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Fix issue with sidebar autogenerated groups configured with a directory containing leading or trailing slash

- [#985](https://github.com/withastro/starlight/pull/985) [`92b3b57`](https://github.com/withastro/starlight/commit/92b3b575404d0dc34f720c0ba29d8ed50be98f58) Thanks [@delucis](https://github.com/delucis)! - Fix edit URLs for pages displaying fallback content

- [#986](https://github.com/withastro/starlight/pull/986) [`0470734`](https://github.com/withastro/starlight/commit/0470734e0dc323f9945e06bee4338c2f777ba0d6) Thanks [@dreyfus92](https://github.com/dreyfus92)! - Prevent overscrolling on mobile table of contents by setting 'overscroll-behavior: contain'.

- [#924](https://github.com/withastro/starlight/pull/924) [`39d6302`](https://github.com/withastro/starlight/commit/39d6302db42ee1105d690bbd3a66053e6b21e15a) Thanks [@kevinzunigacuellar](https://github.com/kevinzunigacuellar)! - Remove extra margin from markdown lists that uses inline code

- [#814](https://github.com/withastro/starlight/pull/814) [`1e517d9`](https://github.com/withastro/starlight/commit/1e517d92a4cf146d2dcae58f7c4299d6f25ea73e) Thanks [@julien-deramond](https://github.com/julien-deramond)! - Prevent text from overflowing pagination items

## 0.11.1

### Patch Changes

- [#892](https://github.com/withastro/starlight/pull/892) [`2b30321`](https://github.com/withastro/starlight/commit/2b30321bde801bb9945d73dc954e25b40f4324fa) Thanks [@delucis](https://github.com/delucis)! - Add Patreon social link icon

- [#854](https://github.com/withastro/starlight/pull/854) [`71a52a1`](https://github.com/withastro/starlight/commit/71a52a16c44e3568128c83070541235133c44436) Thanks [@mehalter](https://github.com/mehalter)! - Add Reddit icon

- [#852](https://github.com/withastro/starlight/pull/852) [`344c92e`](https://github.com/withastro/starlight/commit/344c92e1b8bca5f92ec087df6cccf5c611eefdff) Thanks [@Lootjs](https://github.com/Lootjs)! - Improve Russian language support

- [#891](https://github.com/withastro/starlight/pull/891) [`395920c`](https://github.com/withastro/starlight/commit/395920c46e7b24cfff31800b3426ab375078e5c1) Thanks [@Frikadellios](https://github.com/Frikadellios)! - Add Ukrainian language support

- [#890](https://github.com/withastro/starlight/pull/890) [`63ea8e8`](https://github.com/withastro/starlight/commit/63ea8e86643b050c6be6f9a6167f6642b039c709) Thanks [@delucis](https://github.com/delucis)! - Update `execa` dependency to v8

- [#859](https://github.com/withastro/starlight/pull/859) [`eaa7a90`](https://github.com/withastro/starlight/commit/eaa7a902c7b7638b326709fd5203d932b20ed3fa) Thanks [@oggnimodd](https://github.com/oggnimodd)! - Improve Indonesian language support

- [#864](https://github.com/withastro/starlight/pull/864) [`b84aff2`](https://github.com/withastro/starlight/commit/b84aff2b9cccbc35c8619763c7f36841abe6344b) Thanks [@mehalter](https://github.com/mehalter)! - Optimize UI icon SVG paths

## 0.11.0

### Minor Changes

- [#774](https://github.com/withastro/starlight/pull/774) [`903a579`](https://github.com/withastro/starlight/commit/903a57942ceb99b68672c3fa54622b39cc5d76f8) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Support adding HTML attributes to sidebar links from config and frontmatter

- [#796](https://github.com/withastro/starlight/pull/796) [`372ec96`](https://github.com/withastro/starlight/commit/372ec96d31d0c1a9aa8bc1605de2b424bf9bd5af) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Add the `@astrojs/sitemap` and `@astrojs/mdx` integrations only if they are not detected in the Astro configuration.

  ⚠️ **BREAKING CHANGE** The minimum supported version of Astro is now v3.2.0. Make sure you update Astro at the same time as updating Starlight:

  ```sh
  npm install astro@latest
  ```

- [#447](https://github.com/withastro/starlight/pull/447) [`b45719b`](https://github.com/withastro/starlight/commit/b45719b581353f8d8f0ce0a9b5c89132e902377b) Thanks [@andremralves](https://github.com/andremralves)! - Add `titleDelimiter` configuration option and include site title in page `<title>` tags

  ⚠️ **BREAKING CHANGE** — Previously, every page’s `<title>` only included its individual frontmatter title.
  Now, `<title>` tags include the page title, a delimiter character (`|` by default), and the site title.
  For example, in the Startlight docs, `<title>Configuration Reference` is now `Configuration Reference | Starlight`.

  If you have a page where you need to override this new behaviour, set a custom title using the `head` frontmatter property:

  ```md
  ---
  title: My Page
  head:
    - tag: title
      content: Custom Title
  ---
  ```

- [#709](https://github.com/withastro/starlight/pull/709) [`140e729`](https://github.com/withastro/starlight/commit/140e729a8bf12f805ae0b7e2b5ad959cf68d8e22) Thanks [@delucis](https://github.com/delucis)! - Add support for overriding Starlight’s built-in components

  ⚠️ **BREAKING CHANGE** — The page footer is now included on pages with `template: splash` in their frontmatter. Previously, this was not the case. If you are using `template: splash` and want to continue to hide footer elements, disable them in your frontmatter:

  ```md
  ---
  title: Landing page
  template: splash
  # Disable unwanted footer elements as needed
  editUrl: false
  lastUpdated: false
  prev: false
  next: false
  ---
  ```

  ⚠️ **BREAKING CHANGE** — This change involved refactoring the structure of some of Starlight’s built-in components slightly. If you were previously overriding these using other techniques, you may need to adjust your code.

### Patch Changes

- [#815](https://github.com/withastro/starlight/pull/815) [`b7b23a2`](https://github.com/withastro/starlight/commit/b7b23a2c90a25fe8ea08338379b83d19c74d9037) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Add Facebook and email icons

- [#810](https://github.com/withastro/starlight/pull/810) [`dbe977b`](https://github.com/withastro/starlight/commit/dbe977b6ce3efcffefab850eca08bef316b41e53) Thanks [@hasham-qaiser](https://github.com/hasham-qaiser)! - Use `` instead of `

` in sidebar group headings - [#807](https://github.com/withastro/starlight/pull/807) [`7c73dd1`](https://github.com/withastro/starlight/commit/7c73dd146ee294f9092346a0b0041990cc648a13) Thanks [@torn4dom4n](https://github.com/torn4dom4n)! - Add Vietnamese translations for Starlight UI - [#756](https://github.com/withastro/starlight/pull/756) [`f55a8f0`](https://github.com/withastro/starlight/commit/f55a8f014a7addc46e971dd6b7148f4545acd16c) Thanks [@julien-deramond](https://github.com/julien-deramond)! - Prevent text from overflowing in several cases ## 0.10.4 ### Patch Changes - [#752](https://github.com/withastro/starlight/pull/752) [`6833ee1`](https://github.com/withastro/starlight/commit/6833ee12159ea5be23885c41da80569a89aafa33) Thanks [@apinet](https://github.com/apinet)! - Add X social link logo - [#789](https://github.com/withastro/starlight/pull/789) [`2528fb0`](https://github.com/withastro/starlight/commit/2528fb011a388f3920af9994012bd7db2b1654c3) Thanks [@delucis](https://github.com/delucis)! - Update bundled version of `@astrojs/mdx` to v1.1.0 - [#794](https://github.com/withastro/starlight/pull/794) [`a0de12d`](https://github.com/withastro/starlight/commit/a0de12d596ab2b1c0d79d6d63d2d6cb9fe6d2644) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Add Telegram icon - [#792](https://github.com/withastro/starlight/pull/792) [`a8358df`](https://github.com/withastro/starlight/commit/a8358df7849b342de342a4a2e88e019c39d5bbe8) Thanks [@HiDeoo](https://github.com/HiDeoo)! - Add RSS icon - [#778](https://github.com/withastro/starlight/pull/778) [`957d2c3`](https://github.com/withastro/starlight/commit/957d2c32123ab0c223fcef03f91ce3ad7be7aa21) Thanks [@jermanuts](https://github.com/jermanuts)! - Improve Arabic UI translations ## 0.10.3 ### Patch Changes - [#783](https://github.com/withastro/starlight/pull/783) [`f94727e`](https://github.com/withastro/starlight/commit/f94727e7d286a6910f913a572b27eb17c42f1729) Thanks [@kevinzunigacuellar](https://github.com/kevinzunigacuellar)! - Fix GitHub edit link to include src path from project config - [#781](https://github.com/withastro/starlight/pull/781) [`a293ef9`](https://github.com/withastro/starlight/commit/a293ef9ebb10a07db456156d8bdacc4ff6a2ca38) Thanks [@dreyfus92](https://github.com/dreyfus92)! - Removed role from Banner component to avoid duplication in header. - [#745](https://github.com/withastro/starlight/pull/745) [`006d606`](https://github.com/withastro/starlight/commit/006d60695761ec10e5c4e715ed2212cd1fbedda0) Thanks [@TheOtterlord](https://github.com/TheOtterlord)! - Prevent Starlight crashing when the content folder doesn't exist, or is empty - [#775](https://github.com/withastro/starlight/pull/775) [`2ef3036`](https://github.com/withastro/starlight/commit/2ef303649a0b66a6ec6a216815e05d41bf22b594) Thanks [@delucis](https://github.com/delucis)! - Fix content collection schema compatibility with Astro 3.1 and higher - [#773](https://github.com/withastro/starlight/pull/773) [`423d575`](https://github.com/withastro/starlight/commit/423d575cc8227e4db86a85c70c45c0f3f7a184d2) Thanks [@tlandmangh](https://github.com/tlandmangh)! - Fix Dutch UI translation for “Previous page” links ## 0.10.2 ### Patch Changes - [#735](https://github.com/withastro/starlight/pull/735) [`2da8692`](https://github.com/withastro/starlight/commit/2da86929c8041f6585790c3baf1cba42220650cc) Thanks [@delucis](https://github.com/delucis)! - Use Starlight font custom property in Pagefind modal - [#735](https://github.com/withastro/starlight/pull/735) [`2da8692`](https://github.com/withastro/starlight/commit/2da86929c8041f6585790c3baf1cba42220650cc) Thanks [@delucis](https://github.com/delucis)! - Fix RTL styling in Pagefind modal - [#739](https://github.com/withastro/starlight/pull/739) [`a9de4a7`](https://github.com/withastro/starlight/commit/a9de4a7dcf9ec8c5c801e8a6cbb0d7faf2c34db7) Thanks [@radenpioneer](https://github.com/radenpioneer)! - Add Indonesian UI translation - [#747](https://github.com/withastro/starlight/pull/747) [`7589515`](https://github.com/withastro/starlight/commit/75895154b11cf9368d4d6b45647b156ce32a88f0) Thanks [@nirtamir2](https://github.com/nirtamir2)! - Add Hebrew UI translations ## 0.10.1 ### Patch Changes - [#726](https://github.com/withastro/starlight/pull/726) [`f3157c6`](https://github.com/withastro/starlight/commit/f3157c6065943af39995b6dbae5f63cf424bd9a3) Thanks [@delucis](https://github.com/delucis)! - Fix a rare bug in table of contents when handling headings that increase by more than one level on a page. - [#729](https://github.com/withastro/starlight/pull/729) [`80c6ab1`](https://github.com/withastro/starlight/commit/80c6ab1c1ec48805e74c53b615a78d65127eeacb) Thanks [@delucis](https://github.com/delucis)! - Upgrade Pagefind to v1.0.3 - [#715](https://github.com/withastro/starlight/pull/715) [`e726155`](https://github.com/withastro/starlight/commit/e7261559f2539a0ceefd36a28e4fbbc17f5970b8) Thanks [@itsmatteomanf](https://github.com/itsmatteomanf)! - feat: prevent scroll on body when search is open ## 0.10.0 ### Minor Changes - [#692](https://github.com/withastro/starlight/pull/692) [`2a58e1a`](https://github.com/withastro/starlight/commit/2a58e1aa068d01833a0ab9e74e4b46cccaee1775) Thanks [@delucis](https://github.com/delucis)! - Upgrade Pagefind to v1 and display page headings in search results ### Patch Changes - [#708](https://github.com/withastro/starlight/pull/708) [`136cfb1`](https://github.com/withastro/starlight/commit/136cfb180f22db116cfdb62fd93d21daff596946) Thanks [@julien-deramond](https://github.com/julien-deramond)! - Fix main content column width for pages without a table of contents - [#682](https://github.com/withastro/starlight/pull/682) [`660a5f5`](https://github.com/withastro/starlight/commit/660a5f57adf0340de21df3e364aada38255bb06c) Thanks [@vedmalex](https://github.com/vedmalex)! - Add Russian language support ## 0.9.1 ### Patch Changes - [#647](https://github.com/withastro/starlight/pull/647) [`ea57726`](https://github.com/withastro/starlight/commit/ea5772655274a3900310cb700836fdd2f6dba7cd) Thanks [@bgmort](https://github.com/bgmort)! - Fix translated 404 pages not being excluded from search results - [#667](https://github.com/withastro/starlight/pull/667) [`9828f73`](https://github.com/withastro/starlight/commit/9828f739b73e2f377c1450b9e11f0914722ee440) Thanks [@delucis](https://github.com/delucis)! - Break inline `` across lines to avoid overflow - [#642](https://github.com/withastro/starlight/pull/642) [`e623d92`](https://github.com/withastro/starlight/commit/e623d92c2fddc0ff5fe83d2554266885d683a906) Thanks [@fk](https://github.com/fk)! - Don't hard-code nav height in table of contents highlighting script - [#676](https://github.com/withastro/starlight/pull/676) [`6419006`](https://github.com/withastro/starlight/commit/641900615aa9a9a128d6934e65a57ba89e503cfd) Thanks [@vedmalex](https://github.com/vedmalex)! - Upgrade and pin Pagefind to latest beta release. - [#647](https://github.com/withastro/starlight/pull/647) [`ea57726`](https://github.com/withastro/starlight/commit/ea5772655274a3900310cb700836fdd2f6dba7cd) Thanks [@bgmort](https://github.com/bgmort)! - Add frontmatter option to exclude a page from Pagefind search results ## 0.9.0 ### Minor Changes - [#626](https://github.com/withastro/starlight/pull/626) [`5dd22b8`](https://github.com/withastro/starlight/commit/5dd22b875dc19a32c48692082fbd934e2b70da63) Thanks [@delucis](https://github.com/delucis)! - Throw an error for duplicate MDX or sitemap integrations - [#615](https://github.com/withastro/starlight/pull/615) [`7b75b3e`](https://github.com/withastro/starlight/commit/7b75b3eb7e6f7870a0adef2d6534ff48309fdb0e) Thanks [@delucis](https://github.com/delucis)! - Bump minimum required Astro version to 3.0 ⚠️ **BREAKING CHANGE** Astro v2 is no longer supported. Make sure you [update Astro](https://docs.astro.build/en/guides/upgrade-to/v3/) and any other integrations at the same time as updating Starlight. ## 0.8.1 ### Patch Changes - [#612](https://github.com/withastro/starlight/pull/612) [`1b367e3`](https://github.com/withastro/starlight/commit/1b367e3f65e3736b5f91c9853a487f7f5d174a6f) Thanks [@KubaJastrz](https://github.com/KubaJastrz)! - Avoid applying hovered `

`, }), ].join(''); const { html } = processPanels(input); expect(html).toMatchInlineSnapshot( `""` ); const tabPanels = extractTabPanels(html); expect(tabPanels[0]).not.includes('tabindex="0"'); expect(tabPanels[1]).includes('tabindex="0"'); expect(tabPanels[2]).not.includes('tabindex="0"'); }); test('processes a tab item icon', () => { const icon = 'star'; const input = TabItem({ label: 'Test', slot: '

Random paragraph

', icon }); const { panels, html } = processPanels(input); expect(html).toMatchInlineSnapshot( `"

Random paragraph

"` ); expect(panels).toHaveLength(1); expect(panels?.[0]?.icon).toBe(icon); }); ================================================ FILE: packages/starlight/__tests__/remark-rehype/remark-rehype.test.ts ================================================ import { createMarkdownProcessor } from '@astrojs/markdown-remark'; import { expect, test } from 'vitest'; import { starlightRehypePlugins, starlightRemarkPlugins } from '../../integrations/remark-rehype'; import { createRemarkRehypePluginTestOptions } from './utils'; test('does not run Starlight remark plugins on documents without a file path', async () => { const processor = await createMarkdownProcessor({ remarkPlugins: [...starlightRemarkPlugins(await createRemarkRehypePluginTestOptions())], }); const res = await processor.render( ` :::note Some text ::: `, // Rendering Markdown content using the content loader `renderMarkdown()` API does not provide // a `fileURL` option. {} ); // Asides directives should not be processed. expect(res.code).not.includes(`aside`); expect(res.code).not.includes(`Note

`); }); test('does not run Starlight rehype plugins on documents without a file path', async () => { const processor = await createMarkdownProcessor({ rehypePlugins: [...starlightRehypePlugins(await createRemarkRehypePluginTestOptions())], }); const res = await processor.render( ` ## Some heading And \`some\` inline code. `, // Rendering Markdown content using the content loader `renderMarkdown()` API does not provide // a `fileURL` option. {} ); // Heading anchor links should not be added. expect(res.code).not.includes('Section titled'); // Code elements should not be processed for RTL support. expect(res.code).not.includes(''); }); ================================================ FILE: packages/starlight/__tests__/remark-rehype/snapshots/file-tree-basic.html ================================================
  • root_file
  • Directoryroot_directory/
    • nested_file
================================================ FILE: packages/starlight/__tests__/remark-rehype/snapshots/file-tree-comment-nodes.html ================================================
  • file this is an important comment
================================================ FILE: packages/starlight/__tests__/remark-rehype/snapshots/file-tree-comment-text.html ================================================
  • file this is a comment
================================================ FILE: packages/starlight/__tests__/remark-rehype/snapshots/generates-anchor-link-markup.html ================================================ ================================================ FILE: packages/starlight/__tests__/remark-rehype/snapshots/generates-aside-caution-custom-icon.html ================================================ ================================================ FILE: packages/starlight/__tests__/remark-rehype/snapshots/generates-aside-caution-custom-label-and-icon.html ================================================ ================================================ FILE: packages/starlight/__tests__/remark-rehype/snapshots/generates-aside-danger-custom-icon.html ================================================ ================================================ FILE: packages/starlight/__tests__/remark-rehype/snapshots/generates-aside-danger-custom-label-and-icon.html ================================================ ================================================ FILE: packages/starlight/__tests__/remark-rehype/snapshots/generates-aside-note-custom-icon.html ================================================ ================================================ FILE: packages/starlight/__tests__/remark-rehype/snapshots/generates-aside-note-custom-label-and-icon.html ================================================ ================================================ FILE: packages/starlight/__tests__/remark-rehype/snapshots/generates-aside-note-multiple-path-custom-icon.html ================================================ ================================================ FILE: packages/starlight/__tests__/remark-rehype/snapshots/generates-aside-tip-custom-icon.html ================================================ ================================================ FILE: packages/starlight/__tests__/remark-rehype/snapshots/generates-aside-tip-custom-label-and-icon.html ================================================ ================================================ FILE: packages/starlight/__tests__/remark-rehype/snapshots/generates-aside.html ================================================ ================================================ FILE: packages/starlight/__tests__/remark-rehype/snapshots/handles-complex-children.html ================================================ ================================================ FILE: packages/starlight/__tests__/remark-rehype/snapshots/nested-asides-custom-titles.html ================================================ ================================================ FILE: packages/starlight/__tests__/remark-rehype/snapshots/nested-asides.html ================================================ ================================================ FILE: packages/starlight/__tests__/remark-rehype/utils.ts ================================================ import type { StarlightUserConfig } from '../../types'; import { StarlightConfigSchema } from '../../utils/user-config'; import type { RemarkRehypePluginOptions } from '../../integrations/remark-rehype'; import { createTranslationSystemFromFs } from '../../utils/translations-fs'; import { absolutePathToLang } from '../../integrations/shared/absolutePathToLang'; import { getCollectionPosixPath } from '../../utils/collection-fs'; /** Returns options for the Starlight remark-rehype plugins to be used in tests. */ export async function createRemarkRehypePluginTestOptions( starlightUserConfig?: StarlightUserConfig ): Promise { const starlightConfig = StarlightConfigSchema.parse( starlightUserConfig ?? { title: 'Remark-Rehype Tests' } ); const astroConfig = { root: new URL(import.meta.url), srcDir: new URL('./_src/', import.meta.url), }; return { starlightConfig, astroConfig, useTranslations: await createTranslationSystemFromFs( starlightConfig, // Using non-existent `_src/` to ignore custom files in test fixtures. { srcDir: astroConfig.srcDir } ), absolutePathToLang: (path: string) => absolutePathToLang(path, { docsPath: getCollectionPosixPath('docs', astroConfig.srcDir), starlightConfig, }), }; } ================================================ FILE: packages/starlight/__tests__/remark-rehype/vitest.config.ts ================================================ import { defineVitestConfig } from '../test-config'; export default defineVitestConfig({ title: 'Remark-Rehype' }); ================================================ FILE: packages/starlight/__tests__/sidebar/navigation-attributes.test.ts ================================================ import { describe, expect, test, vi } from 'vitest'; import { getSidebar } from '../../utils/navigation'; vi.mock('astro:content', async () => (await import('../test-utils')).mockedAstroContent({ docs: [ ['index.mdx', { title: 'Home Page' }], ['environmental-impact.md', { title: 'Eco-friendly docs' }], ['resources/plugins.mdx', { title: 'Plugins' }], ['resources/themes.mdx', { title: 'Themes' }], [ 'reference/frontmatter.md', { title: 'Frontmatter Reference', sidebar: { attrs: { class: 'advanced', ping: 'https://example.com' } }, }, ], // Links to pages in the `api/v1/` directory have custom attributes, even nested ones. ['api/v1/users.md', { title: 'Users API' }], ['api/v1/products/add.md', { title: 'Add Product' }], [ 'api/v1/products/remove.md', // A page in the `api/v1/` directory can specify custom attributes to be merged with the // default ones. { title: 'Remove Product', sidebar: { attrs: { 'data-experimental': true } }, }, ], ['Deprecated API/users.md', { title: 'Deprecated Users API' }], ], }) ); describe('getSidebar', () => { test('passes down custom HTML link attributes', () => { expect(getSidebar('/', undefined)).toMatchInlineSnapshot(` [ { "attrs": {}, "badge": undefined, "href": "/", "isCurrent": true, "label": "Home", "type": "link", }, { "badge": undefined, "collapsed": false, "entries": [ { "attrs": {}, "badge": { "text": "New", "variant": "success", }, "href": "/intro", "isCurrent": false, "label": "Introduction", "type": "link", }, { "attrs": {}, "badge": { "text": "Deprecated", "variant": "default", }, "href": "/next-steps", "isCurrent": false, "label": "Next Steps", "type": "link", }, { "attrs": { "class": "showcase-link", "target": "_blank", }, "badge": undefined, "href": "/showcase", "isCurrent": false, "label": "Showcase", "type": "link", }, ], "label": "Start Here", "type": "group", }, { "badge": undefined, "collapsed": false, "entries": [ { "attrs": {}, "badge": undefined, "href": "/resources/plugins/", "isCurrent": false, "label": "Plugins", "type": "link", }, { "attrs": {}, "badge": undefined, "href": "/resources/themes/", "isCurrent": false, "label": "Themes", "type": "link", }, ], "label": "Resources", "type": "group", }, { "badge": { "text": "Experimental", "variant": "default", }, "collapsed": false, "entries": [ { "attrs": { "class": "advanced", "ping": "https://example.com", }, "badge": undefined, "href": "/reference/frontmatter/", "isCurrent": false, "label": "Frontmatter Reference", "type": "link", }, ], "label": "Reference", "type": "group", }, { "badge": undefined, "collapsed": false, "entries": [ { "badge": undefined, "collapsed": false, "entries": [ { "attrs": { "class": "current", "data-version": "1", }, "badge": undefined, "href": "/api/v1/products/add/", "isCurrent": false, "label": "Add Product", "type": "link", }, { "attrs": { "class": "current", "data-experimental": true, "data-version": "1", }, "badge": undefined, "href": "/api/v1/products/remove/", "isCurrent": false, "label": "Remove Product", "type": "link", }, ], "label": "products", "type": "group", }, { "attrs": { "class": "current", "data-version": "1", }, "badge": undefined, "href": "/api/v1/users/", "isCurrent": false, "label": "Users API", "type": "link", }, ], "label": "API v1", "type": "group", }, { "badge": undefined, "collapsed": false, "entries": [ { "attrs": {}, "badge": undefined, "href": "/deprecated-api/users/", "isCurrent": false, "label": "Deprecated Users API", "type": "link", }, ], "label": "API (deprecated)", "type": "group", }, ] `); }); }); ================================================ FILE: packages/starlight/__tests__/sidebar/navigation-badges.test.ts ================================================ import { describe, expect, test, vi } from 'vitest'; import { getSidebar } from '../../utils/navigation'; vi.mock('astro:content', async () => (await import('../test-utils')).mockedAstroContent({ docs: [ ['index.mdx', { title: 'Home Page' }], ['environmental-impact.md', { title: 'Eco-friendly docs' }], ['resources/plugins.mdx', { title: 'Plugins' }], ['resources/themes.mdx', { title: 'Themes' }], [ 'reference/configuration.mdx', { title: 'Config Reference', sidebar: { badge: { text: 'Experimental', variant: 'tip', }, }, }, ], ['reference/frontmatter.md', { title: 'Frontmatter Reference', sidebar: { badge: 'New' } }], ['api/v1/users.md', { title: 'Users API' }], ['guides/project-structure.mdx', { title: 'Project Structure' }], ['Deprecated API/users.md', { title: 'Deprecated Users API' }], ], }) ); describe('getSidebar', () => { test('adds a badge object to the sidebar when using a "string" or "object"', () => { expect(getSidebar('/', undefined)).toMatchInlineSnapshot(` [ { "attrs": {}, "badge": undefined, "href": "/", "isCurrent": true, "label": "Home", "type": "link", }, { "badge": undefined, "collapsed": false, "entries": [ { "attrs": {}, "badge": { "text": "New", "variant": "success", }, "href": "/intro", "isCurrent": false, "label": "Introduction", "type": "link", }, { "attrs": {}, "badge": { "text": "Deprecated", "variant": "default", }, "href": "/next-steps", "isCurrent": false, "label": "Next Steps", "type": "link", }, { "attrs": { "class": "showcase-link", "target": "_blank", }, "badge": undefined, "href": "/showcase", "isCurrent": false, "label": "Showcase", "type": "link", }, ], "label": "Start Here", "type": "group", }, { "badge": undefined, "collapsed": false, "entries": [ { "attrs": {}, "badge": undefined, "href": "/resources/plugins/", "isCurrent": false, "label": "Plugins", "type": "link", }, { "attrs": {}, "badge": undefined, "href": "/resources/themes/", "isCurrent": false, "label": "Themes", "type": "link", }, ], "label": "Resources", "type": "group", }, { "badge": { "text": "Experimental", "variant": "default", }, "collapsed": false, "entries": [ { "attrs": {}, "badge": { "text": "Experimental", "variant": "tip", }, "href": "/reference/configuration/", "isCurrent": false, "label": "Config Reference", "type": "link", }, { "attrs": {}, "badge": { "text": "New", "variant": "default", }, "href": "/reference/frontmatter/", "isCurrent": false, "label": "Frontmatter Reference", "type": "link", }, ], "label": "Reference", "type": "group", }, { "badge": undefined, "collapsed": false, "entries": [ { "attrs": { "class": "current", "data-version": "1", }, "badge": undefined, "href": "/api/v1/users/", "isCurrent": false, "label": "Users API", "type": "link", }, ], "label": "API v1", "type": "group", }, { "badge": undefined, "collapsed": false, "entries": [ { "attrs": {}, "badge": undefined, "href": "/deprecated-api/users/", "isCurrent": false, "label": "Deprecated Users API", "type": "link", }, ], "label": "API (deprecated)", "type": "group", }, ] `); }); }); ================================================ FILE: packages/starlight/__tests__/sidebar/navigation-hidden.test.ts ================================================ import { describe, expect, test, vi } from 'vitest'; import { getSidebar } from '../../utils/navigation'; vi.mock('astro:content', async () => (await import('../test-utils')).mockedAstroContent({ docs: [ ['index.mdx', { title: 'Home Page' }], ['environmental-impact.md', { title: 'Eco-friendly docs' }], ['resources/plugins.mdx', { title: 'Plugins' }], ['resources/themes.mdx', { title: 'Themes' }], ['reference/configuration.mdx', { title: 'Config Reference' }], ['reference/frontmatter.md', { title: 'Frontmatter Reference', sidebar: { hidden: true } }], ['api/v1/users.md', { title: 'Users API' }], ['guides/project-structure.mdx', { title: 'Project Structure' }], ['Deprecated API/users.md', { title: 'Deprecated Users API' }], ], }) ); describe('getSidebar', () => { test('excludes sidebar entries with hidden: true in frontmatter', () => { expect(getSidebar('/', undefined)).toMatchInlineSnapshot(` [ { "attrs": {}, "badge": undefined, "href": "/", "isCurrent": true, "label": "Home", "type": "link", }, { "badge": undefined, "collapsed": false, "entries": [ { "attrs": {}, "badge": { "text": "New", "variant": "success", }, "href": "/intro", "isCurrent": false, "label": "Introduction", "type": "link", }, { "attrs": {}, "badge": { "text": "Deprecated", "variant": "default", }, "href": "/next-steps", "isCurrent": false, "label": "Next Steps", "type": "link", }, { "attrs": { "class": "showcase-link", "target": "_blank", }, "badge": undefined, "href": "/showcase", "isCurrent": false, "label": "Showcase", "type": "link", }, ], "label": "Start Here", "type": "group", }, { "badge": undefined, "collapsed": false, "entries": [ { "attrs": {}, "badge": undefined, "href": "/resources/plugins/", "isCurrent": false, "label": "Plugins", "type": "link", }, { "attrs": {}, "badge": undefined, "href": "/resources/themes/", "isCurrent": false, "label": "Themes", "type": "link", }, ], "label": "Resources", "type": "group", }, { "badge": { "text": "Experimental", "variant": "default", }, "collapsed": false, "entries": [ { "attrs": {}, "badge": undefined, "href": "/reference/configuration/", "isCurrent": false, "label": "Config Reference", "type": "link", }, ], "label": "Reference", "type": "group", }, { "badge": undefined, "collapsed": false, "entries": [ { "attrs": { "class": "current", "data-version": "1", }, "badge": undefined, "href": "/api/v1/users/", "isCurrent": false, "label": "Users API", "type": "link", }, ], "label": "API v1", "type": "group", }, { "badge": undefined, "collapsed": false, "entries": [ { "attrs": {}, "badge": undefined, "href": "/deprecated-api/users/", "isCurrent": false, "label": "Deprecated Users API", "type": "link", }, ], "label": "API (deprecated)", "type": "group", }, ] `); }); }); ================================================ FILE: packages/starlight/__tests__/sidebar/navigation-order.test.ts ================================================ import { describe, expect, test, vi } from 'vitest'; import { getSidebar } from '../../utils/navigation'; vi.mock('astro:content', async () => (await import('../test-utils')).mockedAstroContent({ docs: [ ['index.mdx', { title: 'Home Page' }], ['environmental-impact.md', { title: 'Eco-friendly docs' }], ['resources/plugins.mdx', { title: 'Plugins' }], ['resources/themes.mdx', { title: 'Themes' }], ['reference/configuration.mdx', { title: 'Config Reference' }], ['reference/frontmatter.md', { title: 'Frontmatter Reference', sidebar: { order: 1 } }], ['api/v1/users.md', { title: 'Users API' }], ['guides/project-structure.mdx', { title: 'Project Structure' }], ['Deprecated API/users.md', { title: 'Deprecated Users API' }], ], }) ); describe('getSidebar', () => { test('returns sidebar entries sorted by frontmatter order', () => { expect(getSidebar('/', undefined)).toMatchInlineSnapshot(` [ { "attrs": {}, "badge": undefined, "href": "/", "isCurrent": true, "label": "Home", "type": "link", }, { "badge": undefined, "collapsed": false, "entries": [ { "attrs": {}, "badge": { "text": "New", "variant": "success", }, "href": "/intro", "isCurrent": false, "label": "Introduction", "type": "link", }, { "attrs": {}, "badge": { "text": "Deprecated", "variant": "default", }, "href": "/next-steps", "isCurrent": false, "label": "Next Steps", "type": "link", }, { "attrs": { "class": "showcase-link", "target": "_blank", }, "badge": undefined, "href": "/showcase", "isCurrent": false, "label": "Showcase", "type": "link", }, ], "label": "Start Here", "type": "group", }, { "badge": undefined, "collapsed": false, "entries": [ { "attrs": {}, "badge": undefined, "href": "/resources/plugins/", "isCurrent": false, "label": "Plugins", "type": "link", }, { "attrs": {}, "badge": undefined, "href": "/resources/themes/", "isCurrent": false, "label": "Themes", "type": "link", }, ], "label": "Resources", "type": "group", }, { "badge": { "text": "Experimental", "variant": "default", }, "collapsed": false, "entries": [ { "attrs": {}, "badge": undefined, "href": "/reference/frontmatter/", "isCurrent": false, "label": "Frontmatter Reference", "type": "link", }, { "attrs": {}, "badge": undefined, "href": "/reference/configuration/", "isCurrent": false, "label": "Config Reference", "type": "link", }, ], "label": "Reference", "type": "group", }, { "badge": undefined, "collapsed": false, "entries": [ { "attrs": { "class": "current", "data-version": "1", }, "badge": undefined, "href": "/api/v1/users/", "isCurrent": false, "label": "Users API", "type": "link", }, ], "label": "API v1", "type": "group", }, { "badge": undefined, "collapsed": false, "entries": [ { "attrs": {}, "badge": undefined, "href": "/deprecated-api/users/", "isCurrent": false, "label": "Deprecated Users API", "type": "link", }, ], "label": "API (deprecated)", "type": "group", }, ] `); }); }); ================================================ FILE: packages/starlight/__tests__/sidebar/navigation-unicode.test.ts ================================================ import { describe, expect, test, vi } from 'vitest'; import { getSidebar } from '../../utils/navigation'; vi.mock('astro:content', async () => (await import('../test-utils')).mockedAstroContent({ docs: [ ['index.mdx', { title: 'Home Page' }], ['environmental-impact.md', { title: 'Eco-friendly docs' }], ['resources/plugins.mdx', { title: 'Plugins' }], ['resources/themes.mdx', { title: 'Themes' }], ['reference/configuration.mdx', { title: 'Config Reference' }], ['reference/frontmatter.md', { title: 'Frontmatter Reference' }], ['api/v1/用户.md', { title: 'Path with non-ASCII characters' }], ['guides/project-structure.mdx', { title: 'Project Structure' }], ['Deprecated API/用户.md', { title: 'Another path with non-ASCII characters' }], ], }) ); describe('getSidebar', () => { test('matches current page when path contains non-ascii characters', () => { expect(getSidebar('/api/v1/%E7%94%A8%E6%88%B7', undefined)).toMatchInlineSnapshot(` [ { "attrs": {}, "badge": undefined, "href": "/", "isCurrent": false, "label": "Home", "type": "link", }, { "badge": undefined, "collapsed": false, "entries": [ { "attrs": {}, "badge": { "text": "New", "variant": "success", }, "href": "/intro", "isCurrent": false, "label": "Introduction", "type": "link", }, { "attrs": {}, "badge": { "text": "Deprecated", "variant": "default", }, "href": "/next-steps", "isCurrent": false, "label": "Next Steps", "type": "link", }, { "attrs": { "class": "showcase-link", "target": "_blank", }, "badge": undefined, "href": "/showcase", "isCurrent": false, "label": "Showcase", "type": "link", }, ], "label": "Start Here", "type": "group", }, { "badge": undefined, "collapsed": false, "entries": [ { "attrs": {}, "badge": undefined, "href": "/resources/plugins/", "isCurrent": false, "label": "Plugins", "type": "link", }, { "attrs": {}, "badge": undefined, "href": "/resources/themes/", "isCurrent": false, "label": "Themes", "type": "link", }, ], "label": "Resources", "type": "group", }, { "badge": { "text": "Experimental", "variant": "default", }, "collapsed": false, "entries": [ { "attrs": {}, "badge": undefined, "href": "/reference/configuration/", "isCurrent": false, "label": "Config Reference", "type": "link", }, { "attrs": {}, "badge": undefined, "href": "/reference/frontmatter/", "isCurrent": false, "label": "Frontmatter Reference", "type": "link", }, ], "label": "Reference", "type": "group", }, { "badge": undefined, "collapsed": false, "entries": [ { "attrs": { "class": "current", "data-version": "1", }, "badge": undefined, "href": "/api/v1/用户/", "isCurrent": true, "label": "Path with non-ASCII characters", "type": "link", }, ], "label": "API v1", "type": "group", }, { "badge": undefined, "collapsed": false, "entries": [ { "attrs": {}, "badge": undefined, "href": "/deprecated-api/用户/", "isCurrent": false, "label": "Another path with non-ASCII characters", "type": "link", }, ], "label": "API (deprecated)", "type": "group", }, ] `); }); }); ================================================ FILE: packages/starlight/__tests__/sidebar/navigation.test.ts ================================================ import { describe, expect, test, vi } from 'vitest'; import { getSidebar } from '../../utils/navigation'; import type { SidebarEntry } from '../../utils/routing/types'; vi.mock('astro:content', async () => (await import('../test-utils')).mockedAstroContent({ docs: [ ['index.mdx', { title: 'Home Page' }], ['environmental-impact.md', { title: 'Eco-friendly docs' }], ['resources/plugins.mdx', { title: 'Plugins' }], ['resources/themes.mdx', { title: 'Themes' }], ['reference/configuration.mdx', { title: 'Config Reference' }], ['reference/frontmatter.md', { title: 'Frontmatter Reference' }], ['reference/frontmatter/foo.mdx', { title: 'Foo' }], ['api/v1/users.md', { title: 'Users API' }], ['guides/project-structure.mdx', { title: 'Project Structure' }], ['Deprecated API/users.md', { title: 'Deprecated Users API' }], ], }) ); describe('getSidebar', () => { test('returns an array of sidebar entries', () => { expect(getSidebar('/', undefined)).toMatchInlineSnapshot(` [ { "attrs": {}, "badge": undefined, "href": "/", "isCurrent": true, "label": "Home", "type": "link", }, { "badge": undefined, "collapsed": false, "entries": [ { "attrs": {}, "badge": { "text": "New", "variant": "success", }, "href": "/intro", "isCurrent": false, "label": "Introduction", "type": "link", }, { "attrs": {}, "badge": { "text": "Deprecated", "variant": "default", }, "href": "/next-steps", "isCurrent": false, "label": "Next Steps", "type": "link", }, { "attrs": { "class": "showcase-link", "target": "_blank", }, "badge": undefined, "href": "/showcase", "isCurrent": false, "label": "Showcase", "type": "link", }, ], "label": "Start Here", "type": "group", }, { "badge": undefined, "collapsed": false, "entries": [ { "attrs": {}, "badge": undefined, "href": "/resources/plugins/", "isCurrent": false, "label": "Plugins", "type": "link", }, { "attrs": {}, "badge": undefined, "href": "/resources/themes/", "isCurrent": false, "label": "Themes", "type": "link", }, ], "label": "Resources", "type": "group", }, { "badge": { "text": "Experimental", "variant": "default", }, "collapsed": false, "entries": [ { "attrs": {}, "badge": undefined, "href": "/reference/configuration/", "isCurrent": false, "label": "Config Reference", "type": "link", }, { "badge": undefined, "collapsed": false, "entries": [ { "attrs": {}, "badge": undefined, "href": "/reference/frontmatter/", "isCurrent": false, "label": "Frontmatter Reference", "type": "link", }, { "attrs": {}, "badge": undefined, "href": "/reference/frontmatter/foo/", "isCurrent": false, "label": "Foo", "type": "link", }, ], "label": "frontmatter", "type": "group", }, ], "label": "Reference", "type": "group", }, { "badge": undefined, "collapsed": false, "entries": [ { "attrs": { "class": "current", "data-version": "1", }, "badge": undefined, "href": "/api/v1/users/", "isCurrent": false, "label": "Users API", "type": "link", }, ], "label": "API v1", "type": "group", }, { "badge": undefined, "collapsed": false, "entries": [ { "attrs": {}, "badge": undefined, "href": "/deprecated-api/users/", "isCurrent": false, "label": "Deprecated Users API", "type": "link", }, ], "label": "API (deprecated)", "type": "group", }, ] `); }); test("ensures trailing slash consistency between internal and auto-generated sidebar links when using `trailingSlash: 'ignore'`", () => { const sidebar = getSidebar('/', undefined); const internalLinksGroup = sidebar.at(2); const autoGeneratedLinksGroup = sidebar.at(3); function includesOnlyLinksWithTrailingSlash(entry: SidebarEntry | undefined): boolean { return ( entry !== undefined && ((entry.type === 'link' && entry.href.endsWith('/')) || (entry.type === 'group' && entry.entries.every(includesOnlyLinksWithTrailingSlash))) ); } expect(includesOnlyLinksWithTrailingSlash(internalLinksGroup)).toBe(true); expect(includesOnlyLinksWithTrailingSlash(autoGeneratedLinksGroup)).toBe(true); }); }); ================================================ FILE: packages/starlight/__tests__/sidebar/vitest.config.ts ================================================ import { defineVitestConfig } from '../test-config'; export default defineVitestConfig({ title: 'Sidebar Test', sidebar: [ // A single link item labelled “Home”. { label: 'Home', link: '/' }, // A group labelled “Start Here” containing two links. { label: 'Start Here', items: [ { label: 'Introduction', link: '/intro', badge: { variant: 'success', text: 'New', }, }, { label: 'Next Steps', link: '/next-steps', badge: 'Deprecated' }, { label: 'Showcase', link: '/showcase', attrs: { class: 'showcase-link', target: '_blank' }, }, ], }, // A group containing internal links using the `slug` property or its shorthand string syntax. { label: 'Resources', items: ['resources/plugins', { slug: 'resources/themes' }], }, // A group linking to all pages in the `reference` directory. { label: 'Reference', badge: 'Experimental', autogenerate: { directory: 'reference' }, }, // A group linking to all pages in the `api/v1` directory. { label: 'API v1', autogenerate: { directory: '/api/v1/', attrs: { class: 'current', 'data-version': '1' } }, }, // A group linking to all pages in the `Deprecated API/` directory. { label: 'API (deprecated)', autogenerate: { directory: '/Deprecated API/' }, }, ], }); ================================================ FILE: packages/starlight/__tests__/sidebar-slug-error/sidebar-slug-error.test.ts ================================================ import { describe, expect, test, vi } from 'vitest'; import { getSidebar } from '../../utils/navigation'; vi.mock('astro:content', async () => (await import('../test-utils')).mockedAstroContent({ docs: [['getting-started.mdx', { title: 'Getting Started' }]], }) ); describe('getSidebar', () => { test('throws an error if slug doesn’t match a content collection entry', () => { expect(() => getSidebar('/', undefined)).toThrowErrorMatchingInlineSnapshot(` "[AstroUserError]: The slug \`"/getting-started/"\` specified in the Starlight sidebar config must not start or end with a slash. Hint: Please try updating \`"/getting-started/"\` to \`"getting-started"\`." `); }); }); ================================================ FILE: packages/starlight/__tests__/sidebar-slug-error/vitest.config.ts ================================================ import { defineVitestConfig } from '../test-config'; export default defineVitestConfig({ title: 'sidebar slug error', sidebar: ['/getting-started/'], }); ================================================ FILE: packages/starlight/__tests__/snapshot-serializer-astro-error.ts ================================================ import { AstroError } from 'astro/errors'; import type { SnapshotSerializer } from 'vitest'; export default { /** Check if a value should be handled by this serializer, i.e. if it is an `AstroError`. */ test(val) { return !!val && AstroError.is(val); }, /** Customize serialization of Astro errors to include the `hint`. Vitest only uses `message` by default. */ serialize({ name, message, hint }: AstroError, config, indentation, depth, refs, printer) { const prettyError = `[${name}]:\n${indent(message)}\nHint:\n${indent(hint)}`; return printer(prettyError, config, indentation, depth, refs); }, } satisfies SnapshotSerializer; /** Indent each line in `string` with a given character. */ function indent(string = '', indentation = '\t') { return string .split('\n') .map((line) => indentation + line) .join('\n'); } ================================================ FILE: packages/starlight/__tests__/test-config.ts ================================================ /// import type { AstroConfig } from 'astro'; import { getViteConfig } from 'astro/config'; import { vitePluginStarlightUserConfig } from '../integrations/virtual-user-config'; import { runPlugins, type StarlightUserConfigWithPlugins } from '../utils/plugins'; import { createTestPluginContext } from './test-plugin-utils'; import { vitePluginStarlightCssLayerOrder } from '../integrations/vite-layer-order'; export async function defineVitestConfig( { plugins, ...config }: StarlightUserConfigWithPlugins, opts?: { build?: Pick; trailingSlash?: AstroConfig['trailingSlash']; command?: 'dev' | 'build' | 'preview'; } ) { const root = new URL('./', import.meta.url); const srcDir = new URL('./src/', root); const build = opts?.build ?? { format: 'directory' }; const trailingSlash = opts?.trailingSlash ?? 'ignore'; const command = opts?.command ?? 'dev'; const { starlightConfig, pluginTranslations } = await runPlugins( config, plugins, createTestPluginContext() ); return getViteConfig({ plugins: [ vitePluginStarlightCssLayerOrder(), vitePluginStarlightUserConfig( { command, isNodeCompatibleEnv: true }, starlightConfig, { root, srcDir, build, trailingSlash, legacy: { collectionsBackwardsCompat: false }, }, pluginTranslations ), ], test: { snapshotSerializers: ['./snapshot-serializer-astro-error.ts'], }, }); } ================================================ FILE: packages/starlight/__tests__/test-plugin-utils.ts ================================================ import type { AstroIntegrationLogger } from 'astro'; import { type StarlightPluginContext } from '../utils/plugins'; export function createTestPluginContext(): StarlightPluginContext { return { command: 'dev', // @ts-expect-error - we don't provide a full Astro config but only what is needed for the // plugins to run. config: { srcDir: new URL('./src/', import.meta.url), integrations: [] }, isRestart: false, logger: new TestAstroIntegrationLogger(), }; } export class TestAstroIntegrationLogger { options = {} as AstroIntegrationLogger['options']; constructor(public label = 'test-integration-logger') {} fork = (label: string) => new TestAstroIntegrationLogger(label); info = () => undefined; warn = () => undefined; error = () => undefined; debug = () => undefined; } ================================================ FILE: packages/starlight/__tests__/test-utils.ts ================================================ import { z } from 'astro/zod'; import { docsSchema, i18nSchema } from '../schema'; import type { StarlightDocsCollectionEntry } from '../utils/routing/types'; import type { RouteDataContext } from '../utils/routing/data'; import { vi } from 'vitest'; const frontmatterSchema = docsSchema()({ image: () => z.object({ src: z.string(), width: z.number(), height: z.number(), format: z.union([ z.literal('png'), z.literal('jpg'), z.literal('jpeg'), z.literal('tiff'), z.literal('webp'), z.literal('gif'), z.literal('svg'), z.literal('avif'), ]), }), }); function mockDoc( docsFilePath: string, data: z.input, body = '' ): StarlightDocsCollectionEntry { const slug = docsFilePath .replace(/\.[^.]+$/, '') .replace(/\s/, '-') .replace(/\/index$/, '') .toLowerCase(); return { id: slug, body, collection: 'docs', data: frontmatterSchema.parse(data), filePath: `src/content/docs/${docsFilePath}`, }; } function mockDict(id: string, data: z.input>) { return { id: id.toLocaleLowerCase(), data: i18nSchema().parse(data), filePath: `src/content/i18n/${id}.yml`, }; } export async function mockedAstroContent({ docs = [], i18n = [], }: { docs?: Parameters[]; i18n?: Parameters[]; }) { const mod = await vi.importActual('astro:content'); const mockDocs = docs.map((doc) => mockDoc(...doc)); const mockDicts = i18n.map((dict) => mockDict(...dict)); return { ...mod, getCollection: ( collection: 'docs' | 'i18n', filter?: (entry: ReturnType | ReturnType) => unknown ) => { const entries = collection === 'i18n' ? mockDicts : mockDocs; return filter ? entries.filter(filter) : entries; }, }; } export async function mockedCollectionConfig(docsUserSchema?: Parameters[0]) { const content = await vi.importActual('astro:content'); const schemas = await vi.importActual('../schema'); const loaders = await vi.importActual('../loaders'); return { collections: { docs: content.defineCollection({ loader: loaders.docsLoader(), schema: schemas.docsSchema(docsUserSchema), }), i18n: content.defineCollection({ loader: loaders.i18nLoader(), schema: schemas.i18nSchema(), }), }, }; } type RouteDataTestContextOptions = { /** * The pathname to get route data context for, e.g. `"/getting-started/"`. * @default "/" */ pathname?: string; /** * Whether or not the context should include a value for `site`. Set to `false` to test without a `site` value. * @default true */ setSite?: boolean; }; export function getRouteDataTestContext({ pathname, setSite = true, }: RouteDataTestContextOptions = {}): RouteDataContext { const site = new URL('https://example.com'); return { generator: 'Astro', url: pathname ? new URL(pathname, site) : site, site: setSite ? site : undefined, }; } ================================================ FILE: packages/starlight/__tests__/toc-custom-config/toc-custom-config.test.ts ================================================ import { describe, expect, test, vi } from 'vitest'; import { routes } from '../../utils/routing'; import { getRouteDataTestContext } from '../test-utils'; import { generateRouteData } from '../../utils/routing/data'; vi.mock('astro:content', async () => (await import('../test-utils')).mockedAstroContent({ docs: [ ['index.mdx', { title: 'Home Page' }], ['showcase.mdx', { title: 'ToC Disabled', tableOfContents: false }], [ 'environmental-impact.md', { title: 'Explicit update date', tableOfContents: { minHeadingLevel: 2 } }, ], ], }) ); const headings = [ { depth: 1, slug: 'heading-1', text: 'Heading 1' }, { depth: 2, slug: 'heading-2', text: 'Heading 2' }, { depth: 3, slug: 'heading-3', text: 'Heading 3' }, { depth: 4, slug: 'heading-4', text: 'Heading 4' }, ]; describe('custom table of contents config', () => { test('table of contents heading levels match configuration', () => { const route = routes[0]!; const data = generateRouteData({ props: { ...route, headings }, context: getRouteDataTestContext(), }); expect(data.toc?.minHeadingLevel).toBe(1); expect(data.toc?.maxHeadingLevel).toBe(4); }); test('table of contents can be disabled by frontmatter', () => { const route = routes[1]!; const data = generateRouteData({ props: { ...route, headings }, context: getRouteDataTestContext(), }); expect(data.toc).toBeUndefined(); }); test('table of contents heading levels can be customised by frontmatter', () => { const route = routes[2]!; const data = generateRouteData({ props: { ...route, headings }, context: getRouteDataTestContext(), }); expect(data.toc?.minHeadingLevel).toBe(2); expect(data.toc?.maxHeadingLevel).toBe(3); }); }); ================================================ FILE: packages/starlight/__tests__/toc-custom-config/vitest.config.ts ================================================ import { defineVitestConfig } from '../test-config'; export default defineVitestConfig({ title: 'custom ToC config', tableOfContents: { minHeadingLevel: 1, maxHeadingLevel: 4, }, }); ================================================ FILE: packages/starlight/components/AnchorHeading.astro ================================================ --- import type { HTMLAttributes } from 'astro/types'; import { transform } from 'ultrahtml'; import sanitize from 'ultrahtml/transformers/sanitize'; // These styles are included globally by default, but can be removed when `markdown.headingLinks` is // set to `false`. We import them here to ensure they are included if the component is used with the // global Markdown option disabled. import '../style/anchor-links.css'; import { AstroError } from 'astro/errors'; const headingLevels = [1, 2, 3, 4, 5, 6, '1', '2', '3', '4', '5', '6'] as const; interface Props extends HTMLAttributes<'h1'> { level: 1 | 2 | 3 | 4 | 5 | 6 | `${1 | 2 | 3 | 4 | 5 | 6}`; id: string; } const { level, id, ...attrs } = Astro.props; if (!id) { throw new AstroError( 'Missing `id` attribute passed to `` component', `The \`\` component requires an \`id\` attribute, but received \`${typeof id === 'string' ? '""' : id}\`.` ); } if (!headingLevels.includes(level)) { throw new AstroError( 'Invalid `level` attribute passed to `` component', `The \`\` component expects a \`level\` attribute of \`1 | 2 | 3 | 4 | 5 | 6\`, but received \`${level}\`.` ); } const HeadingElement = `h${level}` as const; const headingHTML = await Astro.slots.render('default'); const headingString = await transform(headingHTML, [sanitize({ unblockElements: [] })]); const accessibleLabel = Astro.locals.t('heading.anchorLabel', { title: headingString, interpolation: { escapeValue: false }, }) --- {/* The spacing in this component is a little awkward to ensure whitespace matches what the rehype plugin produces. */}
================================================ FILE: packages/starlight/components/Banner.astro ================================================ --- const { banner } = Astro.locals.starlightRoute.entry.data; --- {banner &&
} ================================================ FILE: packages/starlight/components/ContentNotice.astro ================================================ --- import type { StarlightIcon } from '../components-internals/Icons'; import Icon from '../user-components/Icon.astro'; interface Props { icon: StarlightIcon; label: string; } const { icon, label } = Astro.props; ---

{label}

================================================ FILE: packages/starlight/components/ContentPanel.astro ================================================
================================================ FILE: packages/starlight/components/DraftContentNotice.astro ================================================ --- import ContentNotice from './ContentNotice.astro'; --- ================================================ FILE: packages/starlight/components/EditLink.astro ================================================ --- import Icon from '../user-components/Icon.astro'; const { editUrl } = Astro.locals.starlightRoute; --- { editUrl && ( {Astro.locals.t('page.editLink')} ) } ================================================ FILE: packages/starlight/components/FallbackContentNotice.astro ================================================ --- import ContentNotice from './ContentNotice.astro'; --- ================================================ FILE: packages/starlight/components/Footer.astro ================================================ --- import EditLink from 'virtual:starlight/components/EditLink'; import LastUpdated from 'virtual:starlight/components/LastUpdated'; import Pagination from 'virtual:starlight/components/Pagination'; import config from 'virtual:starlight/user-config'; import { Icon } from '../components'; --- ================================================ FILE: packages/starlight/components/Head.astro ================================================ --- const { head } = Astro.locals.starlightRoute; --- {head.map(({ tag: Tag, attrs, content }) => )} ================================================ FILE: packages/starlight/components/Header.astro ================================================ --- import config from 'virtual:starlight/user-config'; import LanguageSelect from 'virtual:starlight/components/LanguageSelect'; import Search from 'virtual:starlight/components/Search'; import SiteTitle from 'virtual:starlight/components/SiteTitle'; import SocialIcons from 'virtual:starlight/components/SocialIcons'; import ThemeSelect from 'virtual:starlight/components/ThemeSelect'; /** * Render the `Search` component if Pagefind is enabled or the default search component has been overridden. */ const shouldRenderSearch = config.pagefind || config.components.Search !== '@astrojs/starlight/components/Search.astro'; ---
{shouldRenderSearch && }
================================================ FILE: packages/starlight/components/Hero.astro ================================================ --- import { Image } from 'astro:assets'; import { PAGE_TITLE_ID } from '../constants'; import LinkButton from '../user-components/LinkButton.astro'; const { data } = Astro.locals.starlightRoute.entry; const { title = data.title, tagline, image, actions = [] } = data.hero || {}; const imageAttrs = { loading: 'eager' as const, decoding: 'async' as const, width: 400, height: 400, alt: image?.alt || '', }; let darkImage: ImageMetadata | undefined; let lightImage: ImageMetadata | undefined; let rawHtml: string | undefined; if (image) { if ('file' in image) { darkImage = image.file; } else if ('dark' in image) { darkImage = image.dark; lightImage = image.light; } else { rawHtml = image.html; } } ---
{ darkImage && ( ) } {lightImage && } {rawHtml &&
}

{tagline &&
}
{ actions.length > 0 && (
{actions.map( ({ attrs: { class: className, ...attrs } = {}, icon, link: href, text, variant }) => ( {text} {icon?.html && } ) )}
) }

================================================ FILE: packages/starlight/components/LanguageSelect.astro ================================================ --- import context from 'virtual:starlight/project-context'; import config from 'virtual:starlight/user-config'; import { localizedUrl } from '../utils/localizedUrl'; import Select from './Select.astro'; /** * Get the equivalent of the current page path for the passed locale. */ function localizedPathname(locale: string | undefined): string { return localizedUrl(Astro.url, locale, context.trailingSlash).pathname; } --- { config.isMultilingual && ( { Astro.props.options.map(({ value, selected, label }) => (