Skip to content

Commit 1602c6a

Browse files
shhdgitYuiham
andauthored
Feat/restructure (#668)
* feat: implement new LeftNav and RightNav components for improved navigation - Introduced LeftNavDesktop and LeftNavMobile components to enhance the layout and navigation experience. - Added RightNav and RightNavMobile components for better accessibility and organization of content. - Integrated a new H1 component with TitleAction for enhanced header functionality. - Updated translation strings and styles for consistency across the application. - Removed the deprecated Contributors component to streamline the codebase. * chore: update subproject commit reference in docs * feat: add "Improve this document" link in TitleAction component - Introduced a new feature that generates a GitHub edit link for the current document, allowing users to easily contribute improvements. - The link is conditionally rendered based on the presence of pathConfig and filePath, enhancing user engagement with documentation. * fix: update feedback translation for clarity in English and Japanese - Changed the feedback string from "Request docs changes" to "Report a doc issue" in both English and Japanese translation files for improved clarity and user understanding. * fix: update TitleAction component for improved layout and button text - Added flexWrap property to the TitleAction component to enhance layout responsiveness. - Changed button text from "Copy Markdown for LLM" to "Copy for LLM" for brevity and clarity. * fix: update color in RightNav component for better visibility - Changed the text color in the RightNav component from carbon[600] to carbon[700] to enhance readability and visual contrast. * fix: conditionally render TOC in RightNav component - Updated the RightNav component to only display the Table of Contents (TOC) when it contains items, improving layout and preventing unnecessary empty space. * feat: enhance header layout and functionality - Introduced a new header height management system with constants for different header states, improving layout consistency across components. - Updated the Header, LeftNav, RightNav, and various templates to utilize the new header height logic, ensuring proper spacing based on banner visibility. - Added a language switcher option in the HeaderAction component, allowing for better localization support. - Adjusted styles in typography to align with the new header heights, enhancing overall visual coherence. * feat: add new Header components for enhanced navigation and functionality - Introduced HeaderAction, HeaderNav, and LangSwitch components to improve the header layout and user experience. - Implemented a TiDB AI button in HeaderAction for enhanced interactivity. - Added mobile and desktop navigation stacks in HeaderNav for better accessibility. - Integrated a language switcher in LangSwitch to support multiple locales. - Updated the theme with a color adjustment for improved visual consistency. * refactor: enhance header components and introduce mobile navigation - Simplified HeaderAction by consolidating search and action button elements for improved layout. - Updated HeaderNav to remove unused imports and commented-out code, streamlining the component. - Added new HeaderNavMobile component for better mobile navigation experience. - Adjusted spacing and styles in various components for consistency and improved usability. - Enhanced LangSwitch with clearer language labels and updated button styles. - Increased search input width and height for better accessibility. * refactor: reorganize getPageType utility for improved structure - Moved getPageType and PageType type definitions from shared/utils to shared/getPageType for better modularity. - Updated imports across various components to reflect the new location of getPageType, ensuring consistent usage throughout the codebase. - Cleaned up unused imports in several components, enhancing overall code clarity and maintainability. * refactor: replace getPageType with usePageType for improved modularity - Replaced instances of getPageType with the new usePageType hook across various components to enhance code consistency and maintainability. - Updated imports to reflect the new structure, ensuring all components utilize the updated page type logic. - Removed the deprecated getPageType utility, streamlining the codebase and improving clarity. * refactor: replace KeyboardArrowDownIcon with ChevronDownIcon across components - Updated multiple components to use the new ChevronDownIcon for consistency in the UI. - Removed imports of the deprecated KeyboardArrowDownIcon, streamlining the codebase. - Added ChevronDownIcon SVG file to the media/icons directory for improved visual representation. * feat: enhance HeaderNav with dynamic navigation configuration - Introduced a new navigation configuration system in HeaderNav, allowing for dynamic rendering of navigation items and groups based on conditions. - Added NavGroup and NavMenuItem components to improve the structure and maintainability of the navigation logic. - Implemented a default navigation configuration generator to streamline the setup of navigation items based on user cloud plans. - Updated imports and added new icons for improved visual representation in the navigation menu. - Cleaned up unused code and optimized component rendering for better performance. * feat: enhance navigation components with selected item handling - Added onSelectedNavItemChange prop to Header, HeaderNavStack, and LeftNav components to manage selected navigation items. - Implemented a recursive function to find and notify the selected navigation item in HeaderNavStack. - Updated LeftNavDesktop to display the selected navigation item with improved styling and interaction. - Integrated selectedNavItem state management in DocTemplate for better navigation context. - Adjusted styles in various components for consistency and improved user experience. * refactor: update HeaderAction and theme for improved button styling - Replaced ActionButton with Button in HeaderAction for consistency in component usage. - Added secondary color styling for outlined and contained button variants in the theme. - Adjusted button styles to enhance visual coherence and user experience across the application. * refactor: replace ActionButton with Button in FeedbackSection for consistency - Removed the custom ActionButton component and replaced it with the standard Button component from MUI. - Updated button styles to use the secondary color variant for improved visual consistency across the FeedbackSection. - Cleaned up imports by removing the unused ActionButton import, streamlining the codebase. * refactor: improve LangSwitch and theme button styles for consistency - Simplified the LangSwitch component by removing unnecessary padding and adjusting the end icon styling. - Updated the theme to ensure consistent margin settings for button icons, enhancing overall button appearance across the application. * refactor: simplify Box styling in NavGroup for improved readability - Streamlined Box component styles in NavGroup by removing unnecessary sx prop and directly applying display, flexDirection, and gap properties. - Enhanced the layout of child components for better visual consistency and maintainability. * refactor: enhance LeftNavTree with session storage for expanded IDs and scroll position - Removed custom StyledTreeItem in favor of MUI's TreeItem for consistency. - Implemented session storage handling for expanded tree nodes and scroll position restoration. - Updated theme styles for TreeItem to improve visual consistency and user experience. - Cleaned up unused imports and streamlined component logic for better maintainability. * feat: implement clearAllNavStates function for navigation state management - Added clearAllNavStates function to clear session storage for navigation states across components. - Integrated clearAllNavStates in NavMenuItem and NavButton click handlers to ensure consistent navigation behavior. - Updated LeftNav component to utilize clearAllNavStates on item selection for improved user experience. * refactor: update VersionSelect component for improved styling and consistency - Added disableRipple property to MenuItem components for a cleaner interaction experience. - Simplified Divider components by removing unnecessary margin settings. - Enhanced theme styles for MuiMenu to improve layout and item interaction, including active state styling and list organization. - Streamlined MenuItem styles for better visual consistency across the VersionSelect component. * refactor: enhance theme styles for selected TreeItem states - Updated the styling for selected TreeItem states to include focused and hover states for improved visual feedback. - Ensured consistent background color and icon fill for selected items, enhancing user experience in the navigation tree. * refactor: update CloudPlan imports and usage for consistency - Changed the import path for CloudPlan to align with the project structure. - Replaced string literals with CloudPlan enum values in the getTidbCloudFilesFromTocs and determineInDefaultPlan functions for improved type safety and consistency. * Feat/link resolver v1 (#669) * refactor: update CloudPlan imports and usage for consistency - Changed the import path for CloudPlan to align with the project structure. - Replaced string literals with CloudPlan enum values in the getTidbCloudFilesFromTocs and determineInDefaultPlan functions for improved type safety and consistency. * refactor: enhance URL resolver with new link and path mapping utilities - Introduced a comprehensive URL resolver module to map source file paths to published URLs. - Added support for branch aliasing and pattern matching for dynamic URL generation. - Implemented link resolution for markdown links, improving navigation consistency. - Created configuration and utility files for managing path and link mappings, enhancing maintainability and scalability. * feat: add Jest configuration and enhance URL resolution utilities - Introduced Jest configuration for TypeScript tests to improve testing capabilities. - Updated package.json to include Jest and ts-jest dependencies for TypeScript support. - Refactored URL resolution logic to utilize new link resolver utilities, enhancing markdown link handling. - Deprecated the old URL generation method in favor of the new calculateFileUrl function for better maintainability. - Added comprehensive tests for the new URL resolver functionalities, ensuring robust link resolution and alias handling. * refactor: enhance link resolver configuration and logic for improved mapping - Updated link resolver configuration to clarify direct and path-based mapping rules. - Refactored link resolution logic to streamline the processing of link mappings and conditions. - Improved handling of namespace transformations and default language settings in URL generation. - Enhanced type definitions for better clarity on mapping rules and conditions. * refactor: enhance URL resolution logic and link handling for tidbcloud - Updated URL resolver configuration to support dedicated _index files for tidbcloud, improving path mapping accuracy. - Refactored link resolution logic to handle branch-specific paths and filename transformations more effectively. - Enhanced test cases to cover new URL patterns and ensure robust handling of markdown links and fallback scenarios. - Cleaned up deprecated rules and improved overall maintainability of the URL resolver module. * refactor: update mdxAstToToc function to use slug for path resolution - Modified the mdxAstToToc function to accept slug instead of config for improved clarity in path resolution. - Updated related functions in create-types and cloud-plan to ensure consistent usage of slug for TOC generation. - Cleaned up deprecated code and improved overall maintainability of the TOC handling logic. * refactor: simplify selectedId logic in LeftNavTree component - Streamlined the assignment of selectedId by removing unnecessary conditional checks, ensuring it defaults to storedId or undefined. - Improved code clarity and maintainability in the ControlledTreeView function by reducing complexity in state management. * refactor: remove unnecessary logging in URL resolution logic - Eliminated debug logging related to currentFileUrl and resolvedPath in the URL resolution process for tidbcloud. - Improved code cleanliness and maintainability by reducing clutter in the content plugin's index file. * refactor: update navigation and frontmatter handling in Gatsby setup - Replaced createExtraType with createFrontmatter and createNavs in gatsby-node.js for improved type management. - Introduced new functions for generating navigation and frontmatter types, enhancing the structure of Markdown nodes. - Updated URL generation logic in path.ts to include shared namespace handling for better path resolution. - Refactored navigation generation in create-doc-home and create-docs to utilize the new navigation functions. - Improved overall code clarity and maintainability by consolidating navigation logic and enhancing type definitions. * feat: add new link resolver configuration for Tidb documentation - Introduced a new path pattern for Tidb documentation in the link resolver configuration, allowing for better URL mapping. - Enhanced link resolution logic to support specific folder conditions, improving navigation for documentation categories such as "develop," "best-practice," "api," and "releases." - Integrated configuration data from the docs.json file to streamline the management of documentation versions. * refactor: remove unused CONFIG import from link resolver configuration - Eliminated the import of CONFIG from docs.json in the link resolver configuration file to improve code cleanliness and maintainability. * feat: introduce TOCNamespace for improved navigation handling - Added TOCNamespace enum to categorize documentation namespaces, enhancing clarity and maintainability. - Refactored navigation logic in various components to utilize the new TOCNamespace for better type safety and consistency. - Updated link resolver and path generation functions to support TOCNamespace, improving URL mapping and navigation accuracy. - Enhanced the layout and selection logic in navigation components to leverage the new namespace structure, ensuring a more intuitive user experience. * refactor: update navigation and path handling for TOCNamespace - Reorganized SHARED_NAMESPACE_RULES to include TiDBCloud and TiDBInKubernetes namespaces for improved clarity. - Adjusted navigation paths in HeaderNavConfigData to reflect updated folder structure. - Modified useCloudPlan and DocTemplate to utilize TOCNamespace for better type safety and consistency in navigation logic. - Enhanced overall maintainability and accuracy of URL mappings across components. * refactor: enhance URL resolver configuration for tidb and tidb-in-kubernetes - Updated source and target patterns for tidb and tidb-in-kubernetes to improve URL mapping accuracy. - Introduced filename transformation rules to ignore specific filenames for better handling of documentation files. - Added branch alias mappings for both tidb and tidb-in-kubernetes to streamline version management and navigation consistency. * feat: add link resolver and URL resolver configurations for tidb-operator - Introduced new link and target patterns for tidb-operator in both link-resolver and url-resolver configurations to enhance navigation and URL mapping. - Updated HeaderNavConfigData to reflect the new path for TiDB Operator Releases. - Enhanced VersionSelect component to ensure correct selection state for different versions. * refactor: update link and URL resolver configurations for tidb releases - Modified link and target patterns in link-resolver and URL-resolver configurations to include the specific path for tidb releases. - Adjusted navigation paths in HeaderNavConfigData to reflect the updated structure for TiDB Self-Managed Releases. - Updated branch reference in SHARED_NAMESPACE_RULES for improved clarity and consistency in version management. * refactor: integrate TOCNamespace into documentation components for improved navigation - Added TOCNamespace and TOCNamespaceSlugMap to enhance type safety and clarity in navigation logic. - Updated createDocHome to utilize the new namespace for generating navigation URLs. - Refactored MDXContent and CustomContent components to leverage TOCNamespace for better handling of content display based on the current namespace. - Improved overall maintainability and consistency in URL mapping across documentation components. * refactor: enhance HeaderNavMobile component for improved navigation and responsiveness - Integrated TOCNamespace into HeaderNavStackMobile for better type safety and navigation handling. - Refactored navigation item rendering to utilize a dynamic configuration approach, improving maintainability. - Updated Header component to pass namespace prop to HeaderNavStackMobile for enhanced context. - Adjusted layout styles for responsive design, ensuring better user experience across devices. - Removed unused RightNav component to streamline the codebase. * refactor: replace pageUrl with namespace in layout and header components for improved type safety - Removed pageUrl prop from Layout, Header, and HeaderNav components, replacing it with the required namespace prop. - Updated useIsAutoTranslation to utilize namespace instead of pageUrl for better context handling. - Refactored filterRightToc function to accept namespace, enhancing filtering logic based on TOCNamespace. - Deleted unused usePageType module to streamline the codebase and improve maintainability. * refactor: update link resolver configuration to include language support - Modified target patterns in link-resolver configuration to incorporate language as a dynamic segment in URLs. - Extracted current language from the page URL and added it as a default variable in the link resolution process. - Enhanced link mapping rules to ensure proper handling of language-specific paths for tidb releases and documentation. * refactor: enhance URL and link resolver functionality with caching and path calculation improvements - Introduced caching mechanisms in URL and link resolvers to optimize performance by reducing redundant calculations. - Updated `calculateFileUrl` and `parseSourcePath` functions to utilize caching for improved efficiency. - Enhanced link resolution logic to incorporate dynamic language handling and improved path calculations. - Added utility functions to clear caches, facilitating testing and configuration changes. * refactor: extend TOCNamespace for enhanced navigation in templates - Added new TOCNamespace values for NotFound, Search, and CloudAPIApp to improve navigation context. - Updated relevant templates (404Template, CloudAPIReferenceTemplate, DocSearchTemplate) to utilize the new namespace prop in Layout for better type safety and clarity. - Enhanced overall maintainability and consistency in navigation logic across documentation components. * refactor: update URL resolver and configuration for enhanced path handling - Modified link resolver configuration to include additional paths for 'develop', 'best-practice', 'api', and 'releases' in the match patterns. - Added new test cases to validate URL resolution for 'releases' folders in both English and Chinese, ensuring accurate path generation for documentation. - Improved overall robustness of URL resolution logic to accommodate new documentation structures. * refactor: update link and URL resolver configurations for tidb releases and navigation - Modified link resolver configuration to change paths for 'tidb' and 'tidb-in-kubernetes' releases, ensuring accurate mapping to 'tidb-self-managed'. - Updated URL resolver patterns to reflect changes in target paths for tidb releases, enhancing URL generation consistency. - Enhanced test cases to validate new link resolution logic for both English and Chinese, ensuring proper handling of language-specific paths. - Improved navigation components to support dynamic language handling and disabled states for specific items based on language. * refactor: enhance popover handling in HeaderNav component - Added handlePopoverToggle function to manage popover state on click events, improving user interaction. - Implemented handlePopoverCloseImmediate for closing the popover without delay when clicking outside. - Updated NavButton to support onClick prop, allowing for dynamic popover behavior based on user actions. - Ensured consistent popover closing logic across nested navigation items for better usability. * feat: add URL and link resolver documentation for improved clarity - Introduced comprehensive documentation for the URL Mapping Architecture, detailing the processes for page URL mapping, TOC mapping, and article link mapping. - Added a new Link Resolver module documentation, explaining its context-aware link resolution capabilities and configuration structure. - Created URL Resolver documentation, outlining its purpose, usage, and configuration for transforming source file paths into SEO-friendly URLs. - Enhanced overall understanding of the URL mapping system, including configuration rules and examples for better maintainability and extensibility. * feat: add repository guidelines and enhance Header components - Introduced a new AGENTS.md file containing comprehensive repository guidelines covering project structure, build commands, coding style, testing, and commit practices. - Updated HeaderAction component to utilize theme for icon styling, improving visual consistency. - Increased font size in HeaderNav component buttons for better readability. - Renamed navigation items in HeaderNavConfigData for clarity, reflecting deployment methods. - Adjusted font size in LangSwitch and RightNav components for uniformity in design. - Enhanced theme configuration to improve hover effects across components. * refactor: update URL mapping and link resolution for developer namespace - Changed references from 'develop' to 'developer' across URL mapping and link resolver configurations to enhance clarity and consistency. - Updated documentation to reflect the new namespace structure, ensuring accurate guidance for developers. - Adjusted test cases to validate the new 'developer' namespace handling in link resolution logic. - Enhanced Header components to align with the updated navigation paths, improving user experience. * fix: adjust Header and Search component styles for improved layout - Added flexShrink property to the Header component to prevent unwanted shrinking of the header section. - Reduced font size in the Search component from 16px to 14px for better alignment with design specifications. * fix: adjust Header component styles for improved layout - Added height property to the Box component in the Header to ensure consistent spacing. - Updated TiDBLogo component to use percentage-based dimensions for better responsiveness. * refactor: standardize namespace terminology in URL mapping and link resolution - Updated references from 'best-practice' to 'best-practices' across URL mapping, link resolver configurations, and documentation for consistency. - Adjusted test cases to reflect the new 'best-practices' namespace handling, ensuring accurate validation of link resolution logic. - Enhanced documentation to clarify the updated namespace structure, improving guidance for developers. * chore: test commit Tests: not run * chore: update GitHub Actions workflow and clean up HeaderAction component - Added permissions for actions in the sync-nextgen workflow to enhance functionality. - Implemented a step to dispatch the production workflow on the preview-nextgen branch. - Removed commented-out test code in the HeaderAction component for cleaner code. * feat: enhance URL mapping with nested _index rule and update TOC namespace handling - Introduced a new fallback nested _index rule to map nested _index.md pages to their respective folder URLs, preventing conflicts at the repo root. - Updated getTOCNamespace function to return undefined for unmatched slugs, improving error handling. - Adjusted URL resolver configuration to include the new nested _index rule. - Enhanced tests to validate the new URL mapping behavior for nested _index pages. * docs: expand LinkResolver and UrlResolver configuration options in documentation - Added detailed descriptions for `LinkResolverConfig` and `UrlResolverConfig` options, including `linkMappings`, `defaultLanguage`, and various mapping rules. - Enhanced documentation clarity by specifying fields and their functionalities within `LinkMappingRule` and `PathMappingRule`. - Improved guidance for developers on using path-based mappings and alias definitions in URL resolution. * feat: extend URL mapping and link resolution to include AI namespace - Updated gatsby-config.js and documentation to incorporate the 'ai' namespace in URL mappings for better organization of AI-related content. - Enhanced link resolver and URL resolver configurations to support the new 'ai' folder, ensuring consistent URL structure across namespaces. - Added tests to validate the resolution of links and URLs for the 'ai' namespace, improving overall test coverage and reliability. * chore: update subproject commit reference in documentation - Updated the subproject commit reference in the documentation to reflect the latest changes in the associated submodule, ensuring accurate linkage and versioning. * feat: refactor header height calculations and improve layout responsiveness * feat: enhance header scroll behavior with CSS variables and refactor state management * feat: add back-to-top button functionality and improve scroll behavior * feat: update back-to-top button visibility for responsive design * feat: refactor navigation item selection logic and integrate into DocTemplate * feat(layout/header): add AI namespace to navigation and update TOCNamespace enumeration - Introduced a new navigation item for the AI section in the header. - Updated the TOCNamespace enum and slug mapping to include the AI namespace, enhancing content organization and accessibility. * docs: update README to reflect AI namespace in URL resolution tests - Modified the README to change the mapping reference from 'develop/best-practices/api/releases' to 'ai/develop/best-practices/api/releases', ensuring accurate documentation of the URL resolution tests for the AI namespace. * refine(translation): update copy-for-llm text to "Copy as Markdown" for clarity * fix(header): update button text from "Ask TiDB.ai" to "Ask AI" for clarity * fix(mdx/SimpleTab): enhance tab handling logic and improve rendering of nested tab structures - Updated the tab extraction logic to support nested tab elements and wrappers like <CustomContent>. - Refactored the component to use clearer type definitions and improve readability. - Preserved original top-level nodes for rendering, ensuring proper display of tab content. * fix(gatsby/toc): add AI namespace rule to TOC path configuration - Introduced a new namespace rule for the AI section, specifying the repository, branch, folder, and minimum REST length for proper namespace matching in the table of contents. * feat(translation): add new terms and phrases for product features across multiple languages - Expanded translation files for English, Japanese, and Chinese to include new terms related to product features, deployment options, and release information. - Added entries for "Product", "AI", "Developer", "Best Practices", "API", and various TiDB Cloud offerings to enhance localization support. * feat(layout/header): add optional left navigation label to NavItemConfig - Introduced a new optional property `leftNavLabel` to the `NavItemConfig` interface for displaying an alias label in the left navigation. - Updated the `LeftNavDesktop` component to utilize `leftNavLabel` when rendering navigation items, enhancing the display and organization of navigation elements. * feat(layout/header): enhance navigation configuration with translation support and new preview badge - Updated navigation configuration to utilize translation functions for labels and titles, improving localization. - Added a new `PreviewBadge` component to display a preview label for specific navigation items, enhancing visual clarity. - Refactored the `getDefaultNavConfig` function to accept a translation function as a parameter, streamlining the integration of localized text. * refactor(layout/navigation): implement sticky container for left navigation and enhance version selection - Added a `LeftNavStickyContainer` component to improve the layout of the left navigation by making it sticky. - Updated the `LeftNavDesktop` component to utilize the new sticky container for better visual organization. - Enhanced the `VersionSelectButton` to accept a `disableStickyContainer` prop, allowing for flexible layout options. - Refactored the `CloudVersionSelect` and `VersionSelect` components to support the new prop, ensuring consistent behavior across version selection elements. * feat(toc): implement TOC ignore functionality and related tests - Added a new `toc-ignore.ts` file to define rules for ignoring specific TOC files during the build process. - Introduced the `isIgnoredTocRelativePath` function to check if a given relative path should be ignored based on predefined substrings and environment variables. - Updated the `getFilesFromTocs` function in `toc-filter.ts` to utilize the new ignore logic, enhancing filtering capabilities. - Created unit tests in `toc-filter.test.ts` to validate the ignore rules and ensure correct functionality. * feat(link-resolver): add path-based mapping for releases links in TiDB documentation * feat(url-mapping): add comprehensive guidelines for modifying URL mapping rules in website-docs * feat(toc-namespace): introduce TOC namespace resolver and update URL mapping process * feat(link-resolver): update link patterns for releases from TiDB Operator landing page * feat(link-resolver): enhance link resolution for releases from tidb-operator page with language handling * feat(header-animation): implement scroll-driven animations for logo and navigation * refine(translation): update Chinese translations for 'developer' and 'preview' terms * refine(layouts, translation): add 'TiDB for AI' translation in English, Japanese, and Chinese * Revert "feat(header-animation): implement scroll-driven animations for logo and navigation" This reverts commit 9d34ad6. * refine(LeftNav): add margin to VersionSelect component for better spacing * feat(header): implement scroll-driven logo scaling and translation adjustments * feat(link-resolver): enhance link resolution with support for multiple languages and improved default language handling * refine(link-resolver): simplify supported languages configuration * feat: enhance TOC file handling and cloud plan management across components * feat(DocTemplate): enhance cloud plan handling and navigation integration * feat(useCloudPlan): improve cloud plan resolution from query and session storage * feat(banner): auto translation zh ai * feat(banner): auto translation zh tidb cloud releases * chore: remove sync-nextgen.yml --------- Co-authored-by: Yuiham <Yuiham@users.noreply.github.com>
1 parent 8bad120 commit 1602c6a

90 files changed

Lines changed: 10418 additions & 1947 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
---
2+
name: website-docs-url-mapping
3+
description: Modify URL mapping rules in the website-docs Gatsby site by editing gatsby/url-resolver/config.ts and gatsby/link-resolver/config.ts, updating Jest tests, updating gatsby/URL_MAPPING_ARCHITECTURE.md, and reviewing gatsby-plugin-react-i18next matchPath when URL prefixes or languages change.
4+
---
5+
6+
# Website-docs URL Mapping
7+
8+
## Overview
9+
10+
Modify the mapping rules between docs source paths and site URLs, and resolve internal Markdown links, while keeping tests and docs in sync.
11+
12+
## Workflow
13+
14+
### 1) Gather Requirements (Clarify First)
15+
16+
Ask the user for “input → expected output” examples (at least 3 of each; more is better):
17+
- Page URLs: `sourcePath/slug -> pageUrl` (whether to omit default language `/en/`, and trailing slash expectations)
18+
- Link resolution: `(linkPath, currentPageUrl) -> resolvedUrl` (include edge cases: hash, no leading slash, relative paths, etc.)
19+
20+
### 2) Review Existing Design (Align Terms and Current Behavior)
21+
22+
Open and quickly locate the rules sections:
23+
- `gatsby/URL_MAPPING_ARCHITECTURE.md` (Configuration Rules)
24+
- `gatsby/url-resolver/README.md` (pattern/alias/filenameTransform)
25+
- `gatsby/link-resolver/README.md` (direct vs path-based, conditions/pathConditions)
26+
27+
### 3) Edit URL Resolver (Page URLs)
28+
29+
Edit: `gatsby/url-resolver/config.ts`
30+
- `pathMappings` are matched in order (first match wins); new rules usually go before more general ones.
31+
- `sourcePattern` supports `{var}` and `{...var}`; `conditions` use extracted variables to decide applicability.
32+
- Use `filenameTransform` to handle `_index` / `_docHome` (ignore filename or switch `targetPattern`).
33+
- If branch display logic changes, update `aliases` as well (e.g. `{branch:branch-alias-tidb}`).
34+
35+
### 4) Edit Link Resolver (Markdown Links)
36+
37+
Edit: `gatsby/link-resolver/config.ts`
38+
- Direct mapping: only `linkPattern` (does not depend on the current page)
39+
- Path-based mapping: `pathPattern + linkPattern`, constrained by `pathConditions`
40+
- Use `namespaceTransform` for namespace migrations (e.g. `develop -> developer`)
41+
- Watch `defaultLanguage` omission logic and `url-resolver.trailingSlash` (tests should cover both)
42+
43+
### 5) Update/Add Tests (Prevent Regressions)
44+
45+
- `gatsby/url-resolver/__tests__/url-resolver.test.ts`
46+
- `gatsby/link-resolver/__tests__/link-resolver.test.ts`
47+
48+
Coverage (at minimum, every new/changed rule has assertions):
49+
- New rule match vs fallback (ordering)
50+
- `en/zh/ja` + whether `/en/` is omitted
51+
- `_index` vs non-`_index`
52+
- Links: preserve hash, no leading slash, path depth, multi-segment prefixes, etc.
53+
54+
### 6) Run Tests
55+
56+
- Full suite: `yarn test`
57+
- Or run a single test file first: `yarn test gatsby/url-resolver/__tests__/url-resolver.test.ts`, `yarn test gatsby/link-resolver/__tests__/link-resolver.test.ts`
58+
59+
### 7) Update Architecture Doc (Keep It In Sync)
60+
61+
Edit: `gatsby/URL_MAPPING_ARCHITECTURE.md`
62+
- Update interpretations under “URL Resolver Configuration Rules” and “Link Resolver Configuration Rules”
63+
- Keep rule numbering/order consistent with `config.ts`, and update input/output examples
64+
65+
### 8) Check i18n Routing (Often Required When URL Prefixes Change)
66+
67+
Review: `gatsby-config.js``gatsby-plugin-react-i18next`:
68+
- Ensure `languages` matches supported site languages (currently `en/zh/ja`)
69+
- Ensure `pages[].matchPath` includes any new/renamed top-level path prefixes (e.g. `developer`, `best-practices`, `api`, `releases`, and repo keys in `docs/docs.json`)

AGENTS.md

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Repository Guidelines
2+
3+
## Project Structure & Module Organization
4+
5+
- `src/`: Gatsby site code (React components, templates, state, theme, and styles).
6+
- `gatsby/`: build-time utilities (page creation, link/url resolvers, custom plugins) and unit tests.
7+
- `docs/`: documentation content (git submodule pointing to `pingcap/docs-staging`).
8+
- `locale/`: i18n dictionaries (`locale/{en,zh,ja}/translation.json`).
9+
- `static/`, `src/media/`, `images/`: static assets used by the site/README.
10+
- Generated (do not commit): `.cache/`, `public/`, `coverage/`.
11+
12+
## Build, Test, and Development Commands
13+
14+
- `yarn`: install dependencies and apply `patches/` via `patch-package`.
15+
- `git submodule update --init --depth 1 --remote`: fetch/update the docs submodule content.
16+
- `yarn start` (or `yarn dev`): run local development server (Gatsby develop).
17+
- `yarn build`: create a production build.
18+
- `yarn serve`: serve the production build locally.
19+
- `yarn clean`: remove Gatsby build caches (`.cache/`, `public/`).
20+
- `yarn test`: run Jest with coverage for code under `gatsby/`.
21+
22+
## Coding Style & Naming Conventions
23+
24+
- Indentation: 2 spaces (see `.editorconfig`); keep TypeScript `strict` passing.
25+
- Formatting: Prettier runs via Husky + lint-staged on commit (`.husky/pre-commit`).
26+
- Components: PascalCase folders/files (e.g. `src/components/Layout/`); utilities/hooks: camelCase.
27+
- Styles: prefer CSS Modules (`*.module.css`); shared CSS in `src/styles/*.css`.
28+
- Imports: `tsconfig.json` sets `baseUrl: "./src"` (absolute imports like `shared/utils/...` are preferred).
29+
30+
## Testing Guidelines
31+
32+
- Framework: Jest + `ts-jest` (`jest.config.js`).
33+
- Location/pattern: `gatsby/**/__tests__/**/*.test.{ts,tsx,js,jsx}`.
34+
- Add/adjust tests when changing resolver logic or Gatsby build utilities.
35+
36+
## Commit & Pull Request Guidelines
37+
38+
- Commit messages follow a Conventional Commits pattern (common types: `feat:`, `fix:`, `refactor:`, `chore:`).
39+
- PRs should include: clear description + rationale, linked issue(s), and screenshots for UI changes.
40+
- Before requesting review, ensure `yarn test` and `yarn build` pass locally.
41+
42+
## Security & Configuration Tips
43+
44+
- Put local-only env vars in `.env.development` (e.g. `GATSBY_ALGOLIA_APPLICATION_ID`, `GATSBY_ALGOLIA_API_KEY`).
45+
- If GitHub API rate-limits during development, set `GITHUB_AUTHORIZATION_TOKEN=...` when running commands.
46+
- Never commit `.env*` files (they are gitignored).

gatsby-config.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,9 @@ module.exports = {
7979
getLanguageFromPath: false,
8080
},
8181
{
82-
matchPath: `/:lang?/(${Object.keys(docs.docs).join("|")})/(.*)`,
82+
matchPath: `/:lang?/(${Object.keys(docs.docs).join(
83+
"|"
84+
)}|developer|best-practices|api|ai|releases)/(.*)`,
8385
getLanguageFromPath: true,
8486
},
8587
{

gatsby-node.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ const {
88
createDocSearch,
99
create404,
1010
} = require("./gatsby/create-pages");
11-
const { createExtraType } = require("./gatsby/create-types");
11+
const { createFrontmatter, createNavs } = require("./gatsby/create-types");
1212
const {
1313
createConditionalToc,
1414
} = require("./gatsby/plugin/conditional-toc/conditional-toc");
@@ -26,6 +26,7 @@ exports.createPages = async ({ graphql, actions }) => {
2626
};
2727

2828
exports.createSchemaCustomization = (options) => {
29-
createExtraType(options);
29+
createFrontmatter(options);
30+
createNavs(options);
3031
createConditionalToc(options);
3132
};

gatsby-ssr.js

Lines changed: 113 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,113 @@ const fulfillCloudPlanScript = `
9595
})();
9696
`;
9797

98-
export const onRenderBody = ({ setPostBodyComponents, setHeadComponents }) => {
98+
const headerPrehydrateScript = `
99+
(function() {
100+
try {
101+
var ROOT_SELECTOR = "[data-pc-docs-header-root]";
102+
var LEFT_CLUSTER_SELECTOR = "[data-pc-docs-header-left-cluster]";
103+
var LOGO_MEASURE_SELECTOR = "[data-pc-docs-header-logo-measure]";
104+
var CSS_VAR_TRANSLATE_X = "--pc-docs-header-translate-x";
105+
var CSS_VAR_LOGO_SCALE = "--pc-docs-header-logo-scale";
106+
var LOGO_GAP = 24;
107+
var FIRST_ROW_HEIGHT = 56;
108+
109+
function clamp(value, min, max) {
110+
return Math.min(max, Math.max(min, value));
111+
}
112+
113+
function sync(root) {
114+
if (!root || !root.style) {
115+
return false;
116+
}
117+
118+
var y = window.scrollY || 0;
119+
var progress = clamp(y / FIRST_ROW_HEIGHT, 0, 1);
120+
var logoScale = 1 - progress * 0.2;
121+
122+
var leftCluster = root.querySelector(LEFT_CLUSTER_SELECTOR);
123+
var logoMeasure = root.querySelector(LOGO_MEASURE_SELECTOR);
124+
125+
if (!leftCluster || !logoMeasure) {
126+
return false;
127+
}
128+
129+
var leftClusterWidth = leftCluster.getBoundingClientRect().width || 0;
130+
var logoWidth = logoMeasure.getBoundingClientRect().width || 0;
131+
132+
// Always update logo scale; translateX depends on measured widths.
133+
root.style.setProperty(CSS_VAR_LOGO_SCALE, "" + logoScale);
134+
135+
if (!leftClusterWidth || !logoWidth) {
136+
return false;
137+
}
138+
139+
var menuWidth = Math.max(0, leftClusterWidth - logoWidth);
140+
var translateX = progress * (menuWidth + logoWidth * logoScale + LOGO_GAP);
141+
142+
root.style.setProperty(CSS_VAR_TRANSLATE_X, translateX + "px");
143+
return true;
144+
}
145+
146+
function trySync() {
147+
var root = document.querySelector(ROOT_SELECTOR);
148+
if (!root) {
149+
return false;
150+
}
151+
152+
// Desktop only: xs uses a different layout and doesn't consume translateX.
153+
var isDesktop = false;
154+
try {
155+
isDesktop = window.matchMedia && window.matchMedia("(min-width: 900px)").matches;
156+
} catch (e) {
157+
isDesktop = false;
158+
}
159+
if (!isDesktop) {
160+
root.style.setProperty(CSS_VAR_TRANSLATE_X, "0px");
161+
root.style.setProperty(CSS_VAR_LOGO_SCALE, "1");
162+
return true;
163+
}
164+
165+
return sync(root);
166+
}
167+
168+
if (trySync()) {
169+
return;
170+
}
171+
172+
var observer = new MutationObserver(function() {
173+
if (trySync()) {
174+
observer.disconnect();
175+
}
176+
});
177+
178+
observer.observe(document.documentElement, { childList: true, subtree: true });
179+
180+
// Fallback retries (in case layout isn't ready when the observer fires).
181+
var retries = 0;
182+
(function retry() {
183+
if (trySync()) {
184+
observer.disconnect();
185+
return;
186+
}
187+
retries += 1;
188+
if (retries >= 20) {
189+
observer.disconnect();
190+
return;
191+
}
192+
setTimeout(retry, 50);
193+
})();
194+
} catch (e) {
195+
// no-op
196+
}
197+
})();
198+
`;
199+
200+
export const onRenderBody = ({
201+
setPostBodyComponents,
202+
setHeadComponents,
203+
setPreBodyComponents,
204+
}) => {
99205
setHeadComponents([
100206
<link
101207
key="moderat-bold"
@@ -130,6 +236,12 @@ export const onRenderBody = ({ setPostBodyComponents, setHeadComponents }) => {
130236
crossOrigin="anonymous"
131237
/>,
132238
]);
239+
setPreBodyComponents([
240+
<script
241+
key="header-prehydrate"
242+
dangerouslySetInnerHTML={{ __html: headerPrehydrateScript }}
243+
/>,
244+
]);
133245
setPostBodyComponents([
134246
<script key="deprecated" dangerouslySetInnerHTML={{ __html: script }} />,
135247
<script

0 commit comments

Comments
 (0)