feat: first draft

This commit is contained in:
2025-01-25 20:39:55 +01:00
parent 78c69dbc1a
commit 06fbbab24d
53 changed files with 13416 additions and 123 deletions

14
.eslintrc.json Normal file
View File

@@ -0,0 +1,14 @@
{
"extends": [
"next/core-web-vitals",
"plugin:@typescript-eslint/recommended",
"prettier"
],
"plugins": ["@typescript-eslint", "prettier"],
"rules": {
"prettier/prettier": "error",
"@typescript-eslint/no-unused-vars": "error",
"@typescript-eslint/no-explicit-any": "error",
"react-hooks/exhaustive-deps": "warn"
}
}

155
.gitignore vendored
View File

@@ -1,130 +1,41 @@
# Logs
logs
*.log
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# env files (can opt-in for committing if needed)
.env*
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# vercel
.vercel
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
# typescript
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
next-env.d.ts

7
.prettierrc Normal file
View File

@@ -0,0 +1,7 @@
{
"semi": true,
"trailingComma": "es5",
"singleQuote": true,
"tabWidth": 2,
"useTabs": false
}

127
README.md
View File

@@ -1 +1,126 @@
# blue-ocean
# Blue Ocean Strategy Analysis Tool
A comprehensive web application for visualizing and analyzing business strategies using the Blue Ocean Strategy framework. This tool helps strategists and business analysts create, validate, and visualize market-creating strategies through an interactive interface.
## Features
### 💹 Strategy Canvas
- Interactive line chart visualization
- Factor management with market vs. idea comparison
- Notes and annotations for each factor
- Drag-and-drop factor reordering
### 🎯 Four Actions Framework
- Organize strategic factors into Eliminate/Reduce/Raise/Create
- Link factors with strategy canvas
- Notes per action category
- Color-coded sections for clarity
### 🛣️ Six Paths Framework
- Analysis across alternative industries
- Strategic group evaluation
- Buyer chain exploration
- Complementary products/services assessment
- Functional/emotional appeal analysis
- Time trend tracking
### 📊 Buyer Utility Map
- Interactive grid visualization
- Toggle opportunities
- Notes per cell
- Six stages × six utility levers
### 💰 Price Corridor
- Target price setting
- Competitor price tracking
- Visual price band analysis
- Three-tier market segmentation
### ✅ Strategy Validation
- Non-customer analysis
- Strategic sequence validation
- Implementation notes
- Progress tracking
## Technical Stack
- **Framework**: Next.js 14 with App Router
- **Language**: TypeScript 5
- **Styling**: Tailwind CSS + shadcn/ui
- **Storage**: Redis
- **Charts**: Recharts
- **Utilities**: Lodash
## Getting Started
1. Clone the repository
```bash
git clone https://github.com/riccardosenica/blue-ocean.git
cd blue-ocean
```
2. Install dependencies
```bash
yarn install
```
3. Set up environment variables
```bash
cp .env.example .env.local
```
4. Update the following variables in `.env.local`:
```
KV_REST_API_URL=your_kv_url
KV_REST_API_TOKEN=your_kv_token
```
5. Run the development server
```bash
yarn dev
```
6. Open [http://localhost:3000](http://localhost:3000) in your browser
## State Management
The application uses React Context for state management with the following structure:
- Strategy Canvas data
- Four Actions framework entries
- Six Paths analysis
- Utility Map toggles and notes
- Price Corridor data
- Validation checkpoints
## Storage
- Primary storage in browser's localStorage
- Backup functionality to Redis
- Automatic state persistence
- Import/Export capabilities
## Development
### Available Scripts
- `yarn dev`: Start development server
- `yarn build`: Build for production
- `yarn start`: Start production server
- `yarn lint`: Run ESLint
- `yarn typecheck`: Run TypeScript compiler
## Acknowledgments
- Blue Ocean Strategy by W. Chan Kim and Renée Mauborgne

15
app/api/backup/route.ts Normal file
View File

@@ -0,0 +1,15 @@
import { redis } from '@utils/redis';
import { NextResponse } from 'next/server';
import crypto from 'crypto';
export async function POST(req: Request) {
try {
const { state } = await req.json();
const key = crypto.randomBytes(8).toString('hex');
await redis.set(key, JSON.stringify(state));
return NextResponse.json({ success: true, key });
} catch (error) {
console.error(error);
return NextResponse.json({ error: 'Backup failed' }, { status: 500 });
}
}

35
app/api/restore/route.ts Normal file
View File

@@ -0,0 +1,35 @@
import { redis } from '@utils/redis';
import { validateState } from '@utils/validateState';
import { NextResponse } from 'next/server';
export async function GET(req: Request) {
try {
const { searchParams } = new URL(req.url);
const key = searchParams.get('key');
if (!key) {
return NextResponse.json({ error: 'No key provided' }, { status: 400 });
}
const state = await redis.get(key);
if (!state) {
return NextResponse.json(
{ error: 'No data found for this key' },
{ status: 404 }
);
}
const validatedState = validateState(state);
return NextResponse.json({ data: validatedState });
} catch (error) {
console.error('Restore operation failed:', error);
return NextResponse.json(
{
error: 'Restore failed',
details: error instanceof Error ? error.message : 'Unknown error',
},
{ status: 500 }
);
}
}

BIN
app/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

193
app/globals.css Normal file
View File

@@ -0,0 +1,193 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--background: 190 95% 95%;
--foreground: 200 50% 3%;
--card: 0 0% 100%;
--card-foreground: 200 50% 3%;
--popover: 0 0% 100%;
--popover-foreground: 200 50% 3%;
--primary: 190 100% 50%; /* Bright cyan */
--primary-foreground: 0 0% 100%;
--secondary: 185 100% 85%;
--secondary-foreground: 200 50% 3%;
--muted: 185 35% 88%;
--muted-foreground: 200 40% 40%;
--accent: 170 85% 45%; /* Bold turquoise */
--accent-foreground: 200 50% 3%;
--destructive: 345 84% 60%; /* Coral red */
--destructive-foreground: 210 40% 98%;
--border: 190 95% 85%;
--input: 190 95% 85%;
--ring: 190 100% 50%;
--radius: 0.5rem;
}
.dark {
--background: 200 50% 3%;
--foreground: 210 40% 98%;
--card: 200 50% 3%;
--card-foreground: 210 40% 98%;
--popover: 200 50% 3%;
--popover-foreground: 210 40% 98%;
--primary: 190 100% 50%;
--primary-foreground: 200 50% 3%;
--secondary: 200 34% 20%;
--secondary-foreground: 210 40% 98%;
--muted: 200 34% 20%;
--muted-foreground: 200 40% 60%;
--accent: 170 85% 45%;
--accent-foreground: 210 40% 98%;
--destructive: 345 62% 40%;
--destructive-foreground: 210 40% 98%;
--border: 200 34% 20%;
--input: 200 34% 20%;
--ring: 190 100% 50%;
}
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
background: linear-gradient(
180deg,
hsl(190 95% 95%) 0%,
hsl(185 90% 92%) 100%
);
min-height: 100vh;
}
/* Animated waves for the header */
@keyframes wave {
0% {
transform: translateX(0) translateZ(0) scaleY(1);
}
50% {
transform: translateX(-25%) translateZ(0) scaleY(0.8);
}
100% {
transform: translateX(-50%) translateZ(0) scaleY(1);
}
}
@keyframes swell {
0%,
100% {
transform: translateY(-12px);
}
50% {
transform: translateY(12px);
}
}
.wave {
background: url("data:image/svg+xml,%3Csvg viewBox='0 0 800 88.7' width='800' height='88.7' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M800 56.9c-155.5 0-204.9-50-405.5-49.9-200 0-250 49.9-394.5 49.9v31.8h800v-.2-31.6z' fill='%23ffffff33'/%3E%3C/svg%3E");
position: absolute;
width: 200%;
height: 100%;
animation: wave 12s linear infinite;
transform-origin: center bottom;
}
.wave-2 {
animation: wave 18s linear reverse infinite;
opacity: 0.5;
}
.wave-3 {
animation: wave 20s linear infinite;
opacity: 0.2;
}
.swell {
position: absolute;
width: 100%;
height: 100%;
animation: swell 7s ease -1.25s infinite;
transform-origin: center bottom;
}
/* Glass effect for cards */
.glass-card {
background: rgba(255, 255, 255, 0.7);
backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.2);
box-shadow: 0 8px 32px rgba(31, 38, 135, 0.15);
}
.dark .glass-card {
background: rgba(0, 0, 0, 0.7);
border: 1px solid rgba(255, 255, 255, 0.1);
}
/* Gradient borders */
.gradient-border {
position: relative;
border: none;
}
.gradient-border::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
border-radius: inherit;
padding: 2px;
background: linear-gradient(
45deg,
hsl(190 100% 50%),
hsl(170 85% 45%),
hsl(190 100% 50%)
);
-webkit-mask:
linear-gradient(#fff 0 0) content-box,
linear-gradient(#fff 0 0);
mask:
linear-gradient(#fff 0 0) content-box,
linear-gradient(#fff 0 0);
-webkit-mask-composite: xor;
mask-composite: exclude;
}
}
.tabs-list {
@apply inline-flex h-12 items-center justify-center rounded-lg bg-white p-1 shadow-lg dark:bg-gray-800/50 backdrop-blur-sm;
}
.tab {
@apply inline-flex items-center justify-center whitespace-nowrap rounded-md px-6 py-2.5 text-sm font-medium ring-offset-white transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-950 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 dark:ring-offset-slate-950 dark:focus-visible:ring-slate-300;
}
.tab[data-state='active'] {
@apply bg-gradient-to-r from-cyan-500 to-blue-500 text-white shadow-sm;
}
.tab[data-state='inactive'] {
@apply text-slate-500 hover:text-slate-900 dark:text-slate-400 dark:hover:text-slate-50;
}

45
app/layout.tsx Normal file
View File

@@ -0,0 +1,45 @@
import { Inter } from 'next/font/google';
import './globals.css';
import { ThemeProvider } from '@components/ThemeProvider';
import type { Metadata } from 'next';
import Header from '@components/Header';
import { StateProvider } from '@contexts/state/StateProvider';
const inter = Inter({ subsets: ['latin'] });
export const metadata: Metadata = {
title: `Blue ocean strategy tool by ${process.env.NEXT_PUBLIC_BRAND_NAME}`,
description:
'Web application for visualizing and analyzing business strategies using the Blue Ocean Strategy framework',
keywords: 'blue ocean, strategy, business, visualization, analysis',
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en" suppressHydrationWarning>
<body className={inter.className}>
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
<StateProvider>
<div className="min-h-screen bg-background transition-colors">
<Header />
<main className="container max-w-screen-xl mx-auto px-4 py-6">
<div className="flex justify-center">
<div className="w-full">{children}</div>
</div>
</main>
</div>
</StateProvider>
</ThemeProvider>
</body>
</html>
);
}

47
app/page.tsx Normal file
View File

@@ -0,0 +1,47 @@
'use client';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@components/ui/tabs';
import StrategyCanvas from '@components/core/StrategyCanvas';
import FourActions from '@components/core/FourActions';
import SixPaths from '@components/core/SixPaths';
import UtilityMap from '@components/core/UtilityMap';
import PriceCorridor from '@components/core/PriceCorridor';
import Validation from '@components/core/Validation';
import BackupControls from '@components/BackupControls';
export default function Home() {
return (
<>
<BackupControls />
<Tabs defaultValue="canvas" className="w-full">
<TabsList>
<TabsTrigger value="canvas">Strategy Canvas</TabsTrigger>
<TabsTrigger value="actions">Four Actions</TabsTrigger>
<TabsTrigger value="paths">Six Paths</TabsTrigger>
<TabsTrigger value="utility">Utility Map</TabsTrigger>
<TabsTrigger value="price">Price Corridor</TabsTrigger>
<TabsTrigger value="validation">Validation</TabsTrigger>
</TabsList>
<TabsContent value="canvas">
<StrategyCanvas />
</TabsContent>
<TabsContent value="actions">
<FourActions />
</TabsContent>
<TabsContent value="paths">
<SixPaths />
</TabsContent>
<TabsContent value="utility">
<UtilityMap />
</TabsContent>
<TabsContent value="price">
<PriceCorridor />
</TabsContent>
<TabsContent value="validation">
<Validation />
</TabsContent>
</Tabs>
</>
);
}

21
components.json Normal file
View File

@@ -0,0 +1,21 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "tailwind.config.ts",
"css": "app/globals.css",
"baseColor": "zinc",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}

