AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

section-tabs.tsx 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. import type { LucideIcon } from 'lucide-react';
  2. import type { KeyboardEvent, ReactNode } from 'react';
  3. import { useEffect, useRef, useState } from 'react';
  4. import { cn } from '@/lib/utils';
  5. export type SectionTab = {
  6. key: string;
  7. label: string;
  8. icon: LucideIcon;
  9. /** A small number after the label, such as how many tiles there are. */
  10. count?: number;
  11. /** Something in this tab needs fixing, such as a field the save refused. */
  12. hasError?: boolean;
  13. content: ReactNode;
  14. };
  15. /**
  16. * The look shared by every tab row in the app (Design, Settings, the store menu, Appearance): flat cells, and the
  17. * open one filled with the border colour. Put it on the row's buttons or links.
  18. */
  19. export function tabClass(selected: boolean): string {
  20. return cn(
  21. 'flex shrink-0 items-center px-4 py-3 text-sm whitespace-nowrap transition-colors duration-200 focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none focus-visible:ring-inset motion-reduce:transition-none',
  22. selected
  23. ? 'bg-border font-medium text-foreground'
  24. : 'text-muted-foreground hover:bg-muted/60 hover:text-foreground',
  25. );
  26. }
  27. /** The row around the tabs: a bordered strip that slides sideways on phones. */
  28. export const tabRowClass =
  29. 'flex [scrollbar-width:none] overflow-x-auto rounded-xl border';
  30. /** A tab's icon and words. They rise in each time the tab opens. */
  31. export function TabLabel({
  32. icon: Icon,
  33. label,
  34. selected,
  35. count,
  36. hasError,
  37. errorTest,
  38. }: {
  39. icon: LucideIcon;
  40. label: string;
  41. selected: boolean;
  42. count?: number;
  43. hasError?: boolean;
  44. errorTest?: string;
  45. }) {
  46. return (
  47. // A new key when the tab opens, so the label rises in each time.
  48. <span
  49. key={selected ? 'open' : 'closed'}
  50. className={cn(
  51. 'flex items-center gap-2',
  52. selected &&
  53. 'animate-in duration-300 fade-in-50 slide-in-from-bottom-1 motion-reduce:animate-none',
  54. )}
  55. >
  56. <Icon className="size-4" aria-hidden="true" />
  57. {label}
  58. {count !== undefined && count > 0 && (
  59. <span className="text-muted-foreground tabular-nums">
  60. {count}
  61. </span>
  62. )}
  63. {hasError && (
  64. <span
  65. className="size-1.5 rounded-full bg-red-600"
  66. data-test={errorTest}
  67. >
  68. <span className="sr-only">(needs fixing)</span>
  69. </span>
  70. )}
  71. </span>
  72. );
  73. }
  74. function storageKey(name: string): string {
  75. return `section-tabs:${name}:${window.location.pathname}`;
  76. }
  77. /** The tab named in the address (#contact), else the one last open on this page. */
  78. function startingTab(name: string, tabs: SectionTab[]): string {
  79. const keys = tabs.map((tab) => tab.key);
  80. const hash = window.location.hash.slice(1);
  81. if (keys.includes(hash)) {
  82. return hash;
  83. }
  84. try {
  85. const saved = window.sessionStorage.getItem(storageKey(name));
  86. if (saved && keys.includes(saved)) {
  87. return saved;
  88. }
  89. } catch {
  90. // Storage can be blocked; the first tab is fine.
  91. }
  92. return keys[0] ?? '';
  93. }
  94. /**
  95. * Sections of a page as one row of tabs, one open at a time (the Design tab, Settings).
  96. * - Every panel stays mounted, so half-typed changes survive switching tabs and the page's form still sends them.
  97. * - The open tab is remembered for this browser tab, so saving (which reloads the page) keeps you where you were.
  98. * - A link to an id inside a tab (#payments, #pickup) opens that tab and scrolls to it.
  99. * - When a save is refused, the first tab with a problem opens.
  100. */
  101. export default function SectionTabs({
  102. name,
  103. label,
  104. tabs,
  105. panelClassName,
  106. onChange,
  107. }: {
  108. /** Short page name, used for ids and to remember the open tab. */
  109. name: string;
  110. /** What the row is, for screen readers. */
  111. label: string;
  112. tabs: SectionTab[];
  113. panelClassName?: string;
  114. onChange?: (key: string) => void;
  115. }) {
  116. const [active, setActive] = useState(() => startingTab(name, tabs));
  117. const buttons = useRef<Record<string, HTMLButtonElement | null>>({});
  118. const onChangeRef = useRef(onChange);
  119. const current = tabs.some((tab) => tab.key === active)
  120. ? active
  121. : (tabs[0]?.key ?? '');
  122. useEffect(() => {
  123. onChangeRef.current = onChange;
  124. }, [onChange]);
  125. useEffect(() => {
  126. try {
  127. window.sessionStorage.setItem(storageKey(name), current);
  128. } catch {
  129. // Not remembered; nothing else changes.
  130. }
  131. onChangeRef.current?.(current);
  132. }, [name, current]);
  133. // Links such as Settings#payments: open the tab holding that id, then scroll to it.
  134. useEffect(() => {
  135. function openFromHash() {
  136. const id = window.location.hash.slice(1);
  137. const target = id ? document.getElementById(id) : null;
  138. const panel = target?.closest<HTMLElement>(
  139. `[data-section-tabs="${name}"] [role="tabpanel"]`,
  140. );
  141. if (!target || !panel?.dataset.tabKey) {
  142. return;
  143. }
  144. setActive(panel.dataset.tabKey);
  145. requestAnimationFrame(() =>
  146. target.scrollIntoView({ block: 'start' }),
  147. );
  148. }
  149. openFromHash();
  150. window.addEventListener('hashchange', openFromHash);
  151. return () => window.removeEventListener('hashchange', openFromHash);
  152. }, [name]);
  153. // A refused save: show the first tab with a problem, unless the open one has one.
  154. const errorKeys = tabs
  155. .filter((tab) => tab.hasError)
  156. .map((tab) => tab.key)
  157. .join(',');
  158. useEffect(() => {
  159. const withErrors = errorKeys === '' ? [] : errorKeys.split(',');
  160. if (withErrors.length > 0) {
  161. setActive((open) =>
  162. withErrors.includes(open) ? open : withErrors[0],
  163. );
  164. }
  165. }, [errorKeys]);
  166. // Arrow keys move along the row, like any tab list.
  167. function onKeyDown(event: KeyboardEvent<HTMLDivElement>) {
  168. const index = tabs.findIndex((tab) => tab.key === current);
  169. const step =
  170. event.key === 'ArrowRight' ? 1 : event.key === 'ArrowLeft' ? -1 : 0;
  171. const target =
  172. event.key === 'Home'
  173. ? tabs[0]
  174. : event.key === 'End'
  175. ? tabs[tabs.length - 1]
  176. : step !== 0
  177. ? tabs[(index + step + tabs.length) % tabs.length]
  178. : undefined;
  179. if (!target) {
  180. return;
  181. }
  182. event.preventDefault();
  183. setActive(target.key);
  184. buttons.current[target.key]?.focus();
  185. }
  186. if (tabs.length === 0) {
  187. return null;
  188. }
  189. return (
  190. <div
  191. className="rounded-xl border"
  192. data-section-tabs={name}
  193. data-test={`${name}-tabs`}
  194. // A browser check refused a field in a closed tab: open that tab so the field can be seen and fixed.
  195. onInvalidCapture={(event) => {
  196. const key = (event.target as HTMLElement).closest<HTMLElement>(
  197. '[role="tabpanel"]',
  198. )?.dataset.tabKey;
  199. if (key) {
  200. setActive(key);
  201. }
  202. }}
  203. >
  204. <div
  205. role="tablist"
  206. aria-label={label}
  207. onKeyDown={onKeyDown}
  208. className={cn(
  209. tabRowClass,
  210. 'rounded-none rounded-t-xl border-0 border-b',
  211. )}
  212. >
  213. {tabs.map((tab) => {
  214. const selected = tab.key === current;
  215. return (
  216. <button
  217. key={tab.key}
  218. ref={(element) => {
  219. buttons.current[tab.key] = element;
  220. }}
  221. type="button"
  222. role="tab"
  223. id={`${name}-tab-${tab.key}`}
  224. aria-selected={selected}
  225. aria-controls={`${name}-panel-${tab.key}`}
  226. tabIndex={selected ? 0 : -1}
  227. onClick={() => setActive(tab.key)}
  228. data-test={`${name}-tab-${tab.key}`}
  229. className={tabClass(selected)}
  230. >
  231. <TabLabel
  232. icon={tab.icon}
  233. label={tab.label}
  234. selected={selected}
  235. count={tab.count}
  236. hasError={tab.hasError}
  237. errorTest={`${name}-tab-error`}
  238. />
  239. </button>
  240. );
  241. })}
  242. </div>
  243. {tabs.map((tab) => (
  244. <div
  245. key={tab.key}
  246. role="tabpanel"
  247. id={`${name}-panel-${tab.key}`}
  248. aria-labelledby={`${name}-tab-${tab.key}`}
  249. data-tab-key={tab.key}
  250. hidden={tab.key !== current}
  251. // Rises in each time it is shown: a hidden element replays its animation when it appears.
  252. className={cn(
  253. 'animate-in p-4 duration-300 fade-in slide-in-from-bottom-2 motion-reduce:animate-none',
  254. panelClassName,
  255. )}
  256. >
  257. {tab.content}
  258. </div>
  259. ))}
  260. </div>
  261. );
  262. }