Chapter 8

Interface interaction

Master UI component design, interaction patterns, responsive design, and user experience principles to build excellent user interfaces.

Use Sequential Thinking to learn AI-driven interface interactions

The application of AI in interface interactions involves multiple layers, usingStructured thinking methodsCan help you systematically master:

1
Basic overview of interface design
Quickly understand Design Tokens, theme systems, and component architecture
2
AI-assisted component development
Component code generation, style optimization, component library selection
3
AI-assisted interaction implementation
State management code generation, form validation, animation effects
4
AI-assisted responsive design and accessibility
Responsive layout generation, accessibility checks, WCAG compliance verification
5
AI-driven performance optimization
Performance bottleneck analysis, optimization plan generation, performance monitoring

Design System

A design system is a set of reusable design standards and component libraries that ensure product consistency and maintainability.

Design Tokens Design Tokens

Design Tokens are the smallest unit of design decisions, and CSS variables centrally manage design elements such as colors, spacing, and fonts.

Color system (OKLCH color space)

Using the OKLCH color space makes it easier to handle color contrast and theme switching. Color definitions in the project:

:root {
  --primary: oklch(0.7 0.15 200);
  --background: oklch(0.09 0 0);
  --foreground: oklch(0.98 0 0);
  --border: oklch(0.25 0 0);
  /* ... more color variables */
}

Spacing system

Tailwind default spacing scale (4px base): 0, 1, 2, 3, 4, 5, 6, 8, 10, 12, 16, 20, 24, 32, 40, 48, 56, 64

0
0px
1
4px
2
8px
4
16px
8
32px
12
48px
16
64px
24
96px

Font System

Font family
--font-sans: 'Geist'
--font-mono: 'Geist Mono'
Font size ratio
xs: 0.75rem, sm: 0.875rem, base: 1rem, lg: 1.125rem, xl: 1.25rem, 2xl: 1.5rem

Rounded corner system

--radius-sm: calc(var(--radius) - 4px)
--radius-md: calc(var(--radius) - 2px)
--radius-lg: var(--radius)
--radius-xl: calc(var(--radius) + 4px)

Theme system

Dark mode implementation

Use next-themes Implement theme switching:

// app/layout.tsx
import { ThemeProvider } from '@/components/theme-provider'

export default function RootLayout({ children }) {
  return (
    <ThemeProvider
      attribute="class"
      defaultTheme="system"
      enableSystem
      disableTransitionOnChange
    >
      {children}
    </ThemeProvider>
  )
}

Theme switching with CSS variables

Pass .dark Class toggle theme variable:

.dark {
  --background: oklch(0.09 0 0);
  --foreground: oklch(0.98 0 0);
  /* All color variables in dark mode */
}

Component Architecture

Atomic design methodology

Atom
Buttons, input fields, labels
Button, Input
Molecule
Search boxes, form fields
SearchBox, FormField
Organization
Navigation bar, forms, card lists
Header, Form, CardList
Template
Page layout structure
DashboardLayout
Page
Final user interface
DashboardPage

Component Variant System (CVA)

Use class-variance-authority Manage component variants:

import { cva, type VariantProps } from 'class-variance-authority'

const buttonVariants = cva(
  'inline-flex items-center justify-center rounded-md',
  {
    variants: {
      variant: {
        default: 'bg-primary text-primary-foreground',
        destructive: 'bg-destructive text-destructive-foreground',
        outline: 'border border-input',
      },
      size: {
        default: 'h-10 px-4 py-2',
        sm: 'h-9 rounded-md px-3',
        lg: 'h-11 rounded-md px-8',
      },
    },
    defaultVariants: {
      variant: 'default',
      size: 'default',
    },
  }
)

Best practices for AI in interface interactions

Use AI to improve front-end UI development efficiency, with AI-assisted practices across the full workflow from component design to performance optimization.

AI-assisted component development

Use AI to generate component code

Describe the component requirements to AI and have it generate a complete React/Next.js component:

Prompt template:

I need to create a user card component with the following features:
1. Display the user's avatar, name, and email
2. Support clicking to view details
3. Use Tailwind CSS styles
4. Support dark mode
5. Responsive design (mobile and desktop)
6. Use TypeScript
7. Follow shadcn/ui design guidelines

