Model.Util Implementation Guide

Specialized client components that encapsulate model-specific functionality and business logic
Purpose and Role
Model.Util components serve as reusable utility components that encapsulate model-specific functionality. They handle actions, UI interactions, and complex client-side logic while integrating with stores and API signals.
Action Buttons

CRUD operations with built-in state management

1DeleteButton, CreateButton, RefreshButton
Form Wrappers

Specialized form components with validation

1QuickEditForm, StatusToggle
Data Visualizers

Components for displaying model statistics

1StatsPanel, AnalyticsChart
Composite Utilities

Combined functionality components

1FilterPanel, CategorySelector
Basic Implementation
1
2// File: lib/project/Project.Util.tsx
3"use client";
4
5import { useState } from "react";
6import { Button } from "@util/ui";
7import { projectStore } from "./project.store";
8import { projectSignal } from "./project.signal";
9
10export const CreateButton = ({ className }: { className?: string }) => {
11  const { showCreateModal } = projectStore();
12
13  return (
14    <Button 
15      className={className}
16      variant="primary"
17      onClick={showCreateModal}
18    >
19      Create New Project
20    </Button>
21  );
22};
23
24export const DeleteButton = ({ id, name }: { id: string; name: string }) => {
25  const [confirming, setConfirming] = useState(false);
26  const { deleteProject } = projectStore();
27
28  const handleDelete = async () => {
29    await projectSignal.deleteProject(id);
30    setConfirming(false);
31    deleteProject(id);
32  };
33
34  return (
35    <>
36      <Button variant="error" onClick={() => setConfirming(true)}>
37        Delete
38      </Button>
39      
40      {confirming && (
41        <div className="modal modal-open">
42          <div className="modal-box">
43            <h3>Confirm Delete</h3>
44            <p>Delete project {name}?</p>
45            <div className="modal-action">
46              <Button variant="outline" onClick={() => setConfirming(false)}>
47                Cancel
48              </Button>
49              <Button variant="error" onClick={handleDelete}>
50                Confirm
51              </Button>
52            </div>
53          </div>
54        </div>
55      )}
56    </>
57  );
58};
59        
Store Integration
Util components connect to Zustand stores for state management and actions:
useStore:Hook:-

Access store state and actions

1st.use.model()
Selective State:Pattern:-

Extract only needed state properties

1state => ({ item: state.items[id] })
Loading States:Handling:-

Track and display loading indicators

1isUpdating, isRefreshing
1
2export const StatusToggle = ({ id }: { id: string }) => {
3  const { status, updateStatus } = projectStore(
4    (state) => ({
5      status: state.projects[id]?.status,
6      updateStatus: state.updateStatus
7    })
8  );
9
10  const toggle = () => {
11    const newStatus = status === 'active' ? 'inactive' : 'active';
12    updateStatus(id, newStatus);
13  };
14
15  return (
16    <Toggle
17      checked={status === 'active'}
18      onChange={toggle}
19      label={status === 'active' ? 'Active' : 'Inactive'}
20    />
21  );
22};
23        
Performance Optimization
Optimize util components with memoization and lazy loading:
1
2import { memo } from "react";
3
4export const StatCard = memo(({ value, label }: { value: number; label: string }) => (
5  <div className="stats bg-base-200">
6    <div className="stat">
7      <div className="stat-title">{label}</div>
8      <div className="stat-value">{value}</div>
9    </div>
10  </div>
11));
12
13// Lazy load heavy components
14const LazyChart = dynamic(() => import('./ChartComponent'), {
15  loading: () => <div className="loading loading-spinner"></div>
16});
17
18export const AnalyticsPanel = ({ id }: { id: string }) => (
19  <div className="h-96">
20    <LazyChart projectId={id} />
21  </div>
22);
23        
Usage in Application Layers
Util components integrate across all application layers:
1
2// In Views
3import { ProjectUtil } from "../project.Util";
4
5export const ProjectDetailView = ({ id }) => (
6  <div className="p-4">
7    <div className="flex justify-end gap-2 mb-4">
8      <ProjectUtil.EditButton id={id} />
9      <ProjectUtil.ShareButton id={id} />
10      <ProjectUtil.DeleteButton id={id} />
11    </div>
12    {/* ... */}
13  </div>
14);
15
16// In Units
17export const ProjectCard = ({ project }) => (
18  <div className="card bg-base-100 shadow">
19    <div className="card-body">
20      <h3 className="card-title">{project.name}</h3>
21      <ProjectUtil.StatusBadge status={project.status} />
22      <div className="card-actions justify-end">
23        <ProjectUtil.ViewButton id={project.id} />
24      </div>
25    </div>
26  </div>
27);
28
29// In Templates
30export const ProjectForm = () => (
31  <form>
32    {/* Form fields */}
33    <ProjectUtil.CategorySelector />
34    <ProjectUtil.TagsInput />
35    <div className="form-actions">
36      <ProjectUtil.CancelButton />
37      <ProjectUtil.SubmitButton />
38    </div>
39  </form>
40);
41        
Best Practices
Follow these guidelines for maintainable util components:
  • Always include className prop for styling flexibility
  • Handle loading, error, and success states consistently
  • Use TypeScript interfaces for props and state
  • Implement JSDoc comments for documentation
  • Memoize expensive computations and components
1
2/**
3 * Renders a status badge with color coding
4 * 
5 * @param status - Current project status
6 * @param size - Badge size (sm/md/lg)
7 */
8export const StatusBadge = ({ 
9  status, 
10  size = 'md' 
11}: { 
12  status: ProjectStatus; 
13  size?: 'sm' | 'md' | 'lg';
14}) => {
15  const colorMap = {
16    active: 'success',
17    pending: 'warning',
18    archived: 'neutral'
19  };
20
21  return (
22    <span className={`badge badge-${colorMap[status]} badge-${size}`}>
23      {status}
24    </span>
25  );
26};
27        
Summary
Model.Util components are essential building blocks that encapsulate model-specific functionality, promote code reuse, and maintain separation between business logic and presentation. By following these patterns, you create maintainable and consistent utilities throughout your application.
Released under the MIT License
Official Akan.js Consulting onAkansoft
Copyright © 2025 Akan.js. All rights reserved.
System managed bybassman