View File

@@ -0,0 +1,133 @@
import { useState } from 'react';
import { Loader2, Copy, Check, RotateCcw } from 'lucide-react';
import { Button } from '@components/ui/button';
import { Input } from '@components/ui/input';
import { Card, CardContent, CardHeader, CardTitle } from '@components/ui/card';
import { Alert, AlertDescription } from '@components/ui/alert';
import { useStorage } from '@utils/useStorage';
import { useGlobalState } from '@contexts/state/StateContext';
export function LoadingSpinner() {
return <Loader2 className="h-4 w-4 animate-spin" />;
}
export default function BackupControls() {
const [key, setKey] = useState('');
const [backupKey, setBackupKey] = useState('');
const [isBackingUp, setIsBackingUp] = useState(false);
const [isRestoring, setIsRestoring] = useState(false);
const [copied, setCopied] = useState(false);
const [error, setError] = useState<string | null>(null);
const { state, dispatch, resetState } = useGlobalState();
const { backupState, restoreState } = useStorage();
const handleBackup = async () => {
setIsBackingUp(true);
setError(null);
try {
const result = await backupState(state);
if (result?.key) {
setBackupKey(result.key);
}
} catch (error) {
console.error(error);
setError('Failed to backup data. Please try again.');
} finally {
setIsBackingUp(false);
}
};
const handleRestore = async () => {
if (!key) {
setError('Please enter a key');
return;
}
setIsRestoring(true);
setError(null);
try {
const restored = await restoreState(key);
if (restored) {
dispatch({ type: 'SET_STATE', payload: restored });
setKey('');
} else {
setError('No data found for this key');
}
} catch (error) {
console.error(error);
setError('Failed to restore data. Please check your key and try again.');
} finally {
setIsRestoring(false);
}
};
const copyKey = async () => {
try {
await navigator.clipboard.writeText(backupKey);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch (error) {
console.error(error);
setError('Failed to copy key to clipboard');
}
};
return (
<Card className="mb-6">
<CardHeader>
<CardTitle>Backup Controls</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="flex gap-4">
<Button onClick={handleBackup} disabled={isBackingUp}>
{isBackingUp ? <LoadingSpinner /> : 'Backup data'}
</Button>
<Button onClick={resetState} variant="outline">
<RotateCcw className="h-4 w-4 mr-2" />
Reset data
</Button>
{backupKey && (
<div className="flex-1 flex items-center rounded-md border bg-card text-card-foreground h-9 px-3">
<div className="flex items-center gap-2 flex-1">
<span className="text-sm font-medium">Your backup key:</span>
<code className="bg-muted px-1.5 rounded text-sm">
{backupKey}
</code>
</div>
<Button
variant="ghost"
size="icon"
onClick={copyKey}
disabled={copied}
className="h-7 w-7"
>
{copied ? (
<Check className="h-4 w-4" />
) : (
<Copy className="h-4 w-4" />
)}
</Button>
</div>
)}
</div>
<div className="flex gap-4">
<Input
placeholder="Enter backup key"
value={key}
onChange={(e) => setKey(e.target.value)}
disabled={isRestoring}
/>
<Button onClick={handleRestore} disabled={isRestoring}>
{isRestoring ? <LoadingSpinner /> : 'Restore data'}
</Button>
</div>
</CardContent>
</Card>
);
}

34
components/Header.tsx Normal file
View File

@@ -0,0 +1,34 @@
import React from 'react';
import { ThemeToggle } from '@components/ThemeToggle';
import { WavesIcon } from 'lucide-react';
export default function Header() {
return (
<header className="relative overflow-hidden bg-gradient-to-r from-cyan-500 via-blue-500 to-cyan-500 h-32">
<div className="absolute inset-0 overflow-hidden">
<div className="swell">
<div className="wave"></div>
<div className="wave wave-2"></div>
<div className="wave wave-3"></div>
</div>
</div>
<div className="relative px-4 h-full">
<div className="absolute right-4 top-3">
<ThemeToggle />
</div>
<div className="container max-w-4xl mx-auto h-full flex flex-col items-center justify-center text-white">
<div className="flex items-center gap-2">
<WavesIcon className="h-6 w-6" />
<h1 className="text-2xl font-bold tracking-tight">
Blue Ocean Strategy
</h1>
</div>
<p className="text-cyan-100 text-sm">
Navigate to new market spaces and create uncontested growth
</p>
</div>
</div>
</header>
);
}

View File

@@ -0,0 +1,12 @@
import React from 'react';
import { ThemeProvider as NextThemesProvider } from 'next-themes';
export function ThemeProvider({
children,
...props
}: {
children: React.ReactNode;
[key: string]: unknown;
}) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>;
}

View File

@@ -0,0 +1,37 @@
'use client';
import React from 'react';
import { Moon, Sun } from 'lucide-react';
import { useTheme } from 'next-themes';
import { Button } from '@components/ui/button';
export function ThemeToggle() {
const { setTheme, resolvedTheme } = useTheme();
const [mounted, setMounted] = React.useState(false);
React.useEffect(() => {
setMounted(true);
}, []);
if (!mounted) {
return (
<Button variant="ghost" size="icon" className="w-9 px-0">
<Sun className="h-5 w-5 opacity-50" />
</Button>
);
}
return (
<Button
variant="ghost"
size="icon"
onClick={() => setTheme(resolvedTheme === 'dark' ? 'light' : 'dark')}
className="w-9 px-0"
>
<Sun className="h-5 w-5 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
<Moon className="absolute h-5 w-5 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
<span className="sr-only">Toggle theme</span>
</Button>
);
}

View File