Please generate the complete component code, including:
- Type definitions
- Props interface
- Style class names
- Responsive breakpoints
- Accessibility attributes

AI-generated component example

// components/user-card.tsx
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { Card, CardContent } from '@/components/ui/card'

interface UserCardProps {
  name: string
  email: string
  avatar?: string
  onClick?: () => void
}

export function UserCard({ name, email, avatar, onClick }: UserCardProps) {
  const initials = name
    .split(' ')
    .map(n => n[0])
    .join('')
    .toUpperCase()
    .slice(0, 2)

  return (
    <Card 
      className="cursor-pointer transition-shadow hover:shadow-md"
      onClick={onClick}
      role="button"
      tabIndex={0}
      onKeyDown={(e) => {
        if (e.key === 'Enter' || e.key === ' ') {
          onClick?.()
        }
      }}
    >
      <CardContent className="p-4 flex items-center gap-4">
        <Avatar className="h-12 w-12">
          <AvatarImage src={avatar} alt={name} />
          <AvatarFallback>{initials}</AvatarFallback>
        </Avatar>
        <div className="flex-1 min-w-0">
          <h3 className="font-semibold text-foreground truncate">{name}</h3>
          <p className="text-sm text-muted-foreground truncate">{email}</p>
        </div>
      </CardContent>
    </Card>
  )
}

AI-assisted style optimization

Use AI to optimize Tailwind CSS class names and generate more concise, efficient styles:

Prompt:

Optimize the following Tailwind CSS class names to make them more concise and efficient:

Current code:
<div className="flex flex-row items-center justify-between p-4 m-2 bg-white dark:bg-gray-800 rounded-lg shadow-sm hover:shadow-md transition-shadow duration-200">

Please:
1. Merge duplicate class names
2. Use a more concise syntax
3. Ensure responsive and dark mode support
4. Maintain the same visual effect

Selecting an AI-assisted component library

Prompt:

I need to choose a component library for a Next.js 16 + TypeScript project. The requirements are:
1. Dark mode support
2. High customizability
3. Type safety
4. Excellent performance
5. An active community

Please compare the following component libraries:
- shadcn/ui
- Material-UI (MUI)
- Ant Design
- Chakra UI

Provide a recommendation and the reasons, and explain how to integrate it into a Next.js project.

UI component design

Componentization is a core idea in modern front-end development, building complex user interfaces by combining reusable components.

Advanced Tailwind CSS configuration

Configuration file structure

// tailwind.config.ts
import type { Config } from 'tailwindcss'

const config: Config = {
  content: [
    './app/**/*.{js,ts,jsx,tsx,mdx}',
    './components/**/*.{js,ts,jsx,tsx}',
  ],
  theme: {
    extend: {
      colors: {
        background: 'var(--background)',
        foreground: 'var(--foreground)',
        // Use CSS variables
      },
      borderRadius: {
        lg: 'var(--radius)',
        md: 'calc(var(--radius) - 2px)',
        sm: 'calc(var(--radius) - 4px)',
      },
    },
  },
  plugins: [],
}

export default config

Custom tool class

// Add custom utility classes in globals.css
@layer utilities {
  .text-balance {
    text-wrap: balance;
  }
  
  .scrollbar-hide {
    -ms-overflow-style: none;
    scrollbar-width: none;
  }
  
  .scrollbar-hide::-webkit-scrollbar {
    display: none;
  }
}

Custom responsive breakpoints

// tailwind.config.ts
theme: {
  screens: {
    'xs': '475px',
    'sm': '640px',
    'md': '768px',
    'lg': '1024px',
    'xl': '1280px',
    '2xl': '1536px',
  },
}

Dark mode settings

Use dark: Prefix:

<div className="bg-white dark:bg-gray-900 text-gray-900 dark:text-white">
  {/* Content */}
</div>

Component library comparison and selection

Component LibraryFeaturesApplicable scenarios
shadcn/uiCopy-pasteable, fully controllable, based on Radix UIHighly customized projects, Next.js projects
Material-UIRich components, comprehensive documentation, Material DesignEnterprise applications, rapid prototyping
Ant DesignEnterprise-grade components, admin/back-office applications, Chinese documentationMiddle-tier systems, management platforms
Chakra UISimple, modular, TypeScript supportModern web applications, projects that need flexibility

