import { makeAutoObservable, runInAction } from 'mobx';
import type { CartItem, Product } from './types';
const MOCK_PRODUCTS: Product[] = [
{
id: 1,
name: '无线降噪耳机',
price: 299,
image: '🎧',
description: '沉浸式音质体验',
},
{
id: 2,
name: '智能运动手表',
price: 199,
image: '⌚️',
description: '全天候健康监测',
},
{
id: 3,
name: '手机',
price: 399,
image: '📱',
description: '拥抱科技,享受未来',
},
{
id: 4,
name: '机械键盘',
price: 69,
image: '⌨️',
description: '静音完美手感',
},
];
class CartStore {
cartItems: CartItem[] = [];
private sharedWorker: SharedWorker | undefined;
constructor() {
makeAutoObservable(this);
if (typeof SharedWorker !== 'undefined') {
const sharedWorker = new SharedWorker(
new URL('../workers/cart.work.ts', import.meta.url),
{
type: 'module',
credentials: 'same-origin',
},
);
sharedWorker.port.onmessage = e => {
runInAction(() => {
this.cartItems = e.data;
});
};
this.sharedWorker = sharedWorker;
sharedWorker.port.start();
}
}
get products() {
return MOCK_PRODUCTS;
}
get totalPrice() {
return this.cartItems.reduce(
(total, item) => total + item.price * item.quantity,
0,
);
}
get totalQuantity() {
return this.cartItems.reduce((sum, item) => sum + item.quantity, 0);
}
addToCart = (product: Product) => {
const existingItem = this.cartItems.find(item => item.id === product.id);
if (existingItem) {
existingItem.quantity += 1;
} else {
this.cartItems.push({
...product,
quantity: 1,
});
}
this.synchronizeData();
};
increaseQuantity = (id: number) => {
const item = this.cartItems.find(item => item.id === id);
if (item) {
item.quantity += 1;
}
this.synchronizeData();
};
decreaseQuantity = (id: number) => {
const item = this.cartItems.find(item => item.id === id);
if (item) {
if (item.quantity > 1) {
item.quantity -= 1;
} else {
this.removeFromCart(id);
}
}
this.synchronizeData();
};
removeFromCart = (id: number) => {
this.cartItems = this.cartItems.filter(item => item.id !== id);
this.synchronizeData();
};
private synchronizeData() {
if (this.sharedWorker) {
if (this.sharedWorker.port.postMessage) {
this.sharedWorker.port.postMessage(
this.cartItems.reduce(
(cart: CartItem[], item) => [...cart, { ...item }],
[],
),
);
}
}
}
}
export const cartStore = new CartStore();