@@ -0,0 +1,124 @@
import React, { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@components/ui/card';
import { Button } from '@components/ui/button';
import { Input } from '@components/ui/input';
import { useGlobalState } from '@contexts/state/StateContext';
import { Trash2, Plus } from 'lucide-react';
const FourActions = () => {
const { state, dispatch } = useGlobalState();
const [newItems, setNewItems] = useState({
eliminate: '',
reduce: '',
raise: '',
create: '',
});
const addItem = (actionType: keyof typeof newItems) => {
if (!newItems[actionType]) return;
dispatch({
type: 'ADD_ACTION',
payload: {
actionType,
value: newItems[actionType],
},
});
setNewItems((prev) => ({ ...prev, [actionType]: '' }));
};
const removeItem = (
actionType: keyof typeof state.fourActions,
index: number
) => {
dispatch({
type: 'SET_STATE',
payload: {
...state,
fourActions: {
...state.fourActions,
[actionType]: state.fourActions[actionType].filter(
(_, i) => i !== index
),
},
},
});
};
const renderActionSection = (
title: string,
actionType: keyof typeof state.fourActions,
description: string,
colorClasses: string
) => (
<Card className={`${colorClasses} border-2`}>
<CardHeader>
<CardTitle>{title}</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground mb-4">{description}</p>
<div className="flex gap-2 mb-4">
<Input
placeholder={`Add ${title.toLowerCase()} factor...`}
value={newItems[actionType]}
onChange={(e) =>
setNewItems((prev) => ({ ...prev, [actionType]: e.target.value }))
}
className="flex-1"
/>
<Button onClick={() => addItem(actionType)} variant="secondary">
<Plus className="h-4 w-4" />
</Button>
</div>
<div className="space-y-2">
{state.fourActions[actionType].map((item, index) => (
<div
key={index}
className="flex items-center gap-2 p-2 bg-background rounded-lg border"
>
<span className="flex-1">{item}</span>
<Button
variant="ghost"
size="sm"
onClick={() => removeItem(actionType, index)}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
))}
</div>
</CardContent>
</Card>
);
return (
<div className="grid grid-cols-2 gap-4">
{renderActionSection(
'Eliminate',
'eliminate',
'Which factors should be eliminated?',
'border-red-500/50 dark:border-red-500/30 bg-red-50/50 dark:bg-red-950/10'
)}
{renderActionSection(
'Reduce',
'reduce',
'Which factors should be reduced well below the industry standard?',
'border-yellow-500/50 dark:border-yellow-500/30 bg-yellow-50/50 dark:bg-yellow-950/10'
)}
{renderActionSection(
'Raise',
'raise',
'Which factors should be raised well above the industry standard?',
'border-green-500/50 dark:border-green-500/30 bg-green-50/50 dark:bg-green-950/10'
)}
{renderActionSection(
'Create',
'create',
'Which factors should be created that the industry has never offered?',
'border-blue-500/50 dark:border-blue-500/30 bg-blue-50/50 dark:bg-blue-950/10'
)}
</div>
);
};
export default FourActions;

View File

@@ -0,0 +1,301 @@
import React, { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@components/ui/card';
import { Button } from '@components/ui/button';
import { Input } from '@components/ui/input';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@components/ui/select';
import { useGlobalState } from '@contexts/state/StateContext';
import { Trash2, Plus } from 'lucide-react';
import {
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ReferenceLine,
ReferenceArea,
ResponsiveContainer,
} from 'recharts';
const PriceCorridor = () => {
const { state, dispatch } = useGlobalState();
const [newCompetitor, setNewCompetitor] = useState<{
name: string;
price: number;
category: 'same-form' | 'different-form' | 'different-function';
}>({
name: '',
price: 0,
category: 'same-form',
});
const setTargetPrice = (price: number) => {
dispatch({
type: 'UPDATE_TARGET_PRICE',
payload: price,
});
};
const addCompetitor = () => {
if (!newCompetitor.name || !newCompetitor.price) return;
dispatch({
type: 'ADD_COMPETITOR',
payload: {
name: newCompetitor.name,
price: newCompetitor.price,
category: newCompetitor.category,
},
});
setNewCompetitor({ name: '', price: 0, category: 'same-form' });
};
const removeCompetitor = (index: number) => {
dispatch({
type: 'SET_STATE',
payload: {
...state,
priceCorridor: {
...state.priceCorridor,
competitors: state.priceCorridor.competitors.filter(
(_, i) => i !== index
),
},
},
});
};
const sortedCompetitors = [...state.priceCorridor.competitors].sort(
(a, b) => a.price - b.price
);
const prices = sortedCompetitors.map((c) => c.price);
const upperBound = Math.max(...prices, 0);
const lowerBound = Math.min(...prices, 0);
const range = upperBound - lowerBound;
const corridorLower = lowerBound + range * 0.3;
const corridorUpper = lowerBound + range * 0.8;
const chartData = sortedCompetitors.map((comp) => ({
name: comp.name,
price: comp.price,
category: comp.category,
}));
const categorizedCompetitors = {
'same-form': sortedCompetitors.filter((c) => c.category === 'same-form'),
'different-form': sortedCompetitors.filter(
(c) => c.category === 'different-form'
),
'different-function': sortedCompetitors.filter(
(c) => c.category === 'different-function'
),
};
return (
<div className="space-y-4">
<Card>
<CardHeader>
<CardTitle>Price Corridor of the Mass</CardTitle>
</CardHeader>
<CardContent>
<div className="h-[400px] w-full flex justify-center">
<ResponsiveContainer width="100%" height="100%" maxHeight={400}>
<LineChart
data={chartData}
margin={{ top: 20, right: 110, left: 50, bottom: 20 }}
className="[&_.recharts-cartesian-grid-horizontal]:stroke-muted [&_.recharts-cartesian-grid-vertical]:stroke-muted [&_.recharts-cartesian-axis-line]:stroke-muted [&_.recharts-cartesian-axis-tick-line]:stroke-muted [&_.recharts-cartesian-axis-tick-value]:fill-foreground"
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" stroke="currentColor" />
<YAxis stroke="currentColor" />
<Tooltip
contentStyle={{
backgroundColor: 'var(--background)',
borderColor: 'var(--border)',
color: 'var(--foreground)',
}}
/>
<Line
type="monotone"
dataKey="price"
stroke="hsl(var(--primary))"
/>
{state.priceCorridor.targetPrice > 0 && (
<ReferenceLine
y={state.priceCorridor.targetPrice}
stroke="hsl(var(--destructive))"
strokeDasharray="3 3"
label={{
value: 'Target Price',
position: 'insideRight',
fill: 'hsl(var(--destructive))',
offset: 100,
}}
/>
)}
{chartData.length > 0 && (
<ReferenceArea
y1={corridorLower}
y2={corridorUpper}
fill="hsl(var(--primary))"
fillOpacity={0.1}
stroke="hsl(var(--primary))"
strokeDasharray="3 3"
label={{
value: 'Price Corridor',
position: 'insideRight',
offset: 90,
}}
/>
)}
</LineChart>
</ResponsiveContainer>
</div>
</CardContent>
</Card>
<div className="grid grid-cols-2 gap-4">
<Card>
<CardHeader>
<CardTitle>Strategic Price</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
{chartData.length > 0 && (
<div className="text-sm space-y-2">
<p>
Suggested price corridor: {corridorLower.toFixed(2)} -{' '}
{corridorUpper.toFixed(2)}
</p>
<p>This range typically captures 70-80% of target buyers</p>
</div>
)}
<div className="flex gap-2 items-center">
<Input
type="number"
value={state.priceCorridor.targetPrice || ''}
onChange={(e) => setTargetPrice(Number(e.target.value))}
placeholder="Set target price..."
className="w-48"
/>
<span className="text-sm text-muted-foreground">
Current target: {state.priceCorridor.targetPrice || 'Not set'}
</span>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Add Alternative</CardTitle>
</CardHeader>
<CardContent>
<div className="flex gap-2">
<Input
placeholder="Name"
value={newCompetitor.name}
onChange={(e) =>
setNewCompetitor((prev) => ({
...prev,
name: e.target.value,
}))
}
className="flex-1"
/>
<Input
type="number"
placeholder="Price"
value={newCompetitor.price || ''}
onChange={(e) =>
setNewCompetitor((prev) => ({
...prev,
price: Number(e.target.value),
}))
}
className="w-32"
/>
<Select
value={
newCompetitor.category as
| 'same-form'
| 'different-form'
| 'different-function'
}
onValueChange={(
value: 'same-form' | 'different-form' | 'different-function'
) => setNewCompetitor((prev) => ({ ...prev, category: value }))}
>
<SelectTrigger className="w-48">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="same-form">Same Form</SelectItem>
<SelectItem value="different-form">Different Form</SelectItem>
<SelectItem value="different-function">
Different Function
</SelectItem>
</SelectContent>
</Select>
<Button onClick={addCompetitor}>
<Plus className="h-4 w-4" />
</Button>
</div>
</CardContent>
</Card>
</div>
<Card>
<CardHeader>
<CardTitle>Price Alternatives Analysis</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-6">
{Object.entries(categorizedCompetitors).map(
([category, competitors]) => (
<div key={category} className="space-y-2">
<h3 className="font-semibold capitalize">
{category.replace('-', ' ')} Alternatives
</h3>
{competitors.length > 0 ? (
<div className="space-y-2">
{competitors.map((comp, index) => (
<div
key={index}
className="flex items-center gap-2 p-2 bg-muted rounded-lg"
>
<span className="flex-1">{comp.name}</span>
<span className="w-32 text-right">{comp.price}</span>
<Button
variant="ghost"
size="sm"
onClick={() => removeCompetitor(index)}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
))}
</div>
) : (
<p className="text-sm text-muted-foreground">
No alternatives added
</p>
)}
</div>
)
)}
</div>
</CardContent>
</Card>
</div>
);
};
export default PriceCorridor;

View File

@@ -0,0 +1,156 @@
import React, { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@components/ui/card';
import { Button } from '@components/ui/button';
import { Input } from '@components/ui/input';
import { Textarea } from '@components/ui/textarea';
import { useGlobalState } from '@contexts/state/StateContext';
import { Trash2, Plus } from 'lucide-react';
import type { PathType } from '@utils/types';
const pathDefinitions = {
industries: {
title: 'Alternative Industries',
description: 'Look across substitute and alternative industries',
},
groups: {
title: 'Strategic Groups',
description: 'Look across strategic groups within your industry',
},
buyers: {
title: 'Buyer Groups',
description: 'Look across chain of buyers',
},
complementary: {
title: 'Complementary Products',
description: 'Look across complementary product and service offerings',
},
functional: {
title: 'Functional/Emotional Appeal',
description: 'Look across functional or emotional appeal to buyers',
},
trends: {
title: 'Time Trends',
description: 'Look across time and market trends',
},
};
const SixPaths = () => {
const { state, dispatch } = useGlobalState();
const [newOpportunities, setNewOpportunities] = useState<
Record<PathType, string>
>({
industries: '',
groups: '',
buyers: '',
complementary: '',
functional: '',
trends: '',
});
const addOpportunity = (pathType: PathType) => {
if (!newOpportunities[pathType]) return;
dispatch({
type: 'ADD_OPPORTUNITY',
payload: {
pathType,
value: newOpportunities[pathType],
},
});
setNewOpportunities((prev) => ({ ...prev, [pathType]: '' }));
};
const removeOpportunity = (pathType: PathType, index: number) => {
dispatch({
type: 'SET_STATE',
payload: {
...state,
sixPaths: {
...state.sixPaths,
[pathType]: {
...state.sixPaths[pathType],
opportunities: state.sixPaths[pathType].opportunities.filter(
(_, i) => i !== index
),
},
},
},
});
};
const updateNotes = (pathType: PathType, notes: string) => {
dispatch({
type: 'UPDATE_PATH_NOTES',
payload: { pathType, notes },
});
};
const renderPath = (pathType: PathType) => {
const { title, description } = pathDefinitions[pathType];
return (
<Card key={pathType}>
<CardHeader>
<CardTitle>{title}</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-gray-600 mb-4">{description}</p>
<Textarea
placeholder="Add notes about this path..."
value={state.sixPaths[pathType].notes}
onChange={(e) => updateNotes(pathType, e.target.value)}
className="mb-4"
/>
<div className="flex gap-2 mb-4">
<Input
placeholder="Add opportunity..."
value={newOpportunities[pathType]}
onChange={(e) =>
setNewOpportunities((prev) => ({
...prev,
[pathType]: e.target.value,
}))
}
className="flex-1"
/>
<Button onClick={() => addOpportunity(pathType)}>
<Plus className="h-4 w-4" />
</Button>
</div>
<div className="space-y-2">
{state.sixPaths[pathType].opportunities.map(
(opportunity, index) => (
<div
key={index}
className="flex items-center gap-2 p-2 bg-background rounded-lg"
>
<span className="flex-1">{opportunity}</span>
<Button
variant="ghost"
size="sm"
onClick={() => removeOpportunity(pathType, index)}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
)
)}
</div>
</CardContent>
</Card>
);
};
return (
<div className="grid grid-cols-2 gap-4">
{(Object.keys(pathDefinitions) as PathType[]).map((pathType) =>
renderPath(pathType)
)}
</div>
);
};
export default SixPaths;

View File

@@ -0,0 +1,386 @@
import React, { useState, useCallback } from 'react';
import {
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
ResponsiveContainer,
TooltipProps,
} from 'recharts';
import { Card, CardContent, CardHeader, CardTitle } from '@components/ui/card';
import { Button } from '@components/ui/button';
import { Input } from '@components/ui/input';
import { Textarea } from '@components/ui/textarea';
import { useGlobalState } from '@contexts/state/StateContext';
import { Trash2, Plus, MoveUp, MoveDown } from 'lucide-react';
import {
NameType,
ValueType,
} from 'recharts/types/component/DefaultTooltipContent';
interface Factor {
id: string;
name: string;
marketScore: number;
ideaScore: number;
}
interface NewFactor {
name: string;
marketScore: number;
ideaScore: number;
}
interface ChartDataPoint {
name: string;
Market: number;
'Your Idea': number;
tooltip: string;
}
interface CustomTooltipProps extends TooltipProps<ValueType, NameType> {
active?: boolean;
payload?: Array<{
name: string;
value: number;
color: string;
}>;
label?: string;
}
const StrategyCanvas: React.FC = () => {
const { state, dispatch } = useGlobalState();
const [newFactor, setNewFactor] = useState<NewFactor>({
name: '',
marketScore: 5,
ideaScore: 5,
});
const [error, setError] = useState<string>('');
const validateFactor = (factor: NewFactor): boolean => {
if (!factor.name.trim()) {
setError('Factor name is required');
return false;
}
if (factor.marketScore < 0 || factor.marketScore > 10) {
setError('Market score must be between 0 and 10');
return false;
}
if (factor.ideaScore < 0 || factor.ideaScore > 10) {
setError('Idea score must be between 0 and 10');
return false;
}
setError('');
return true;
};
const addFactor = useCallback((): void => {
if (!validateFactor(newFactor)) return;
dispatch({
type: 'ADD_FACTOR',
payload: {
id: `factor-${Date.now()}`,
...newFactor,
},
});
setNewFactor({ name: '', marketScore: 5, ideaScore: 5 });
}, [newFactor, dispatch]);
const moveFactor = useCallback(
(id: string, direction: 'up' | 'down'): void => {
const factors = [...state.strategyCanvas.factors];
const index = factors.findIndex((f) => f.id === id);
if (
(direction === 'up' && index === 0) ||
(direction === 'down' && index === factors.length - 1)
)
return;
const newIndex = direction === 'up' ? index - 1 : index + 1;
[factors[index], factors[newIndex]] = [factors[newIndex], factors[index]];
dispatch({
type: 'SET_STATE',
payload: {
...state,
strategyCanvas: {
...state.strategyCanvas,
factors,
},
},
});
},
[state, dispatch]
);
const updateFactorField = useCallback(
(id: string, field: keyof Factor, value: string | number): void => {
dispatch({
type: 'SET_STATE',
payload: {
...state,
strategyCanvas: {
...state.strategyCanvas,
factors: state.strategyCanvas.factors.map((f) =>
f.id === id
? {
...f,
[field]: field === 'name' ? value : Number(value),
}
: f
),
},
},
});
},
[state, dispatch]
);
const updateNotes = useCallback(
(id: string, notes: string): void => {
dispatch({
type: 'SET_STATE',
payload: {
...state,
strategyCanvas: {
...state.strategyCanvas,
notes: {
...state.strategyCanvas.notes,
[id]: notes,
},
},
},
});
},
[state, dispatch]
);
const deleteFactor = useCallback(
(id: string): void => {
dispatch({
type: 'SET_STATE',
payload: {
...state,
strategyCanvas: {
...state.strategyCanvas,
factors: state.strategyCanvas.factors.filter((f) => f.id !== id),
},
},
});
},
[state, dispatch]
);
const chartData: ChartDataPoint[] = state.strategyCanvas.factors.map((f) => ({
name: f.name,
Market: f.marketScore,
'Your Idea': f.ideaScore,
tooltip: `${f.name}\nMarket: ${f.marketScore}\nYour Idea: ${f.ideaScore}`,
}));
const CustomTooltip: React.FC<CustomTooltipProps> = ({
active,
payload,
label,
}) => {
if (!active || !payload?.length) return null;
return (
<div className="bg-background border rounded p-2 shadow-lg">
<p className="font-medium">{label}</p>
{payload.map((entry, index) => (
<p key={index} style={{ color: entry.color }}>
{entry.name}: {entry.value}
</p>
))}
</div>
);
};
return (
<div className="space-y-4">
<Card>
<CardHeader>
<CardTitle>Strategy Canvas</CardTitle>
</CardHeader>
<CardContent>
<div className="h-96">
<ResponsiveContainer width="100%" height="100%">
<LineChart
data={chartData}
margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
className="[&_.recharts-cartesian-grid-horizontal]:stroke-muted [&_.recharts-cartesian-grid-vertical]:stroke-muted [&_.recharts-cartesian-axis-line]:stroke-muted [&_.recharts-cartesian-axis-tick-line]:stroke-muted [&_.recharts-cartesian-axis-tick-value]:fill-foreground"
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis
dataKey="name"
stroke="currentColor"
padding={{ left: 50, right: 50 }}
height={60}
interval={0}
angle={-45}
textAnchor="end"
/>
<YAxis
domain={[0, 10]}
stroke="currentColor"
ticks={[0, 2, 4, 6, 8, 10]}
/>
<Tooltip content={<CustomTooltip />} />
<Legend />
<Line
type="monotone"
dataKey="Market"
stroke="hsl(var(--primary))"
strokeWidth={2}
dot={{ strokeWidth: 2 }}
activeDot={{ r: 8 }}
/>
<Line
type="monotone"
dataKey="Your Idea"
stroke="hsl(var(--destructive))"
strokeWidth={2}
dot={{ strokeWidth: 2 }}
activeDot={{ r: 8 }}
/>
</LineChart>
</ResponsiveContainer>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Factors</CardTitle>
</CardHeader>
<CardContent>
<div className="flex flex-col gap-4">
<div className="flex gap-2">
<Input
placeholder="Factor name"
value={newFactor.name}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setNewFactor({ ...newFactor, name: e.target.value })
}
className="flex-1"
/>
<Input
type="number"
placeholder="Market score (0-10)"
value={newFactor.marketScore}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setNewFactor({
...newFactor,
marketScore: Number(e.target.value),
})
}
min={0}
max={10}
className="w-32"
/>
<Input
type="number"
placeholder="Your score (0-10)"
value={newFactor.ideaScore}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setNewFactor({
...newFactor,
ideaScore: Number(e.target.value),
})
}
min={0}
max={10}
className="w-32"
/>
<Button onClick={addFactor}>
<Plus className="h-4 w-4" />
</Button>
</div>
{error && <p className="text-destructive text-sm">{error}</p>}
</div>
<div className="space-y-2 mt-4">
{state.strategyCanvas.factors.map((factor, index) => (
<div key={factor.id} className="p-4 border rounded-lg bg-card">
<div className="flex items-center gap-2 mb-2">
<div className="flex flex-col gap-1">
<Button
variant="ghost"
size="sm"
onClick={() => moveFactor(factor.id, 'up')}
disabled={index === 0}
>
<MoveUp className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => moveFactor(factor.id, 'down')}
disabled={
index === state.strategyCanvas.factors.length - 1
}
>
<MoveDown className="h-4 w-4" />
</Button>
</div>
<Input
value={factor.name}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
updateFactorField(factor.id, 'name', e.target.value)
}
className="flex-1"
/>
<Input
type="number"
value={factor.marketScore}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
updateFactorField(
factor.id,
'marketScore',
e.target.value
)
}
min={0}
max={10}
className="w-32"
/>
<Input
type="number"
value={factor.ideaScore}
onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
updateFactorField(factor.id, 'ideaScore', e.target.value)
}
min={0}
max={10}
className="w-32"
/>
<Button
variant="destructive"
onClick={() => deleteFactor(factor.id)}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
<Textarea
placeholder="Notes about this factor..."
value={state.strategyCanvas.notes[factor.id] || ''}
onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) =>
updateNotes(factor.id, e.target.value)
}
className="w-full"
/>
</div>
))}
</div>
</CardContent>
</Card>
</div>
);
};
export default StrategyCanvas;