Interactive mode

Good interaction design makes user operations smoother and more intuitive. Master state management, form handling, and animation techniques.

Detailed Guide to State Management

useState Best Practices

// Use functional updates to avoid closure issues
const [count, setCount] = useState(0)

// Correct: use functional updates
setCount(prev => prev + 1)

// Avoid: directly depending on state
setCount(count + 1) // may be inaccurate

// Use useReducer for complex state
const [state, dispatch] = useReducer(reducer, initialState)

Best practices for form handling

Form validation example

// Complete form component example
'use client'

import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage } from '@/components/ui/form'

const formSchema = z.object({
  username: z.string().min(2, 'Username must be at least 2 characters'),
  email: z.string().email('Invalid email address'),
})

export function UserForm() {
  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      username: '',
      email: '',
    },
  })

  function onSubmit(values: z.infer<typeof formSchema>) {
    console.log(values)
  }

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
        <FormField
          control={form.control}
          name="username"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Username</FormLabel>
              <FormControl>
                <Input {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <Button type="submit">Submit</Button>
      </form>
    </Form>
  )
}

Form performance optimization

  • Use mode: 'onBlur' Reduce verification cycles
  • Using complex forms useFieldArray Managing Dynamic Fields
  • Use of large forms shouldUnregister Optimize memory

User feedback system

Toast notifications

import { toast } from 'sonner'

toast.success('Operation succeeded')
toast.error('Operation failed')
toast.info('Information')

Loading state

// Skeleton loading
<Skeleton className="h-4 w-[250px]" />

// Spinner
<Loader2 className="h-4 w-4 animate-spin" />

Animations and transitions

Tailwind animations

// Use tailwindcss-animate
<div className="animate-in fade-in slide-in-from-top-4">
  {/* Content */}
</div>

// Common animation classes
animate-in          // Enter animation
animate-out         // Exit animation
fade-in             // Fade in
slide-in-from-top  // Slide in from top
duration-300        // Duration

Performance considerations

  • Use transform and opacity Trigger GPU acceleration
  • Avoid animations widthheight attributes such as
  • Use will-change Browser optimization tips

Responsive design

Ensure the interface provides a good user experience across different devices. Adopt a mobile-first strategy and use flexible layout techniques.

Mobile-first strategy

Mobile Design Principles

  • Design for mobile first, then gradually enhance the desktop experience
  • Simplify mobile interactions and reduce the number of steps
  • Optimize touch target size (minimum 44x44px)
  • Reduce mobile content and highlight core features

Mobile navigation patterns

Bottom navigation
Suitable for the main feature entry point
Hamburger menu
Suitable for secondary features
Tab
Suitable for content classification

Layout techniques

Advanced Flexbox usage

// Responsive Flexbox
<div className="flex flex-col md:flex-row gap-4">
  <div className="flex-1">Content 1</div>
  <div className="flex-1">Content 2</div>
</div>

// Alignment
<div className="flex items-center justify-between">
  {/* Vertically centered, horizontally space-between */}
</div>

Breakpoint strategy

sm
≥640px
Small-screen devices
md
≥768px
Tablet
lg
≥1024px
Laptop
xl
≥1280px
Desktop
2xl
≥1536px
Large screen
// Best practices for breakpoints
// Mobile-first: default styles apply to mobile
<div className="text-sm md:text-base lg:text-lg">
  {/* Gradually enhance from small screens to large screens */}
</div>

// Avoid: desktop-first (not recommended)
<div className="text-lg md:text-base sm:text-sm">
  {/* This increases the burden on mobile devices */}
</div>

Mobile optimization

Viewport configuration

// app/layout.tsx
export const metadata = {
  viewport: {
    width: 'device-width',
    initialScale: 1,
    maximumScale: 5,
  },
}

Touch event handling

  • Use touch-action Optimize touch response
  • Avoid hover Accidental taps on mobile state
  • Use @media (hover: hover) Detect whether the device supports hovering

Accessibility