View File

@@ -0,0 +1,97 @@
import React from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@components/ui/card';
import { Textarea } from '@components/ui/textarea';
import { Toggle } from '@components/ui/toggle';
import { useGlobalState } from '@contexts/state/StateContext';
const stages = [
'Purchase',
'Delivery',
'Use',
'Supplements',
'Maintenance',
'Disposal',
];
const utilities = [
'Customer Productivity',
'Simplicity',
'Convenience',
'Risk',
'Environmental Friendliness',
'Fun',
];
const UtilityMap = () => {
const { state, dispatch } = useGlobalState();
const toggleCell = (key: string) => {
dispatch({
type: 'TOGGLE_UTILITY',
payload: { key },
});
};
const updateNotes = (key: string, notes: string) => {
dispatch({
type: 'UPDATE_UTILITY_NOTES',
payload: { key, notes },
});
};
return (
<Card>
<CardHeader>
<CardTitle>Buyer Utility Map</CardTitle>
</CardHeader>
<CardContent>
<div className="overflow-x-auto">
<table className="w-full border-collapse">
<thead>
<tr>
<th className="p-2 border"></th>
{stages.map((stage) => (
<th key={stage} className="p-2 border text-center">
{stage}
</th>
))}
</tr>
</thead>
<tbody>
{utilities.map((utility) => (
<tr key={utility}>
<td className="p-2 border font-medium">{utility}</td>
{stages.map((stage) => {
const key = `${utility}-${stage}`;
return (
<td key={stage} className="p-2 border">
<div className="flex flex-col gap-2">
<Toggle
pressed={state.utilityMap[key]?.value || false}
onPressedChange={() => toggleCell(key)}
className="w-full"
>
{state.utilityMap[key]?.value
? 'Opportunity'
: 'No opportunity'}
</Toggle>
<Textarea
placeholder="Add notes..."
value={state.utilityMap[key]?.notes || ''}
onChange={(e) => updateNotes(key, e.target.value)}
className="h-24 text-sm"
/>
</div>
</td>
);
})}
</tr>
))}
</tbody>
</table>
</div>
</CardContent>
</Card>
);
};
export default UtilityMap;

View File

@@ -0,0 +1,131 @@
import React from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@components/ui/card';
import { Checkbox } from '@components/ui/checkbox';
import { Textarea } from '@components/ui/textarea';
import { useGlobalState } from '@contexts/state/StateContext';
const nonCustomerTiers = [
{
id: 'soon',
label: 'Soon-to-be non-customers who are on the edge of your market',
},
{
id: 'refusing',
label: 'Refusing non-customers who consciously choose against your market',
},
{
id: 'unexplored',
label: 'Unexplored non-customers who are in markets distant from yours',
},
];
const sequenceSteps = [
{
id: 'utility',
label: 'Does your offering deliver exceptional utility to buyers?',
},
{ id: 'price', label: 'Is your price accessible to the mass of buyers?' },
{
id: 'cost',
label: 'Can you attain your cost target to profit at your strategic price?',
},
{
id: 'adoption',
label: 'Are there adoption hurdles in actualizing your idea?',
},
];
const Validation = () => {
const { state, dispatch } = useGlobalState();
const toggleNonCustomer = (key: string) => {
dispatch({
type: 'TOGGLE_NON_CUSTOMER',
payload: { key },
});
};
const toggleSequence = (key: string) => {
dispatch({
type: 'TOGGLE_SEQUENCE',
payload: { key },
});
};
const updateNotes = (notes: string) => {
dispatch({
type: 'UPDATE_VALIDATION_NOTES',
payload: notes,
});
};
return (
<div className="space-y-4">
<Card>
<CardHeader>
<CardTitle>Non-Customer Analysis</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
{nonCustomerTiers.map((tier) => (
<div key={tier.id} className="flex items-start space-x-2">
<Checkbox
id={tier.id}
checked={state.validation.nonCustomers[tier.id] || false}
onCheckedChange={() => toggleNonCustomer(tier.id)}
/>
<label
htmlFor={tier.id}
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
{tier.label}
</label>
</div>
))}
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Strategic Sequence</CardTitle>
</CardHeader>
<CardContent>
<div className="space-y-4">
{sequenceSteps.map((step) => (
<div key={step.id} className="flex items-start space-x-2">
<Checkbox
id={step.id}
checked={state.validation.sequence[step.id] || false}
onCheckedChange={() => toggleSequence(step.id)}
/>
<label
htmlFor={step.id}
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
{step.label}
</label>
</div>
))}
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Notes</CardTitle>
</CardHeader>
<CardContent>
<Textarea
placeholder="Add validation notes..."
value={state.validation.notes}
onChange={(e) => updateNotes(e.target.value)}
className="min-h-[200px]"
/>
</CardContent>
</Card>
</div>
);
};
export default Validation;

59
components/ui/alert.tsx Normal file
View File

@@ -0,0 +1,59 @@
import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@utils/cn';
const alertVariants = cva(
'relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7',
{
variants: {
variant: {
default: 'bg-background text-foreground',
destructive:
'border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive',
},
},
defaultVariants: {
variant: 'default',
},
}
);
const Alert = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
>(({ className, variant, ...props }, ref) => (
<div
ref={ref}
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
));
Alert.displayName = 'Alert';
const AlertTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h5
ref={ref}
className={cn('mb-1 font-medium leading-none tracking-tight', className)}
{...props}
/>
));
AlertTitle.displayName = 'AlertTitle';
const AlertDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn('text-sm [&_p]:leading-relaxed', className)}
{...props}
/>
));
AlertDescription.displayName = 'AlertDescription';
export { Alert, AlertTitle, AlertDescription };

57
components/ui/button.tsx Normal file
View File

@@ -0,0 +1,57 @@
import * as React from 'react';
import { Slot } from '@radix-ui/react-slot';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@utils/cn';
const buttonVariants = cva(
'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',
{
variants: {
variant: {
default:
'bg-primary text-primary-foreground shadow hover:bg-primary/90',
destructive:
'bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90',
outline:
'border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground',
secondary:
'bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80',
ghost: 'hover:bg-accent hover:text-accent-foreground',
link: 'text-primary underline-offset-4 hover:underline',
},
size: {
default: 'h-9 px-4 py-2',
sm: 'h-8 rounded-md px-3 text-xs',
lg: 'h-10 rounded-md px-8',
icon: 'h-9 w-9',
},
},
defaultVariants: {
variant: 'default',
size: 'default',
},
}
);
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean;
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : 'button';
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
);
}
);
Button.displayName = 'Button';
export { Button, buttonVariants };

83
components/ui/card.tsx Normal file
View File

@@ -0,0 +1,83 @@
import * as React from 'react';
import { cn } from '@utils/cn';
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
'rounded-xl border bg-card text-card-foreground shadow',
className
)}
{...props}
/>
));
Card.displayName = 'Card';
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn('flex flex-col space-y-1.5 p-6', className)}
{...props}
/>
));
CardHeader.displayName = 'CardHeader';
const CardTitle = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn('font-semibold leading-none tracking-tight', className)}
{...props}
/>
));
CardTitle.displayName = 'CardTitle';
const CardDescription = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
));
CardDescription.displayName = 'CardDescription';
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn('p-6 pt-0', className)} {...props} />
));
CardContent.displayName = 'CardContent';
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn('flex items-center p-6 pt-0', className)}
{...props}
/>
));
CardFooter.displayName = 'CardFooter';
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardDescription,
CardContent,
};