Accessibility ensures that all users can use your app, including users who rely on assistive technologies. Follow WCAG standards to make your product more inclusive.

WCAG standard

WCAG 2.1 level

Level A
Minimum requirements, basic accessibility
Level AA (recommended)
The standard most websites should meet
AAA level
Highest standards, special requirements

Key principles (POUR)

Perceivable
Information can be perceived in various ways
Actionable
UI components and navigation are operable
Understandable
Information and operations are understandable
Can be robust
Content can be interpreted by various assistive technologies

Keyboard navigation

Tab order management

// Use tabIndex to control Tab order
<button tabIndex={1}>First</button>
<button tabIndex={2}>Second</button>

// Skip non-interactive elements
<div tabIndex={-1}>Skip this element</div>

// Remove from the Tab order (not recommended unless necessary)
<button tabIndex={-1}>Cannot be accessed via Tab</button>

Focus management

// Focus Trap - used in modals
import { FocusTrap } from '@radix-ui/react-focus-trap'

<FocusTrap>
  <Dialog>
    {/* Focus is constrained within the dialog */}
  </Dialog>
</FocusTrap>

// Focus-visible styles
<button className="focus-visible:ring-2 focus-visible:ring-primary">
  {/* Show focus ring during keyboard navigation */}
</button>

Keyboard shortcut support

  • Enter/Space: activate a button or link
  • Esc: close the modal or menu
  • Arrow Keys: navigate list or menu items
  • Tab: Move between focusable elements

Screen reader support

Using ARIA labels

// aria-label: provides a label for an element
<button aria-label="Close dialog">
  <X />
</button>

// aria-labelledby: references the ID of another element
<div aria-labelledby="dialog-title">
  <h2 id="dialog-title">Dialog title</h2>
</div>

// aria-describedby: provides additional description
<input 
  aria-describedby="email-help"
  aria-invalid={hasError}
/>
<span id="email-help">Please enter a valid email address</span>

Semantic HTML

// Use semantic tags
<nav>Navigation</nav>
<main>Main content</main>
<article>Article</article>
<section>Section</section>
<aside>Sidebar</aside>
<header>Header</header>
<footer>Footer</footer>

// Avoid: using div instead of semantic tags
<div className="nav"> {/* Not recommended */}
<nav> {/* Recommended */}

Role definition

// Use the role attribute (when semantic tags are unavailable)
<div role="button" tabIndex={0} onClick={handleClick}>
  Custom button
</div>

<div role="alert" aria-live="polite">
  Important notice
</div>

<div role="dialog" aria-modal="true" aria-labelledby="dialog-title">
  {/* Modal dialog */}
</div>

Color contrast

WCAG AA standard

Normal text
Contrast ≥ 4.5:1
Large text (18px+ or 14px+ bold)
Contrast ratio ≥ 3:1

Tool check

  • WebAIM Contrast Checker: online contrast checking tool
  • Lighthouse: built into Chrome DevTools
  • axe DevTools: Browser Extension

Do not rely on color to convey information

// Error: use color only to indicate status
<span className="text-red-500">Error</span>

// Correct: color + icon/text
<span className="text-red-500 flex items-center gap-1">
  <AlertCircle />
  Error: Please enter a valid value
</span>

Accessibility testing

Automated testing tools

axe
npm install @axe-core/react
Lighthouse
Chrome DevTools
WAVE
Browser extension

Manual testing process

  1. Navigate the entire application using only the keyboard
  2. Test using screen readers (NVDA, JAWS, VoiceOver)
  3. Check color contrast
  4. Verify that all images have alt text
  5. Test form error message

Keyboard test checklist

  • All interactive elements can be accessed via Tab
  • The focus order logic is reasonable
  • Focus visible (with focus ring)
  • The modal can be closed with Esc
  • The menu can be navigated with the arrow keys

Performance optimization

Performance directly affects the user experience. Optimize rendering performance, resource loading, and runtime performance to ensure the app responds quickly.

Rendering performance

React rendering optimization

// Use memo to avoid unnecessary re-renders
const ExpensiveComponent = React.memo(({ data }) => {
  return <div>{/* complex rendering */}</div>
})