View File

@@ -0,0 +1,30 @@
'use client';
import * as React from 'react';
import * as CheckboxPrimitive from '@radix-ui/react-checkbox';
import { Check } from 'lucide-react';
import { cn } from '@utils/cn';
const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, ...props }, ref) => (
<CheckboxPrimitive.Root
ref={ref}
className={cn(
'peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground',
className
)}
{...props}
>
<CheckboxPrimitive.Indicator
className={cn('flex items-center justify-center text-current')}
>
<Check className="h-4 w-4" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
));
Checkbox.displayName = CheckboxPrimitive.Root.displayName;
export { Checkbox };

122
components/ui/dialog.tsx Normal file
View File

@@ -0,0 +1,122 @@
'use client';
import * as React from 'react';
import * as DialogPrimitive from '@radix-ui/react-dialog';
import { X } from 'lucide-react';
import { cn } from '@utils/cn';
const Dialog = DialogPrimitive.Root;
const DialogTrigger = DialogPrimitive.Trigger;
const DialogPortal = DialogPrimitive.Portal;
const DialogClose = DialogPrimitive.Close;
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
'fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className
)}
{...props}
/>
));
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
'fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg',
className
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
));
DialogContent.displayName = DialogPrimitive.Content.displayName;
const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
'flex flex-col space-y-1.5 text-center sm:text-left',
className
)}
{...props}
/>
);
DialogHeader.displayName = 'DialogHeader';
const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
'flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2',
className
)}
{...props}
/>
);
DialogFooter.displayName = 'DialogFooter';
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn(
'text-lg font-semibold leading-none tracking-tight',
className
)}
{...props}
/>
));
DialogTitle.displayName = DialogPrimitive.Title.displayName;
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
));
DialogDescription.displayName = DialogPrimitive.Description.displayName;
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogTrigger,
DialogClose,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
};

View File

@@ -0,0 +1,32 @@
import { Input } from '@components/ui/input';
import { Button } from '@components/ui/button';
import { X } from 'lucide-react';
export function EditableList({
items,
onAdd,
onRemove,
onUpdate,
}: {
items: string[];
onAdd: () => void;
onRemove: (index: number) => void;
onUpdate: (index: number, value: string) => void;
}) {
return (
<div className="space-y-2">
{items.map((item, index) => (
<div key={index} className="flex gap-2">
<Input
value={item}
onChange={(e) => onUpdate(index, e.target.value)}
/>
<Button variant="ghost" size="icon" onClick={() => onRemove(index)}>
<X className="h-4 w-4" />
</Button>
</div>
))}
<Button onClick={onAdd}>Add</Button>
</div>
);
}

View File

@@ -0,0 +1,48 @@
import { Label } from '@components/ui/label';
import { Input } from '@components/ui/input';
import { Slider } from '@components/ui/slider';
export function FactorInput({
name,
marketScore,
ideaScore,
onNameChange,
onMarketChange,
onIdeaChange,
}: {
name: string;
marketScore: number;
ideaScore: number;
onNameChange: (value: string) => void;
onMarketChange: (value: number) => void;
onIdeaChange: (value: number) => void;
}) {
return (
<div className="space-y-4">
<div>
<Label>Factor Name</Label>
<Input value={name} onChange={(e) => onNameChange(e.target.value)} />
</div>
<div>
<Label>Market Score</Label>
<Slider
value={[marketScore]}
min={0}
max={10}
step={1}
onValueChange={([value]) => onMarketChange(value)}
/>
</div>
<div>
<Label>Idea Score</Label>
<Slider
value={[ideaScore]}
min={0}
max={10}
step={1}
onValueChange={([value]) => onIdeaChange(value)}
/>
</div>
</div>
);
}

22
components/ui/input.tsx Normal file
View File

@@ -0,0 +1,22 @@
import * as React from 'react';
import { cn } from '@utils/cn';
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<'input'>>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
'flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
className
)}
ref={ref}
{...props}
/>
);
}
);
Input.displayName = 'Input';
export { Input };

26
components/ui/label.tsx Normal file
View File

@@ -0,0 +1,26 @@
'use client';
import * as React from 'react';
import * as LabelPrimitive from '@radix-ui/react-label';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@utils/cn';
const labelVariants = cva(
'text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70'
);
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
));
Label.displayName = LabelPrimitive.Root.displayName;
export { Label };

View File

@@ -0,0 +1,23 @@
import { Textarea } from '@components/ui/textarea';
import { Label } from '@components/ui/label';
export function NotesField({
value,
onChange,
label = 'Notes',
}: {
value: string;
onChange: (value: string) => void;
label?: string;
}) {
return (
<div className="space-y-2">
<Label>{label}</Label>
<Textarea
value={value}
onChange={(e) => onChange(e.target.value)}
className="min-h-[100px]"
/>
</div>
);
}

159
components/ui/select.tsx Normal file
View File

@@ -0,0 +1,159 @@
'use client';
import * as React from 'react';
import * as SelectPrimitive from '@radix-ui/react-select';
import { Check, ChevronDown, ChevronUp } from 'lucide-react';
import { cn } from '@utils/cn';
const Select = SelectPrimitive.Root;
const SelectGroup = SelectPrimitive.Group;
const SelectValue = SelectPrimitive.Value;
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
'flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1',
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDown className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
));
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
const SelectScrollUpButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollUpButton
ref={ref}
className={cn(
'flex cursor-default items-center justify-center py-1',
className
)}
{...props}
>
<ChevronUp className="h-4 w-4" />
</SelectPrimitive.ScrollUpButton>
));
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;
const SelectScrollDownButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollDownButton
ref={ref}
className={cn(
'flex cursor-default items-center justify-center py-1',
className
)}
{...props}
>
<ChevronDown className="h-4 w-4" />
</SelectPrimitive.ScrollDownButton>
));
SelectScrollDownButton.displayName =
SelectPrimitive.ScrollDownButton.displayName;
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = 'popper', ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
'relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
position === 'popper' &&
'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
className
)}
position={position}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
'p-1',
position === 'popper' &&
'h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]'
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
));
SelectContent.displayName = SelectPrimitive.Content.displayName;
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Label
ref={ref}
className={cn('px-2 py-1.5 text-sm font-semibold', className)}
{...props}
/>
));
SelectLabel.displayName = SelectPrimitive.Label.displayName;
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
'relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className
)}
{...props}
>
<span className="absolute right-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
));
SelectItem.displayName = SelectPrimitive.Item.displayName;
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Separator
ref={ref}
className={cn('-mx-1 my-1 h-px bg-muted', className)}
{...props}
/>
));
SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
SelectScrollUpButton,
SelectScrollDownButton,
};

28
components/ui/slider.tsx Normal file
View File

@@ -0,0 +1,28 @@
'use client';
import * as React from 'react';
import * as SliderPrimitive from '@radix-ui/react-slider';
import { cn } from '@utils/cn';
const Slider = React.forwardRef<
React.ElementRef<typeof SliderPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>
>(({ className, ...props }, ref) => (
<SliderPrimitive.Root
ref={ref}
className={cn(
'relative flex w-full touch-none select-none items-center',
className
)}
{...props}
>
<SliderPrimitive.Track className="relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20">
<SliderPrimitive.Range className="absolute h-full bg-primary" />
</SliderPrimitive.Track>
<SliderPrimitive.Thumb className="block h-4 w-4 rounded-full border border-primary/50 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50" />
</SliderPrimitive.Root>
));
Slider.displayName = SliderPrimitive.Root.displayName;
export { Slider };

55
components/ui/tabs.tsx Normal file
View File

@@ -0,0 +1,55 @@
'use client';
import * as React from 'react';
import * as TabsPrimitive from '@radix-ui/react-tabs';
import { cn } from '@utils/cn';
const Tabs = TabsPrimitive.Root;
const TabsList = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
>(({ className, ...props }, ref) => (
<TabsPrimitive.List
ref={ref}
className={cn(
'inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground',
className
)}
{...props}
/>
));
TabsList.displayName = TabsPrimitive.List.displayName;
const TabsTrigger = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Trigger
ref={ref}
className={cn(
'inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow',
className
)}
{...props}
/>
));
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Content
ref={ref}
className={cn(
'mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2',
className
)}
{...props}
/>
));
TabsContent.displayName = TabsPrimitive.Content.displayName;
export { Tabs, TabsList, TabsTrigger, TabsContent };

View File

@@ -0,0 +1,22 @@
import * as React from 'react';
import { cn } from '@utils/cn';
const Textarea = React.forwardRef<
HTMLTextAreaElement,
React.ComponentProps<'textarea'>
>(({ className, ...props }, ref) => {
return (
<textarea
className={cn(
'flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
className
)}
ref={ref}
{...props}
/>
);
});
Textarea.displayName = 'Textarea';
export { Textarea };

45
components/ui/toggle.tsx Normal file
View File