// Use useMemo to cache computed results
const expensiveValue = useMemo(() => {
  return computeExpensiveValue(a, b)
}, [a, b])

// Use useCallback to cache functions
const handleClick = useCallback(() => {
  doSomething(id)
}, [id])

Virtual scrolling

For large lists, use virtual scrolling to render only visible items:

// Use react-window or react-virtualized
import { FixedSizeList } from 'react-window'

<FixedSizeList
  height={600}
  itemCount={10000}
  itemSize={50}
  width="100%"
>
  {Row}
</FixedSizeList>

Code splitting

// Dynamically import component
import dynamic from 'next/dynamic'

const HeavyComponent = dynamic(() => import('./HeavyComponent'), {
  loading: () => <Skeleton />,
  ssr: false, // If you need to disable SSR
})

// Route-level code splitting (handled automatically by Next.js)
// app/dashboard/page.tsx will be split automatically

Resource optimization

Image optimization

// Automatic optimization by the Next.js Image component
import Image from 'next/image'

<Image
  src="/hero.jpg"
  alt="Hero"
  width={1200}
  height={600}
  priority // above-the-fold image
  loading="lazy" // below-the-fold image
  placeholder="blur" // blurred placeholder
/>

// Supports modern formats such as WebP and AVIF
// Automatically generates responsive images

Font optimization

// Use next/font to optimize fonts
import { GeistSans } from 'next/font/google'

const geistSans = GeistSans({
  subsets: ['latin'],
  display: 'swap', // Font loading strategy
  preload: true,
})

// Font subsetting, load only the required characters

Resource preloading

// Preconnect third-party domains
<link rel="preconnect" href="https://fonts.googleapis.com" />

// Preload critical resources
<link rel="preload" href="/fonts/geist.woff2" as="font" />

// Prefetch next-page resources
<link rel="prefetch" href="/dashboard" />

Runtime performance

Bundle size optimization

  • Use bundle analyzer Analyze bundle size
  • Import libraries as needed (import { debounce } from 'lodash-es'
  • Remove unused dependencies

Tree Shaking

Next.js and modern bundlers automatically perform tree shaking to remove unused code.

Performance monitoring

Core Web Vitals

LCP
Largest Contentful Paint < 2.5s
FID
First input delay < 100ms
CLS
Cumulative Layout Shift < 0.1

Performance analysis tools

  • React DevTools Profiler: analyze component rendering performance
  • Lighthouse: Chrome DevTools performance audit
  • Web Vitals Extension: Real-time monitoring of Core Web Vitals

Practical examples

Learn how to build high-quality UI components and interactions through real code examples.

Complete form component example

'use client'

import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage } from '@/components/ui/form'
import { toast } from 'sonner'

const formSchema = z.object({
  name: z.string().min(2, 'Name must be at least 2 characters'),
  email: z.string().email('Invalid email address'),
  age: z.number().min(18, 'Age must be greater than 18').max(100),
})

export function UserForm() {
  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      name: '',
      email: '',
      age: 18,
    },
  })

  async function onSubmit(values: z.infer<typeof formSchema>) {
    try {
      await saveUser(values)
      toast.success('User created successfully')
      form.reset()
    } catch (error) {
      toast.error('Creation failed, please try again')
    }
  }

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
        <FormField
          control={form.control}
          name="name"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Name</FormLabel>
              <FormControl>
                <Input placeholder="Please enter your name" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <Button type="submit" disabled={form.formState.isSubmitting}>
          {form.formState.isSubmitting ? 'Submitting...' : 'Submit'}
        </Button>
      </form>
    </Form>
  )
}

Learning outcomes

After completing this chapter, you will:

  • 1Understand the basics of design systems and master Design Tokens, theme systems, and component architecture
  • 2Proficient in Tailwind CSS and shadcn/ui, able to configure and customize component libraries
  • 3Master state management, form handling, and animation techniques to build a smooth interactive experience
  • 4Master responsive design methods, using a mobile-first strategy and modern layout techniques
  • 5Understand accessibility standards (WCAG) and be able to implement keyboard navigation and screen reader support
  • 6Master performance optimization techniques, including rendering optimization, resource loading, and performance monitoring
  • 7Able to build complete form components, responsive layouts, and interactive features