@@ -0,0 +1,45 @@
'use client';
import * as React from 'react';
import * as TogglePrimitive from '@radix-ui/react-toggle';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@utils/cn';
const toggleVariants = cva(
'inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0',
{
variants: {
variant: {
default: 'bg-transparent',
outline:
'border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground',
},
size: {
default: 'h-9 px-2 min-w-9',
sm: 'h-8 px-1.5 min-w-8',
lg: 'h-10 px-2.5 min-w-10',
},
},
defaultVariants: {
variant: 'default',
size: 'default',
},
}
);
const Toggle = React.forwardRef<
React.ElementRef<typeof TogglePrimitive.Root>,
React.ComponentPropsWithoutRef<typeof TogglePrimitive.Root> &
VariantProps<typeof toggleVariants>
>(({ className, variant, size, ...props }, ref) => (
<TogglePrimitive.Root
ref={ref}
className={cn(toggleVariants({ variant, size, className }))}
{...props}
/>
));
Toggle.displayName = TogglePrimitive.Root.displayName;
export { Toggle, toggleVariants };

View File

@@ -0,0 +1,18 @@
import { Card, CardHeader, CardTitle, CardContent } from '@components/ui/card';
export function ToolCard({
title,
children,
}: {
title: string;
children: React.ReactNode;
}) {
return (
<Card>
<CardHeader>
<CardTitle>{title}</CardTitle>
</CardHeader>
<CardContent>{children}</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,68 @@
'use client';
import React, { createContext, useContext } from 'react';
import type { GlobalState } from '../../utils/types';
export type Action =
| { type: 'SET_STATE'; payload: GlobalState }
| {
type: 'ADD_FACTOR';
payload: {
id: string;
name: string;
marketScore: number;
ideaScore: number;
};
}
| {
type: 'ADD_ACTION';
payload: { actionType: keyof GlobalState['fourActions']; value: string };
}
| {
type: 'ADD_OPPORTUNITY';
payload: { pathType: keyof GlobalState['sixPaths']; value: string };
}
| { type: 'UPDATE_PATH_NOTES'; payload: { pathType: string; notes: string } }
| { type: 'TOGGLE_UTILITY'; payload: { key: string } }
| { type: 'UPDATE_UTILITY_NOTES'; payload: { key: string; notes: string } }
| { type: 'UPDATE_TARGET_PRICE'; payload: number }
| {
type: 'ADD_COMPETITOR';
payload: {
name: string;
price: number;
category: 'same-form' | 'different-form' | 'different-function';
};
}
| {
type: 'UPDATE_COMPETITOR';
payload: {
index: number;
field: 'name' | 'price' | 'category';
value: string | number;
};
}
| { type: 'TOGGLE_NON_CUSTOMER'; payload: { key: string } }
| { type: 'TOGGLE_SEQUENCE'; payload: { key: string } }
| { type: 'UPDATE_VALIDATION_NOTES'; payload: string }
| { type: 'RESET_STATE' };
export interface StateContextType {
state: GlobalState;
dispatch: React.Dispatch<Action>;
isLoading: boolean;
error: string | null;
resetState: () => void;
}
export const StateContext = createContext<StateContextType | undefined>(
undefined
);
export function useGlobalState() {
const context = useContext(StateContext);
if (!context) {
throw new Error('useGlobalState must be used within StateProvider');
}
return context;
}

View File

@@ -0,0 +1,86 @@
'use client';
import { Alert, AlertDescription } from '@components/ui/alert';
import { StateContext, StateContextType } from './StateContext';
import { Loader2 } from 'lucide-react';
import { useEffect, useReducer, useState } from 'react';
import { useStorage } from '@utils/useStorage';
import { stateReducer } from '@utils/stateReducer';
import _ from 'lodash';
import { initialState } from '@utils/validateState';
export function StateProvider({ children }: { children: React.ReactNode }) {
const [state, dispatch] = useReducer(stateReducer, initialState);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const { loadState, saveState } = useStorage();
useEffect(() => {
const init = async () => {
try {
setIsLoading(true);
setError(null);
const saved = await loadState();
if (saved) {
dispatch({ type: 'SET_STATE', payload: saved });
}
} catch (error) {
console.error('Failed to load initial state:', error);
setError('Failed to load saved data. Starting with empty state.');
} finally {
setIsLoading(false);
}
};
init();
}, [loadState]);
useEffect(() => {
const debouncedSave = _.debounce(async () => {
try {
await saveState(state);
} catch (error) {
console.error('Failed to save state:', error);
setError('Failed to save changes.');
}
}, 1000);
if (!isLoading) {
debouncedSave();
}
return () => {
debouncedSave.cancel();
};
}, [saveState, state, isLoading]);
const resetState = () => {
dispatch({ type: 'RESET_STATE' });
};
if (isLoading) {
return (
<div className="flex items-center justify-center h-screen">
<Loader2 className="h-8 w-8 animate-spin" />
</div>
);
}
const contextValue: StateContextType = {
state,
dispatch,
isLoading,
error,
resetState,
};
return (
<StateContext.Provider value={contextValue}>
{error && (
<Alert variant="destructive" className="mb-4">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
{children}
</StateContext.Provider>
);
}

16
eslint.config.mjs Normal file
View File

@@ -0,0 +1,16 @@
import { dirname } from 'path';
import { fileURLToPath } from 'url';
import { FlatCompat } from '@eslint/eslintrc';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
});
const eslintConfig = [
...compat.extends('next/core-web-vitals', 'next/typescript'),
];
export default eslintConfig;

7
next.config.ts Normal file
View File

@@ -0,0 +1,7 @@
import type { NextConfig } from 'next';
const nextConfig: NextConfig = {
/* config options here */
};
export default nextConfig;

5895
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

54
package.json Normal file
View File

@@ -0,0 +1,54 @@
{
"name": "blue-ocean",
"version": "1.0.0",
"description": "Simple web app for visualizing and analyzing business strategies using the Blue Ocean Strategy framework",
"author": "riccardo@frompixels.com",
"scripts": {
"dev": "next dev --turbopack",
"build": "next build",
"start": "next start",
"lint": "next lint --fix",
"format": "prettier --write .",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@radix-ui/react-checkbox": "^1.1.3",
"@radix-ui/react-dialog": "^1.1.5",
"@radix-ui/react-label": "^2.1.1",
"@radix-ui/react-select": "^2.1.5",
"@radix-ui/react-slider": "^1.2.2",
"@radix-ui/react-slot": "^1.1.1",
"@radix-ui/react-tabs": "^1.1.2",
"@radix-ui/react-toggle": "^1.1.1",
"@upstash/redis": "^1.34.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"lodash": "^4.17.21",
"lucide-react": "^0.474.0",
"next": "15.1.6",
"next-themes": "^0.4.4",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"recharts": "^2.15.0",
"tailwind-merge": "^2.6.0",
"tailwindcss-animate": "^1.0.7"
},
"devDependencies": {
"@eslint/eslintrc": "^3",
"@shadcn/ui": "^0.0.4",
"@types/lodash": "^4.17.14",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"@typescript-eslint/eslint-plugin": "^8.21.0",
"@typescript-eslint/parser": "^8.21.0",
"eslint": "^9",
"eslint-config-next": "15.1.6",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-prettier": "^5.2.3",
"postcss": "^8",
"prettier": "^3.4.2",
"tailwindcss": "^3.4.1",
"typescript": "^5"
}
}

8
postcss.config.mjs Normal file
View File

@@ -0,0 +1,8 @@
/** @type {import('postcss-load-config').Config} */
const config = {
plugins: {
tailwindcss: {},
},
};
export default config;

66
tailwind.config.ts Normal file
View File

@@ -0,0 +1,66 @@
import { Config } from 'tailwindcss';
const config = {
darkMode: ['class'],
content: ['./app/**/*.{ts,tsx}', './components/**/*.{ts,tsx}'],
theme: {
container: {
center: true,
padding: '2rem',
screens: {
'2xl': '1400px',
},
},
extend: {
colors: {
border: 'hsl(var(--border))',
input: 'hsl(var(--input))',
ring: 'hsl(var(--ring))',
background: 'hsl(var(--background))',
foreground: 'hsl(var(--foreground))',
primary: {
DEFAULT: 'hsl(var(--primary))',
foreground: 'hsl(var(--primary-foreground))',
},
secondary: {
DEFAULT: 'hsl(var(--secondary))',
foreground: 'hsl(var(--secondary-foreground))',
},
destructive: {
DEFAULT: 'hsl(var(--destructive))',
foreground: 'hsl(var(--destructive-foreground))',
},
muted: {
DEFAULT: 'hsl(var(--muted))',
foreground: 'hsl(var(--muted-foreground))',
},
accent: {
DEFAULT: 'hsl(var(--accent))',
foreground: 'hsl(var(--accent-foreground))',
},
popover: {
DEFAULT: 'hsl(var(--popover))',
foreground: 'hsl(var(--popover-foreground))',
},
card: {
DEFAULT: 'hsl(var(--card))',
foreground: 'hsl(var(--card-foreground))',
},
ocean: {
50: '#f0f9ff',
100: '#e0f2fe',
200: '#bae6fd',
300: '#7dd3fc',
400: '#38bdf8',
500: '#0ea5e9',
600: '#0284c7',
700: '#0369a1',
800: '#075985',
900: '#0c4a6e',
},
},
},
},
} satisfies Config;
export default config;

29
tsconfig.json Normal file
View File

@@ -0,0 +1,29 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@components/*": ["./components/*"],
"@contexts/*": ["./contexts/*"],
"@utils/*": ["./utils/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}

6
utils/cn.ts Normal file
View File

@@ -0,0 +1,6 @@
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}

18
utils/redis.ts Normal file
View File

@@ -0,0 +1,18 @@
import { Redis } from '@upstash/redis';
if (!process.env.KV_REST_API_URL) {
throw new Error('KV_REST_API_URL is not defined');
}
if (!process.env.KV_REST_API_TOKEN) {
throw new Error('KV_REST_API_TOKEN is not defined');
}
export const redis = new Redis({
url: process.env.KV_REST_API_URL,
token: process.env.KV_REST_API_TOKEN,
retry: {
retries: 3,
backoff: (retryCount) => Math.min(retryCount * 100, 3000),
},
});

149
utils/stateReducer.ts Normal file
View File

@@ -0,0 +1,149 @@
import { GlobalState, PathType } from './types';
import { Action } from '@contexts/state/StateContext';
import { initialState } from './validateState';
export function stateReducer(state: GlobalState, action: Action): GlobalState {
switch (action.type) {
case 'SET_STATE':
return action.payload;
case 'RESET_STATE':
return initialState;
case 'ADD_FACTOR':
return {
...state,
strategyCanvas: {
...state.strategyCanvas,
factors: [...state.strategyCanvas.factors, action.payload],
},
};
case 'ADD_ACTION': {
const { actionType, value } = action.payload;
return {
...state,
fourActions: {
...state.fourActions,
[actionType]: [...state.fourActions[actionType], value],
},
};
}
case 'ADD_OPPORTUNITY': {
const { pathType, value: oppValue } = action.payload;
return {
...state,
sixPaths: {
...state.sixPaths,
[pathType]: {
...state.sixPaths[pathType],
opportunities: [
...state.sixPaths[pathType].opportunities,
oppValue,
],
},
},
};
}
case 'UPDATE_PATH_NOTES': {
const { pathType, notes } = action.payload as {
pathType: PathType;
notes: string;
};
return {
...state,
sixPaths: {
...state.sixPaths,
[pathType]: {
...state.sixPaths[pathType],
notes,
},
},
};
}
case 'TOGGLE_UTILITY': {
const { key } = action.payload;
const currentValue = state.utilityMap[key]?.value ?? false;
return {
...state,
utilityMap: {
...state.utilityMap,
[key]: {
...state.utilityMap[key],
value: !currentValue,
},
},
};
}
case 'UPDATE_UTILITY_NOTES':
return {
...state,
utilityMap: {
...state.utilityMap,
[action.payload.key]: {
...state.utilityMap[action.payload.key],
notes: action.payload.notes,
},
},
};
case 'UPDATE_TARGET_PRICE':
return {
...state,
priceCorridor: {
...state.priceCorridor,
targetPrice: action.payload,
},
};
case 'ADD_COMPETITOR':
return {
...state,
priceCorridor: {
...state.priceCorridor,
competitors: [...state.priceCorridor.competitors, action.payload],
},
};
case 'UPDATE_COMPETITOR': {
const { index, field, value: compValue } = action.payload;
return {
...state,
priceCorridor: {
...state.priceCorridor,
competitors: state.priceCorridor.competitors.map((comp, i) =>
i === index ? { ...comp, [field]: compValue } : comp
),
},
};
}
case 'TOGGLE_NON_CUSTOMER':
return {
...state,
validation: {
...state.validation,
nonCustomers: {
...state.validation.nonCustomers,
[action.payload.key]:
!state.validation.nonCustomers[action.payload.key],
},
},
};
case 'TOGGLE_SEQUENCE':
return {
...state,
validation: {
...state.validation,
sequence: {
...state.validation.sequence,
[action.payload.key]:
!state.validation.sequence[action.payload.key],
},
},
};
case 'UPDATE_VALIDATION_NOTES':
return {
...state,
validation: {
...state.validation,
notes: action.payload,
},
};
default:
return state;
}
}

52
utils/types.ts Normal file
View File

@@ -0,0 +1,52 @@
export interface GlobalState {
strategyCanvas: {
factors: {
id: string;
name: string;
marketScore: number;
ideaScore: number;
}[];
notes: Record<string, string>;
};
fourActions: {
eliminate: string[];
reduce: string[];
raise: string[];
create: string[];
};
sixPaths: Record<
PathType,
{
notes: string;
opportunities: string[];
}
>;
utilityMap: Record<
string,
{
value: boolean;
notes: string;
}
>;
priceCorridor: {
targetPrice: number;
competitors: {
name: string;
price: number;
category: 'same-form' | 'different-form' | 'different-function';
}[];
};
validation: {
nonCustomers: Record<string, boolean>;
sequence: Record<string, boolean>;
notes: string;
};
}
export type PathType =
| 'industries'
| 'groups'
| 'buyers'
| 'complementary'
| 'functional'
| 'trends';

80
utils/useStorage.ts Normal file
View File

@@ -0,0 +1,80 @@
import { GlobalState } from './types';
import { useCallback } from 'react';
import _ from 'lodash';
import { initialState, validateState } from './validateState';
export const useStorage = () => {
const saveState = useCallback(
_.debounce(async (state: GlobalState) => {
try {
const validState = validateState(state);
localStorage.setItem('state', JSON.stringify(validState));
} catch (error) {
console.error('Error saving state:', error);
throw error;
}
}, 1000),
[]
);
const loadState = useCallback(async (): Promise<GlobalState | null> => {
try {
const localState = localStorage.getItem('state');
return localState ? JSON.parse(localState) : null;
} catch (error) {
console.error('Error loading state:', error);
return null;
}
}, []);
const backupState = async (
state: GlobalState
): Promise<{ key?: string; error?: string }> => {
try {
const validState = validateState(state);
const res = await fetch('/api/backup', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ state: validState }),
});
const data = await res.json();
if (!res.ok) {
throw new Error(data.error || 'Backup request failed');
}
return { key: data.key };
} catch (error) {
console.error('Backup failed:', error);
return {
error:
error instanceof Error ? error.message : 'Unknown error occurred',
};
}
};
const restoreState = async (key: string): Promise<GlobalState> => {
try {
if (!key) {
throw new Error('No key provided');
}
const res = await fetch(`/api/restore?key=${encodeURIComponent(key)}`);
const data = await res.json();
if (!res.ok) {
throw new Error(
data.error || `Restore failed with status ${res.status}`
);
}
return validateState(data.data);
} catch (error) {
console.error('Restore failed:', error);
return initialState;
}
};
return { saveState, loadState, backupState, restoreState };
};

109
utils/validateState.ts Normal file
View File

@@ -0,0 +1,109 @@
import { GlobalState } from './types';
export const initialState: GlobalState = {
strategyCanvas: {
factors: [],
notes: {},
},
fourActions: {
eliminate: [],
reduce: [],
raise: [],
create: [],
},
sixPaths: {
industries: { notes: '', opportunities: [] },
groups: { notes: '', opportunities: [] },
buyers: { notes: '', opportunities: [] },
complementary: { notes: '', opportunities: [] },
functional: { notes: '', opportunities: [] },
trends: { notes: '', opportunities: [] },
},
utilityMap: {},
priceCorridor: {
targetPrice: 0,
competitors: [] as Array<{
name: string;
price: number;
category: 'same-form' | 'different-form' | 'different-function';
}>,
},
validation: {
nonCustomers: {},
sequence: {},
notes: '',
},
};
export function validateState(state: any): GlobalState {
if (!state || typeof state !== 'object') {
return initialState;
}
return {
strategyCanvas: {
factors: Array.isArray(state?.strategyCanvas?.factors)
? state.strategyCanvas.factors
: [],
notes: state?.strategyCanvas?.notes || {},
},
fourActions: {
eliminate: Array.isArray(state?.fourActions?.eliminate)
? state.fourActions.eliminate
: [],
reduce: Array.isArray(state?.fourActions?.reduce)
? state.fourActions.reduce
: [],
raise: Array.isArray(state?.fourActions?.raise)
? state.fourActions.raise
: [],
create: Array.isArray(state?.fourActions?.create)
? state.fourActions.create
: [],
},
sixPaths: {
industries: validatePathSection(state?.sixPaths?.industries),
groups: validatePathSection(state?.sixPaths?.groups),
buyers: validatePathSection(state?.sixPaths?.buyers),
complementary: validatePathSection(state?.sixPaths?.complementary),
functional: validatePathSection(state?.sixPaths?.functional),
trends: validatePathSection(state?.sixPaths?.trends),
},
utilityMap: state?.utilityMap || {},
priceCorridor: {
targetPrice: Number(state?.priceCorridor?.targetPrice) || 0,
competitors: Array.isArray(state?.priceCorridor?.competitors)
? state.priceCorridor.competitors.map(
(comp: { name?: string; price?: number; category?: string }) => ({
name: comp.name || '',
price: Number(comp.price) || 0,
category: [
'same-form',
'different-form',
'different-function',
].includes(comp.category || '')
? (comp.category as
| 'same-form'
| 'different-form'
| 'different-function')
: 'same-form',
})
)
: [],
},
validation: {
nonCustomers: state?.validation?.nonCustomers || {},
sequence: state?.validation?.sequence || {},
notes: state?.validation?.notes || '',
},
};
}
function validatePathSection(section: any) {
return {
notes: typeof section?.notes === 'string' ? section.notes : '',
opportunities: Array.isArray(section?.opportunities)
? section.opportunities
: [],
};
}

3997
yarn.lock Normal file

File diff suppressed because it is too large Load Diff