OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.
TypeScript
feat: extract initial image core package
copilot-swe-agent[bot]11f3ce068483
diff --git a/apps/image/package.json b/apps/image/package.jsonindex 3dd0f4af..364d4931 100644--- a/apps/image/package.json+++ b/apps/image/package.json@@ -17,6 +17,7 @@},"dependencies": {"@imgly/background-removal": "^1.7.0",+ "@openreel/image-core": "workspace:*","@openreel/ui": "workspace:*","@radix-ui/react-context-menu": "^2.2.16","@radix-ui/react-dialog": "^1.1.15",diff --git a/apps/image/src/services/project-migration.ts b/apps/image/src/services/project-migration.tsindex 37edb5a1..e0ad9cba 100644--- a/apps/image/src/services/project-migration.ts+++ b/apps/image/src/services/project-migration.ts@@ -1,40 +1 @@--/** The current document format version. Increment when the schema changes. */-export const CURRENT_VERSION = 1;--/**- * Apply all pending migrations to bring `raw` up to the current version.- * Unknown versions are returned as-is so callers can fail validation instead.- */-export function migrateProject(raw: Record<string, unknown>): Record<string, unknown> {- let doc = { ...raw };- const version = typeof doc.version === 'number' ? doc.version : 0;-- // Version 0 → 1: add explicit `version` field and `activeArtboardId` if missing.- if (version < 1) {- doc = migrateV0ToV1(doc);- }-- // Future migrations go here, e.g.:- // if (doc.version < 2) { doc = migrateV1ToV2(doc); }-- return doc;-}--function migrateV0ToV1(doc: Record<string, unknown>): Record<string, unknown> {- const updated: Record<string, unknown> = { ...doc };-- updated.version = 1;-- // Ensure activeArtboardId exists.- if (updated.activeArtboardId === undefined) {- const artboards = Array.isArray(updated.artboards) ? updated.artboards : [];- updated.activeArtboardId =- artboards.length > 0 && typeof artboards[0] === 'object' && artboards[0] !== null- ? (artboards[0] as Record<string, unknown>).id ?? null- : null;- }-- return updated;-}-+export * from '@openreel/image-core/migration';diff --git a/apps/image/src/services/project-schema.ts b/apps/image/src/services/project-schema.tsindex 8433cc66..3f28aa4b 100644--- a/apps/image/src/services/project-schema.ts+++ b/apps/image/src/services/project-schema.ts@@ -1,414 +1 @@-import { z } from 'zod';--// ── Primitives ──────────────────────────────────────────────────────────────--const TransformSchema = z.object({- x: z.number(),- y: z.number(),- width: z.number(),- height: z.number(),- rotation: z.number(),- scaleX: z.number(),- scaleY: z.number(),- skewX: z.number(),- skewY: z.number(),- opacity: z.number(),-});--const BlendModeSchema = z.object({- mode: z.enum([- 'normal', 'multiply', 'screen', 'overlay', 'darken', 'lighten',- 'color-dodge', 'color-burn', 'hard-light', 'soft-light', 'difference', 'exclusion',- ]),-});--const ShadowSchema = z.object({- enabled: z.boolean(),- color: z.string(),- blur: z.number(),- offsetX: z.number(),- offsetY: z.number(),-});--const InnerShadowSchema = z.object({- enabled: z.boolean(),- color: z.string(),- blur: z.number(),- offsetX: z.number(),- offsetY: z.number(),-});--const StrokeSchema = z.object({- enabled: z.boolean(),- color: z.string(),- width: z.number(),- style: z.enum(['solid', 'dashed', 'dotted']),-});--const GlowSchema = z.object({- enabled: z.boolean(),- color: z.string(),- blur: z.number(),- intensity: z.number(),-});--const FilterSchema = z.object({- brightness: z.number(),- contrast: z.number(),- saturation: z.number(),- hue: z.number(),- exposure: z.number(),- vibrance: z.number(),- highlights: z.number(),- shadows: z.number(),- clarity: z.number(),- blur: z.number(),- blurType: z.enum(['gaussian', 'motion', 'radial']),- blurAngle: z.number(),- sharpen: z.number(),- vignette: z.number(),- grain: z.number(),- sepia: z.number(),- invert: z.number(),-});--// ── Adjustments ──────────────────────────────────────────────────────────────--const LevelsChannelSchema = z.object({- inputBlack: z.number(),- inputWhite: z.number(),- gamma: z.number(),- outputBlack: z.number(),- outputWhite: z.number(),-});--const LevelsSchema = z.object({- enabled: z.boolean(),- master: LevelsChannelSchema,- red: LevelsChannelSchema,- green: LevelsChannelSchema,- blue: LevelsChannelSchema,-});--const CurvePointSchema = z.object({ input: z.number(), output: z.number() });--const CurvesChannelSchema = z.object({ points: z.array(CurvePointSchema) });--const CurvesSchema = z.object({- enabled: z.boolean(),- master: CurvesChannelSchema,- red: CurvesChannelSchema,- green: CurvesChannelSchema,- blue: CurvesChannelSchema,-});--const ColorBalanceValuesSchema = z.object({- cyanRed: z.number(),- magentaGreen: z.number(),- yellowBlue: z.number(),-});--const ColorBalanceSchema = z.object({- enabled: z.boolean(),- shadows: ColorBalanceValuesSchema,- midtones: ColorBalanceValuesSchema,- highlights: ColorBalanceValuesSchema,- preserveLuminosity: z.boolean(),-});--const SelectiveColorValuesSchema = z.object({- cyan: z.number(),- magenta: z.number(),- yellow: z.number(),- black: z.number(),-});--const SelectiveColorSchema = z.object({- enabled: z.boolean(),- method: z.enum(['relative', 'absolute']),- reds: SelectiveColorValuesSchema,- yellows: SelectiveColorValuesSchema,- greens: SelectiveColorValuesSchema,- cyans: SelectiveColorValuesSchema,- blues: SelectiveColorValuesSchema,- magentas: SelectiveColorValuesSchema,- whites: SelectiveColorValuesSchema,- neutrals: SelectiveColorValuesSchema,- blacks: SelectiveColorValuesSchema,-});--const BlackWhiteSchema = z.object({- enabled: z.boolean(),- reds: z.number(),- yellows: z.number(),- greens: z.number(),- cyans: z.number(),- blues: z.number(),- magentas: z.number(),- tintEnabled: z.boolean(),- tintHue: z.number(),- tintSaturation: z.number(),-});--const PhotoFilterSchema = z.object({- enabled: z.boolean(),- filter: z.enum(['warming-85', 'warming-81', 'cooling-80', 'cooling-82', 'custom']),- color: z.string(),- density: z.number(),- preserveLuminosity: z.boolean(),-});--const ChannelMixerChannelSchema = z.object({- red: z.number(),- green: z.number(),- blue: z.number(),- constant: z.number(),-});--const ChannelMixerSchema = z.object({- enabled: z.boolean(),- monochrome: z.boolean(),- red: ChannelMixerChannelSchema,- green: ChannelMixerChannelSchema,- blue: ChannelMixerChannelSchema,-});--const GradientMapStopSchema = z.object({ position: z.number(), color: z.string() });--const GradientMapSchema = z.object({- enabled: z.boolean(),- stops: z.array(GradientMapStopSchema),- reverse: z.boolean(),- dither: z.boolean(),-});--const PosterizeSchema = z.object({- enabled: z.boolean(),- levels: z.number(),-});--const ThresholdSchema = z.object({- enabled: z.boolean(),- level: z.number(),-});--// ── Mask ──────────────────────────────────────────────────────────────────────--const LayerMaskSchema = z.object({- id: z.string(),- type: z.enum(['pixel', 'vector']),- enabled: z.boolean(),- linked: z.boolean(),- density: z.number(),- feather: z.number(),- invert: z.boolean(),- data: z.string().nullable(),- vectorPath: z.array(z.object({ x: z.number(), y: z.number() })).nullable(),-});--// ── Layer base ────────────────────────────────────────────────────────────────--const BaseLayerSchema = z.object({- id: z.string(),- name: z.string(),- type: z.enum(['image', 'text', 'shape', 'group']),- visible: z.boolean(),- locked: z.boolean(),- transform: TransformSchema,- blendMode: BlendModeSchema,- shadow: ShadowSchema,- innerShadow: InnerShadowSchema,- stroke: StrokeSchema,- glow: GlowSchema,- filters: FilterSchema,- parentId: z.string().nullable(),- flipHorizontal: z.boolean(),- flipVertical: z.boolean(),- mask: LayerMaskSchema.nullable(),- clippingMask: z.boolean(),- levels: LevelsSchema,- curves: CurvesSchema,- colorBalance: ColorBalanceSchema,- selectiveColor: SelectiveColorSchema,- blackWhite: BlackWhiteSchema,- photoFilter: PhotoFilterSchema,- channelMixer: ChannelMixerSchema,- gradientMap: GradientMapSchema,- posterize: PosterizeSchema,- threshold: ThresholdSchema,-});--// ── Layer variants ────────────────────────────────────────────────────────────--const ImageLayerSchema = BaseLayerSchema.extend({- type: z.literal('image'),- sourceId: z.string(),- cropRect: z- .object({ x: z.number(), y: z.number(), width: z.number(), height: z.number() })- .nullable(),-});--const GradientStopSchema = z.object({ offset: z.number(), color: z.string() });--const GradientSchema = z.object({- type: z.enum(['linear', 'radial']),- angle: z.number(),- stops: z.array(GradientStopSchema),-});--const TextShadowSchema = z.object({- enabled: z.boolean(),- color: z.string(),- blur: z.number(),- offsetX: z.number(),- offsetY: z.number(),-});--const TextStyleSchema = z.object({- fontFamily: z.string(),- fontSize: z.number(),- fontWeight: z.number(),- fontStyle: z.enum(['normal', 'italic']),- textDecoration: z.enum(['none', 'underline', 'line-through']),- textAlign: z.enum(['left', 'center', 'right', 'justify']),- verticalAlign: z.enum(['top', 'middle', 'bottom']),- lineHeight: z.number(),- letterSpacing: z.number(),- fillType: z.enum(['solid', 'gradient']),- color: z.string(),- gradient: GradientSchema.nullable(),- strokeColor: z.string().nullable(),- strokeWidth: z.number(),- backgroundColor: z.string().nullable(),- backgroundPadding: z.number(),- backgroundRadius: z.number(),- textShadow: TextShadowSchema,-});--const TextLayerSchema = BaseLayerSchema.extend({- type: z.literal('text'),- content: z.string(),- style: TextStyleSchema,- autoSize: z.boolean(),-});--const CornerRadiusSchema = z.object({- topLeft: z.number(),- topRight: z.number(),- bottomRight: z.number(),- bottomLeft: z.number(),-});--const NoiseFillSchema = z.object({- baseColor: z.string(),- noiseColor: z.string(),- density: z.number(),- size: z.number(),-});--const ShapeStyleSchema = z.object({- fillType: z.enum(['solid', 'gradient', 'noise']),- fill: z.string().nullable(),- gradient: GradientSchema.nullable(),- noise: NoiseFillSchema.nullable(),- fillOpacity: z.number(),- stroke: z.string().nullable(),- strokeWidth: z.number(),- strokeOpacity: z.number(),- strokeDash: z.enum(['solid', 'dashed', 'dotted', 'dash-dot', 'long-dash']),- cornerRadius: z.number(),- individualCorners: z.boolean(),- corners: CornerRadiusSchema,-});--const ShapeLayerSchema = BaseLayerSchema.extend({- type: z.literal('shape'),- shapeType: z.enum([- 'rectangle', 'ellipse', 'triangle', 'polygon', 'star', 'line', 'arrow', 'path',- ]),- shapeStyle: ShapeStyleSchema,- points: z.array(z.object({ x: z.number(), y: z.number() })).optional(),- sides: z.number().optional(),- innerRadius: z.number().optional(),-});--const GroupLayerSchema = BaseLayerSchema.extend({- type: z.literal('group'),- childIds: z.array(z.string()),- expanded: z.boolean(),-});--export const LayerSchema = z.discriminatedUnion('type', [- ImageLayerSchema,- TextLayerSchema,- ShapeLayerSchema,- GroupLayerSchema,-]);--// ── Project types ─────────────────────────────────────────────────────────────--const CanvasSizeSchema = z.object({ width: z.number(), height: z.number() });--const CanvasBackgroundSchema = z.object({- type: z.enum(['color', 'gradient', 'image', 'transparent']),- color: z.string().optional(),- gradient: z- .object({- type: z.enum(['linear', 'radial']),- angle: z.number(),- stops: z.array(z.object({ offset: z.number(), color: z.string() })),- })- .optional(),- imageId: z.string().optional(),-});--export const ArtboardSchema = z.object({- id: z.string(),- name: z.string(),- size: CanvasSizeSchema,- background: CanvasBackgroundSchema,- layerIds: z.array(z.string()),- position: z.object({ x: z.number(), y: z.number() }),-});--const MediaAssetSchema = z.object({- id: z.string(),- name: z.string(),- type: z.enum(['image', 'svg']),- mimeType: z.string(),- size: z.number(),- width: z.number(),- height: z.number(),- thumbnailUrl: z.string(),- dataUrl: z.string().optional(),- blobUrl: z.string().optional(),-});--/** Current project schema (version 1). */-export const ProjectSchema = z.object({- id: z.string(),- name: z.string(),- createdAt: z.number(),- updatedAt: z.number(),- version: z.number(),- artboards: z.array(ArtboardSchema),- layers: z.record(z.string(), LayerSchema),- assets: z.record(z.string(), MediaAssetSchema),- activeArtboardId: z.string().nullable(),-});--export type ParsedProject = z.infer<typeof ProjectSchema>;--/**- * Validate an unknown value against the Project schema.- * Returns `{ success: true, data }` on success or `{ success: false, error }` on failure.- */-export function parseProject(- raw: unknown,-): { success: true; data: ParsedProject } | { success: false; error: string } {- const result = ProjectSchema.safeParse(raw);- if (result.success) {- return { success: true, data: result.data };- }- return { success: false, error: result.error.message };-}+export * from '@openreel/image-core/schema';diff --git a/apps/image/src/stores/project-store.ts b/apps/image/src/stores/project-store.tsindex cc96394b..033f2e11 100644--- a/apps/image/src/stores/project-store.ts+++ b/apps/image/src/stores/project-store.ts@@ -1,8 +1,16 @@import { create } from 'zustand';import { subscribeWithSelector } from 'zustand/middleware';import { immer } from 'zustand/middleware/immer';-import { parseProject } from '../services/project-schema';-import { migrateProject } from '../services/project-migration';+import {+ addLayerToProject,+ createProjectDocument,+ deserializeProject,+ duplicateLayerInProject,+ removeLayerFromProject,+ reorderArtboardLayers,+ updateLayerInProject,+ updateLayerTransformInProject,+} from '@openreel/image-core/operations';import {Project,Layer,@@ -120,32 +128,18 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(createProject: (name, size, background) => {const artboardId = generateId();- const project: Project = {+ const project = createProjectDocument({id: generateId(),+ artboardId,name,- createdAt: Date.now(),- updatedAt: Date.now(),- version: 1,- artboards: [- {- id: artboardId,- name: 'Artboard 1',- size,- background: background ?? { type: 'color', color: '#ffffff' },- layerIds: [],- position: { x: 0, y: 0 },- },- ],- layers: {},- assets: {},- activeArtboardId: artboardId,- };+ size,+ background,+ });set({ project, selectedLayerIds: [], selectedArtboardId: artboardId, isDirty: true });},loadProject: (project) => {- const migrated = migrateProject(project as unknown as Record<string, unknown>);- const parsed = parseProject(migrated);+ const parsed = deserializeProject(project as unknown as Record<string, unknown>);if (!parsed.success) {console.error('[project-store] Invalid project:', parsed.error);return;@@ -273,10 +267,8 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(posterize: { ...DEFAULT_POSTERIZE },threshold: { ...DEFAULT_THRESHOLD },};- state.project.layers[id] = layer;- artboard.layerIds.unshift(id);+ state.project = addLayerToProject(state.project, state.selectedArtboardId, layer);state.selectedLayerIds = [id];- state.project.updatedAt = Date.now();state.isDirty = true;}}@@ -329,10 +321,8 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(posterize: { ...DEFAULT_POSTERIZE },threshold: { ...DEFAULT_THRESHOLD },};- state.project.layers[id] = layer;- artboard.layerIds.unshift(id);+ state.project = addLayerToProject(state.project, state.selectedArtboardId, layer);state.selectedLayerIds = [id];- state.project.updatedAt = Date.now();state.isDirty = true;}}@@ -384,10 +374,8 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(posterize: { ...DEFAULT_POSTERIZE },threshold: { ...DEFAULT_THRESHOLD },};- state.project.layers[id] = layer;- artboard.layerIds.unshift(id);+ state.project = addLayerToProject(state.project, state.selectedArtboardId, layer);state.selectedLayerIds = [id];- state.project.updatedAt = Date.now();state.isDirty = true;}}@@ -456,10 +444,8 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(posterize: { ...DEFAULT_POSTERIZE },threshold: { ...DEFAULT_THRESHOLD },};- state.project.layers[id] = layer;- artboard.layerIds.unshift(id);+ state.project = addLayerToProject(state.project, state.selectedArtboardId, layer);state.selectedLayerIds = [id];- state.project.updatedAt = Date.now();state.isDirty = true;}}@@ -536,13 +522,15 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(posterize: { ...DEFAULT_POSTERIZE },threshold: { ...DEFAULT_THRESHOLD },};-- state.project.layers[id] = layer;const firstChildIndex = artboard.layerIds.findIndex((lid) => childIds.includes(lid));artboard.layerIds = artboard.layerIds.filter((lid) => !childIds.includes(lid));- artboard.layerIds.splice(firstChildIndex, 0, id);+ state.project = addLayerToProject(+ state.project,+ state.selectedArtboardId,+ layer,+ Math.max(firstChildIndex, 0),+ );state.selectedLayerIds = [id];- state.project.updatedAt = Date.now();state.isDirty = true;}}@@ -553,19 +541,9 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(removeLayer: (layerId) => {set((state) => {if (state.project) {- const layer = state.project.layers[layerId];- if (layer) {- if (layer.type === 'group') {- (layer as GroupLayer).childIds.forEach((childId) => {- delete state.project!.layers[childId];- });- }- delete state.project.layers[layerId];- state.project.artboards.forEach((artboard) => {- artboard.layerIds = artboard.layerIds.filter((id) => id !== layerId);- });+ if (state.project.layers[layerId]) {+ state.project = removeLayerFromProject(state.project, layerId);state.selectedLayerIds = state.selectedLayerIds.filter((id) => id !== layerId);- state.project.updatedAt = Date.now();state.isDirty = true;}}@@ -579,10 +557,8 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(updateLayer: (layerId, updates) => {set((state) => {if (state.project) {- const layer = state.project.layers[layerId];- if (layer) {- Object.assign(layer, updates);- state.project.updatedAt = Date.now();+ if (state.project.layers[layerId]) {+ state.project = updateLayerInProject(state.project, layerId, updates);state.isDirty = true;}}@@ -592,10 +568,8 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(updateLayerTransform: (layerId, transform) => {set((state) => {if (state.project) {- const layer = state.project.layers[layerId];- if (layer) {- Object.assign(layer.transform, transform);- state.project.updatedAt = Date.now();+ if (state.project.layers[layerId]) {+ state.project = updateLayerTransformInProject(state.project, layerId, transform);state.isDirty = true;}}@@ -606,29 +580,16 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(const { project, selectedArtboardId } = get();if (!project || !selectedArtboardId) return null;- const layer = project.layers[layerId];- if (!layer) return null;-const newId = generateId();+ const duplicated = duplicateLayerInProject(project, selectedArtboardId, layerId, newId);+ if (!duplicated) return null;+set((state) => {- if (state.project) {- const artboard = state.project.artboards.find((a) => a.id === selectedArtboardId);- if (artboard) {- const newLayer = JSON.parse(JSON.stringify(layer));- newLayer.id = newId;- newLayer.name = `${layer.name} copy`;- newLayer.transform.x += 20;- newLayer.transform.y += 20;- state.project.layers[newId] = newLayer;- const originalIndex = artboard.layerIds.indexOf(layerId);- artboard.layerIds.splice(originalIndex, 0, newId);- state.selectedLayerIds = [newId];- state.project.updatedAt = Date.now();- state.isDirty = true;- }- }+ state.project = duplicated.project;+ state.selectedLayerIds = [duplicated.duplicatedLayerId];+ state.isDirty = true;});- return newId;+ return duplicated.duplicatedLayerId;},duplicateLayers: (layerIds) => {@@ -678,8 +639,9 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(if (artboard) {const index = artboard.layerIds.indexOf(layerId);if (index > 0) {- [artboard.layerIds[index - 1], artboard.layerIds[index]] = [artboard.layerIds[index], artboard.layerIds[index - 1]];- state.project.updatedAt = Date.now();+ const layerIds = [...artboard.layerIds];+ [layerIds[index - 1], layerIds[index]] = [layerIds[index], layerIds[index - 1]];+ state.project = reorderArtboardLayers(state.project, state.selectedArtboardId, layerIds);state.isDirty = true;}}@@ -694,8 +656,9 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(if (artboard) {const index = artboard.layerIds.indexOf(layerId);if (index < artboard.layerIds.length - 1) {- [artboard.layerIds[index], artboard.layerIds[index + 1]] = [artboard.layerIds[index + 1], artboard.layerIds[index]];- state.project.updatedAt = Date.now();+ const layerIds = [...artboard.layerIds];+ [layerIds[index], layerIds[index + 1]] = [layerIds[index + 1], layerIds[index]];+ state.project = reorderArtboardLayers(state.project, state.selectedArtboardId, layerIds);state.isDirty = true;}}@@ -708,9 +671,9 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(if (state.project && state.selectedArtboardId) {const artboard = state.project.artboards.find((a) => a.id === state.selectedArtboardId);if (artboard) {- artboard.layerIds = artboard.layerIds.filter((id) => id !== layerId);- artboard.layerIds.unshift(layerId);- state.project.updatedAt = Date.now();+ const layerIds = artboard.layerIds.filter((id) => id !== layerId);+ layerIds.unshift(layerId);+ state.project = reorderArtboardLayers(state.project, state.selectedArtboardId, layerIds);state.isDirty = true;}}@@ -722,9 +685,9 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(if (state.project && state.selectedArtboardId) {const artboard = state.project.artboards.find((a) => a.id === state.selectedArtboardId);if (artboard) {- artboard.layerIds = artboard.layerIds.filter((id) => id !== layerId);- artboard.layerIds.push(layerId);- state.project.updatedAt = Date.now();+ const layerIds = artboard.layerIds.filter((id) => id !== layerId);+ layerIds.push(layerId);+ state.project = reorderArtboardLayers(state.project, state.selectedArtboardId, layerIds);state.isDirty = true;}}@@ -734,12 +697,8 @@ export const useProjectStore = create<ProjectState & ProjectActions>()(reorderLayers: (layerIds) => {set((state) => {if (state.project && state.selectedArtboardId) {- const artboard = state.project.artboards.find((a) => a.id === state.selectedArtboardId);- if (artboard) {- artboard.layerIds = layerIds;- state.project.updatedAt = Date.now();- state.isDirty = true;- }+ state.project = reorderArtboardLayers(state.project, state.selectedArtboardId, layerIds);+ state.isDirty = true;}});},diff --git a/apps/image/src/types/adjustments.ts b/apps/image/src/types/adjustments.tsindex 3e45d845..5b85618d 100644--- a/apps/image/src/types/adjustments.ts+++ b/apps/image/src/types/adjustments.ts@@ -1,620 +1 @@-export interface LevelsChannel {- inputBlack: number;- inputWhite: number;- gamma: number;- outputBlack: number;- outputWhite: number;-}--export interface LevelsAdjustment {- enabled: boolean;- master: LevelsChannel;- red: LevelsChannel;- green: LevelsChannel;- blue: LevelsChannel;-}--export interface CurvePoint {- input: number;- output: number;-}--export interface CurvesChannel {- points: CurvePoint[];-}--export interface CurvesAdjustment {- enabled: boolean;- master: CurvesChannel;- red: CurvesChannel;- green: CurvesChannel;- blue: CurvesChannel;-}--export interface ColorBalanceValues {- cyanRed: number;- magentaGreen: number;- yellowBlue: number;-}--export interface ColorBalanceAdjustment {- enabled: boolean;- shadows: ColorBalanceValues;- midtones: ColorBalanceValues;- highlights: ColorBalanceValues;- preserveLuminosity: boolean;-}--export interface SelectiveColorValues {- cyan: number;- magenta: number;- yellow: number;- black: number;-}--export type SelectiveColorTarget =- | 'reds'- | 'yellows'- | 'greens'- | 'cyans'- | 'blues'- | 'magentas'- | 'whites'- | 'neutrals'- | 'blacks';--export interface SelectiveColorAdjustment {- enabled: boolean;- method: 'relative' | 'absolute';- reds: SelectiveColorValues;- yellows: SelectiveColorValues;- greens: SelectiveColorValues;- cyans: SelectiveColorValues;- blues: SelectiveColorValues;- magentas: SelectiveColorValues;- whites: SelectiveColorValues;- neutrals: SelectiveColorValues;- blacks: SelectiveColorValues;-}--export interface BlackWhiteAdjustment {- enabled: boolean;- reds: number;- yellows: number;- greens: number;- cyans: number;- blues: number;- magentas: number;- tintEnabled: boolean;- tintHue: number;- tintSaturation: number;-}--export interface GradientMapStop {- position: number;- color: string;-}--export interface GradientMapAdjustment {- enabled: boolean;- stops: GradientMapStop[];- reverse: boolean;- dither: boolean;-}--export interface PosterizeAdjustment {- enabled: boolean;- levels: number;-}--export interface ThresholdAdjustment {- enabled: boolean;- level: number;-}--export interface PhotoFilterAdjustment {- enabled: boolean;- filter: 'warming-85' | 'warming-81' | 'cooling-80' | 'cooling-82' | 'custom';- color: string;- density: number;- preserveLuminosity: boolean;-}--export interface ChannelMixerChannel {- red: number;- green: number;- blue: number;- constant: number;-}--export interface ChannelMixerAdjustment {- enabled: boolean;- monochrome: boolean;- red: ChannelMixerChannel;- green: ChannelMixerChannel;- blue: ChannelMixerChannel;-}--export const DEFAULT_LEVELS_CHANNEL: LevelsChannel = {- inputBlack: 0,- inputWhite: 255,- gamma: 1.0,- outputBlack: 0,- outputWhite: 255,-};--export const DEFAULT_LEVELS: LevelsAdjustment = {- enabled: false,- master: { ...DEFAULT_LEVELS_CHANNEL },- red: { ...DEFAULT_LEVELS_CHANNEL },- green: { ...DEFAULT_LEVELS_CHANNEL },- blue: { ...DEFAULT_LEVELS_CHANNEL },-};--export const DEFAULT_CURVES_CHANNEL: CurvesChannel = {- points: [- { input: 0, output: 0 },- { input: 255, output: 255 },- ],-};--export const DEFAULT_CURVES: CurvesAdjustment = {- enabled: false,- master: { points: [{ input: 0, output: 0 }, { input: 255, output: 255 }] },- red: { points: [{ input: 0, output: 0 }, { input: 255, output: 255 }] },- green: { points: [{ input: 0, output: 0 }, { input: 255, output: 255 }] },- blue: { points: [{ input: 0, output: 0 }, { input: 255, output: 255 }] },-};--export const DEFAULT_COLOR_BALANCE_VALUES: ColorBalanceValues = {- cyanRed: 0,- magentaGreen: 0,- yellowBlue: 0,-};--export const DEFAULT_COLOR_BALANCE: ColorBalanceAdjustment = {- enabled: false,- shadows: { ...DEFAULT_COLOR_BALANCE_VALUES },- midtones: { ...DEFAULT_COLOR_BALANCE_VALUES },- highlights: { ...DEFAULT_COLOR_BALANCE_VALUES },- preserveLuminosity: true,-};--export const DEFAULT_SELECTIVE_COLOR_VALUES: SelectiveColorValues = {- cyan: 0,- magenta: 0,- yellow: 0,- black: 0,-};--export const DEFAULT_SELECTIVE_COLOR: SelectiveColorAdjustment = {- enabled: false,- method: 'relative',- reds: { ...DEFAULT_SELECTIVE_COLOR_VALUES },- yellows: { ...DEFAULT_SELECTIVE_COLOR_VALUES },- greens: { ...DEFAULT_SELECTIVE_COLOR_VALUES },- cyans: { ...DEFAULT_SELECTIVE_COLOR_VALUES },- blues: { ...DEFAULT_SELECTIVE_COLOR_VALUES },- magentas: { ...DEFAULT_SELECTIVE_COLOR_VALUES },- whites: { ...DEFAULT_SELECTIVE_COLOR_VALUES },- neutrals: { ...DEFAULT_SELECTIVE_COLOR_VALUES },- blacks: { ...DEFAULT_SELECTIVE_COLOR_VALUES },-};--export const DEFAULT_BLACK_WHITE: BlackWhiteAdjustment = {- enabled: false,- reds: 40,- yellows: 60,- greens: 40,- cyans: 60,- blues: 20,- magentas: 80,- tintEnabled: false,- tintHue: 35,- tintSaturation: 25,-};--export const DEFAULT_GRADIENT_MAP: GradientMapAdjustment = {- enabled: false,- stops: [- { position: 0, color: '#000000' },- { position: 1, color: '#ffffff' },- ],- reverse: false,- dither: false,-};--export const DEFAULT_POSTERIZE: PosterizeAdjustment = {- enabled: false,- levels: 4,-};--export const DEFAULT_THRESHOLD: ThresholdAdjustment = {- enabled: false,- level: 128,-};--export const DEFAULT_PHOTO_FILTER: PhotoFilterAdjustment = {- enabled: false,- filter: 'warming-85',- color: '#ec8a00',- density: 25,- preserveLuminosity: true,-};--export const DEFAULT_CHANNEL_MIXER: ChannelMixerAdjustment = {- enabled: false,- monochrome: false,- red: { red: 100, green: 0, blue: 0, constant: 0 },- green: { red: 0, green: 100, blue: 0, constant: 0 },- blue: { red: 0, green: 0, blue: 100, constant: 0 },-};--export function applyLevels(value: number, channel: LevelsChannel): number {- let v = value;-- v = Math.max(channel.inputBlack, Math.min(channel.inputWhite, v));- v = ((v - channel.inputBlack) / (channel.inputWhite - channel.inputBlack)) * 255;-- v = 255 * Math.pow(v / 255, 1 / channel.gamma);-- v = channel.outputBlack + (v / 255) * (channel.outputWhite - channel.outputBlack);-- return Math.max(0, Math.min(255, Math.round(v)));-}--export function interpolateCurve(value: number, points: CurvePoint[]): number {- if (points.length === 0) return value;- if (points.length === 1) return points[0].output;-- const sortedPoints = [...points].sort((a, b) => a.input - b.input);-- if (value <= sortedPoints[0].input) return sortedPoints[0].output;- if (value >= sortedPoints[sortedPoints.length - 1].input) {- return sortedPoints[sortedPoints.length - 1].output;- }-- for (let i = 0; i < sortedPoints.length - 1; i++) {- const p1 = sortedPoints[i];- const p2 = sortedPoints[i + 1];-- if (value >= p1.input && value <= p2.input) {- const t = (value - p1.input) / (p2.input - p1.input);-- if (sortedPoints.length >= 4 && i > 0 && i < sortedPoints.length - 2) {- const p0 = sortedPoints[i - 1];- const p3 = sortedPoints[i + 2];- return catmullRomInterpolate(p0.output, p1.output, p2.output, p3.output, t);- }-- return p1.output + t * (p2.output - p1.output);- }- }-- return value;-}--function catmullRomInterpolate(- p0: number,- p1: number,- p2: number,- p3: number,- t: number-): number {- const t2 = t * t;- const t3 = t2 * t;-- return (- 0.5 *- (2 * p1 +- (-p0 + p2) * t +- (2 * p0 - 5 * p1 + 4 * p2 - p3) * t2 +- (-p0 + 3 * p1 - 3 * p2 + p3) * t3)- );-}--export function applyLevelsToImageData(- imageData: ImageData,- levels: LevelsAdjustment-): ImageData {- if (!levels.enabled) return imageData;-- const result = new ImageData(imageData.width, imageData.height);-- for (let i = 0; i < imageData.data.length; i += 4) {- let r = imageData.data[i];- let g = imageData.data[i + 1];- let b = imageData.data[i + 2];-- r = applyLevels(r, levels.master);- g = applyLevels(g, levels.master);- b = applyLevels(b, levels.master);-- r = applyLevels(r, levels.red);- g = applyLevels(g, levels.green);- b = applyLevels(b, levels.blue);-- result.data[i] = r;- result.data[i + 1] = g;- result.data[i + 2] = b;- result.data[i + 3] = imageData.data[i + 3];- }-- return result;-}--export function applyCurvesToImageData(- imageData: ImageData,- curves: CurvesAdjustment-): ImageData {- if (!curves.enabled) return imageData;-- const result = new ImageData(imageData.width, imageData.height);-- for (let i = 0; i < imageData.data.length; i += 4) {- let r = imageData.data[i];- let g = imageData.data[i + 1];- let b = imageData.data[i + 2];-- r = interpolateCurve(r, curves.master.points);- g = interpolateCurve(g, curves.master.points);- b = interpolateCurve(b, curves.master.points);-- r = interpolateCurve(r, curves.red.points);- g = interpolateCurve(g, curves.green.points);- b = interpolateCurve(b, curves.blue.points);-- result.data[i] = Math.max(0, Math.min(255, Math.round(r)));- result.data[i + 1] = Math.max(0, Math.min(255, Math.round(g)));- result.data[i + 2] = Math.max(0, Math.min(255, Math.round(b)));- result.data[i + 3] = imageData.data[i + 3];- }-- return result;-}--export function applyColorBalanceToImageData(- imageData: ImageData,- colorBalance: ColorBalanceAdjustment-): ImageData {- if (!colorBalance.enabled) return imageData;-- const result = new ImageData(imageData.width, imageData.height);-- for (let i = 0; i < imageData.data.length; i += 4) {- let r = imageData.data[i];- let g = imageData.data[i + 1];- let b = imageData.data[i + 2];-- const luminance = 0.299 * r + 0.587 * g + 0.114 * b;-- const shadowWeight = Math.max(0, 1 - luminance / 128);- const highlightWeight = Math.max(0, (luminance - 128) / 127);- const midtoneWeight = 1 - shadowWeight - highlightWeight;-- const adjustR =- colorBalance.shadows.cyanRed * shadowWeight +- colorBalance.midtones.cyanRed * midtoneWeight +- colorBalance.highlights.cyanRed * highlightWeight;-- const adjustG =- colorBalance.shadows.magentaGreen * shadowWeight +- colorBalance.midtones.magentaGreen * midtoneWeight +- colorBalance.highlights.magentaGreen * highlightWeight;-- const adjustB =- colorBalance.shadows.yellowBlue * shadowWeight +- colorBalance.midtones.yellowBlue * midtoneWeight +- colorBalance.highlights.yellowBlue * highlightWeight;-- r = Math.max(0, Math.min(255, r + adjustR));- g = Math.max(0, Math.min(255, g + adjustG));- b = Math.max(0, Math.min(255, b + adjustB));-- if (colorBalance.preserveLuminosity) {- const newLuminance = 0.299 * r + 0.587 * g + 0.114 * b;- if (newLuminance > 0) {- const factor = luminance / newLuminance;- r = Math.max(0, Math.min(255, r * factor));- g = Math.max(0, Math.min(255, g * factor));- b = Math.max(0, Math.min(255, b * factor));- }- }-- result.data[i] = Math.round(r);- result.data[i + 1] = Math.round(g);- result.data[i + 2] = Math.round(b);- result.data[i + 3] = imageData.data[i + 3];- }-- return result;-}--export function applyThresholdToImageData(- imageData: ImageData,- threshold: ThresholdAdjustment-): ImageData {- if (!threshold.enabled) return imageData;-- const result = new ImageData(imageData.width, imageData.height);-- for (let i = 0; i < imageData.data.length; i += 4) {- const r = imageData.data[i];- const g = imageData.data[i + 1];- const b = imageData.data[i + 2];-- const luminance = 0.299 * r + 0.587 * g + 0.114 * b;- const value = luminance >= threshold.level ? 255 : 0;-- result.data[i] = value;- result.data[i + 1] = value;- result.data[i + 2] = value;- result.data[i + 3] = imageData.data[i + 3];- }-- return result;-}--export function applyPosterizeToImageData(- imageData: ImageData,- posterize: PosterizeAdjustment-): ImageData {- if (!posterize.enabled || posterize.levels < 2) return imageData;-- const result = new ImageData(imageData.width, imageData.height);- const step = 255 / (posterize.levels - 1);-- for (let i = 0; i < imageData.data.length; i += 4) {- result.data[i] = Math.round(Math.round(imageData.data[i] / step) * step);- result.data[i + 1] = Math.round(Math.round(imageData.data[i + 1] / step) * step);- result.data[i + 2] = Math.round(Math.round(imageData.data[i + 2] / step) * step);- result.data[i + 3] = imageData.data[i + 3];- }-- return result;-}--export function applyBlackWhiteToImageData(- imageData: ImageData,- bw: BlackWhiteAdjustment-): ImageData {- if (!bw.enabled) return imageData;-- const result = new ImageData(imageData.width, imageData.height);-- for (let i = 0; i < imageData.data.length; i += 4) {- const r = imageData.data[i];- const g = imageData.data[i + 1];- const b = imageData.data[i + 2];-- const max = Math.max(r, g, b);- const min = Math.min(r, g, b);- const delta = max - min;-- let hue = 0;- if (delta > 0) {- if (max === r) {- hue = ((g - b) / delta) % 6;- } else if (max === g) {- hue = (b - r) / delta + 2;- } else {- hue = (r - g) / delta + 4;- }- hue *= 60;- if (hue < 0) hue += 360;- }-- let weight = 0;- if (hue < 30 || hue >= 330) {- weight = bw.reds / 100;- } else if (hue < 90) {- weight = bw.yellows / 100;- } else if (hue < 150) {- weight = bw.greens / 100;- } else if (hue < 210) {- weight = bw.cyans / 100;- } else if (hue < 270) {- weight = bw.blues / 100;- } else {- weight = bw.magentas / 100;- }-- let gray = 0.299 * r + 0.587 * g + 0.114 * b;- gray = gray * (1 + weight * 0.5);- gray = Math.max(0, Math.min(255, gray));-- let finalR = gray;- let finalG = gray;- let finalB = gray;-- if (bw.tintEnabled) {- const tintH = bw.tintHue / 360;- const tintS = bw.tintSaturation / 100;- const tintL = gray / 255;-- const c = (1 - Math.abs(2 * tintL - 1)) * tintS;- const x = c * (1 - Math.abs((tintH * 6) % 2 - 1));- const m = tintL - c / 2;-- let rTint = 0, gTint = 0, bTint = 0;- const h6 = tintH * 6;- if (h6 < 1) { rTint = c; gTint = x; }- else if (h6 < 2) { rTint = x; gTint = c; }- else if (h6 < 3) { gTint = c; bTint = x; }- else if (h6 < 4) { gTint = x; bTint = c; }- else if (h6 < 5) { rTint = x; bTint = c; }- else { rTint = c; bTint = x; }-- finalR = (rTint + m) * 255;- finalG = (gTint + m) * 255;- finalB = (bTint + m) * 255;- }-- result.data[i] = Math.round(finalR);- result.data[i + 1] = Math.round(finalG);- result.data[i + 2] = Math.round(finalB);- result.data[i + 3] = imageData.data[i + 3];- }-- return result;-}--export function applyGradientMapToImageData(- imageData: ImageData,- gradientMap: GradientMapAdjustment-): ImageData {- if (!gradientMap.enabled || gradientMap.stops.length < 2) return imageData;-- const result = new ImageData(imageData.width, imageData.height);-- const stops = gradientMap.reverse- ? [...gradientMap.stops].reverse().map((s, i, arr) => ({- ...s,- position: 1 - arr[arr.length - 1 - i].position,- }))- : gradientMap.stops;-- const sortedStops = [...stops].sort((a, b) => a.position - b.position);-- for (let i = 0; i < imageData.data.length; i += 4) {- const r = imageData.data[i];- const g = imageData.data[i + 1];- const b = imageData.data[i + 2];-- const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;-- let color1 = sortedStops[0];- let color2 = sortedStops[sortedStops.length - 1];-- for (let j = 0; j < sortedStops.length - 1; j++) {- if (luminance >= sortedStops[j].position && luminance <= sortedStops[j + 1].position) {- color1 = sortedStops[j];- color2 = sortedStops[j + 1];- break;- }- }-- const t = (luminance - color1.position) / (color2.position - color1.position || 1);-- const c1 = hexToRgb(color1.color);- const c2 = hexToRgb(color2.color);-- result.data[i] = Math.round(c1.r + t * (c2.r - c1.r));- result.data[i + 1] = Math.round(c1.g + t * (c2.g - c1.g));- result.data[i + 2] = Math.round(c1.b + t * (c2.b - c1.b));- result.data[i + 3] = imageData.data[i + 3];- }-- return result;-}--function hexToRgb(hex: string): { r: number; g: number; b: number } {- const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);- return result- ? {- r: parseInt(result[1], 16),- g: parseInt(result[2], 16),- b: parseInt(result[3], 16),- }- : { r: 0, g: 0, b: 0 };-}+export * from '@openreel/image-core/adjustments';diff --git a/apps/image/src/types/mask.ts b/apps/image/src/types/mask.tsindex e13ae922..efc8e521 100644--- a/apps/image/src/types/mask.ts+++ b/apps/image/src/types/mask.ts@@ -1,168 +1 @@-export type MaskType = 'pixel' | 'vector';--export interface LayerMask {- id: string;- type: MaskType;- enabled: boolean;- linked: boolean;- density: number;- feather: number;- invert: boolean;- data: string | null;- vectorPath: { x: number; y: number }[] | null;-}--export const DEFAULT_LAYER_MASK: LayerMask = {- id: '',- type: 'pixel',- enabled: true,- linked: true,- density: 100,- feather: 0,- invert: false,- data: null,- vectorPath: null,-};--export function createMaskFromSelection(- selectionPath: { x: number; y: number }[],- width: number,- height: number,- feather: number = 0-): string {- const canvas = new OffscreenCanvas(width, height);- const ctx = canvas.getContext('2d')!;-- ctx.fillStyle = 'white';- ctx.beginPath();-- if (selectionPath.length > 0) {- ctx.moveTo(selectionPath[0].x, selectionPath[0].y);- for (let i = 1; i < selectionPath.length; i++) {- ctx.lineTo(selectionPath[i].x, selectionPath[i].y);- }- ctx.closePath();- ctx.fill();- }-- if (feather > 0) {- const tempCanvas = new OffscreenCanvas(width, height);- const tempCtx = tempCanvas.getContext('2d')!;- tempCtx.filter = `blur(${feather}px)`;- tempCtx.drawImage(canvas, 0, 0);-- ctx.clearRect(0, 0, width, height);- ctx.drawImage(tempCanvas, 0, 0);- }-- return canvas.convertToBlob().then(() => {- const reader = new FileReader();- return new Promise<string>((resolve) => {- canvas.convertToBlob().then((blob) => {- reader.onload = () => resolve(reader.result as string);- reader.readAsDataURL(blob);- });- });- }) as unknown as string;-}--export function createMaskFromImageData(imageData: ImageData): string {- const canvas = new OffscreenCanvas(imageData.width, imageData.height);- const ctx = canvas.getContext('2d')!;- ctx.putImageData(imageData, 0, 0);-- return canvas.convertToBlob().then(() => {- return new Promise<string>((resolve) => {- canvas.convertToBlob().then((blob) => {- const reader = new FileReader();- reader.onload = () => resolve(reader.result as string);- reader.readAsDataURL(blob);- });- });- }) as unknown as string;-}--export function applyMaskToImageData(- imageData: ImageData,- mask: LayerMask,- maskImage: HTMLImageElement | null-): ImageData {- if (!mask.enabled || !maskImage) {- return imageData;- }-- const canvas = new OffscreenCanvas(imageData.width, imageData.height);- const ctx = canvas.getContext('2d')!;-- ctx.drawImage(maskImage, 0, 0, imageData.width, imageData.height);- const maskData = ctx.getImageData(0, 0, imageData.width, imageData.height);-- const result = new ImageData(imageData.width, imageData.height);- const density = mask.density / 100;-- for (let i = 0; i < imageData.data.length; i += 4) {- result.data[i] = imageData.data[i];- result.data[i + 1] = imageData.data[i + 1];- result.data[i + 2] = imageData.data[i + 2];-- let maskAlpha = maskData.data[i];- if (mask.invert) {- maskAlpha = 255 - maskAlpha;- }- maskAlpha = Math.round(maskAlpha * density);-- result.data[i + 3] = Math.round((imageData.data[i + 3] * maskAlpha) / 255);- }-- return result;-}--export function invertMask(maskDataUrl: string, width: number, height: number): Promise<string> {- return new Promise((resolve) => {- const img = new Image();- img.onload = () => {- const canvas = new OffscreenCanvas(width, height);- const ctx = canvas.getContext('2d')!;- ctx.drawImage(img, 0, 0);-- const imageData = ctx.getImageData(0, 0, width, height);- for (let i = 0; i < imageData.data.length; i += 4) {- imageData.data[i] = 255 - imageData.data[i];- imageData.data[i + 1] = 255 - imageData.data[i + 1];- imageData.data[i + 2] = 255 - imageData.data[i + 2];- }- ctx.putImageData(imageData, 0, 0);-- canvas.convertToBlob().then((blob) => {- const reader = new FileReader();- reader.onload = () => resolve(reader.result as string);- reader.readAsDataURL(blob);- });- };- img.src = maskDataUrl;- });-}--export function featherMask(- maskDataUrl: string,- width: number,- height: number,- featherAmount: number-): Promise<string> {- return new Promise((resolve) => {- const img = new Image();- img.onload = () => {- const canvas = new OffscreenCanvas(width, height);- const ctx = canvas.getContext('2d')!;- ctx.filter = `blur(${featherAmount}px)`;- ctx.drawImage(img, 0, 0);-- canvas.convertToBlob().then((blob) => {- const reader = new FileReader();- reader.onload = () => resolve(reader.result as string);- reader.readAsDataURL(blob);- });- };- img.src = maskDataUrl;- });-}+export * from '@openreel/image-core/mask';diff --git a/apps/image/src/types/project.ts b/apps/image/src/types/project.tsindex d1d8514d..be211c83 100644--- a/apps/image/src/types/project.ts+++ b/apps/image/src/types/project.ts@@ -1,437 +1 @@-import type { LayerMask } from './mask';-import type {- LevelsAdjustment,- CurvesAdjustment,- ColorBalanceAdjustment,- SelectiveColorAdjustment,- BlackWhiteAdjustment,- PhotoFilterAdjustment,- ChannelMixerAdjustment,- GradientMapAdjustment,- PosterizeAdjustment,- ThresholdAdjustment,-} from './adjustments';--export type LayerType = 'image' | 'text' | 'shape' | 'group';--export interface Transform {- x: number;- y: number;- width: number;- height: number;- rotation: number;- scaleX: number;- scaleY: number;- skewX: number;- skewY: number;- opacity: number;-}--export interface BlendMode {- mode: 'normal' | 'multiply' | 'screen' | 'overlay' | 'darken' | 'lighten' | 'color-dodge' | 'color-burn' | 'hard-light' | 'soft-light' | 'difference' | 'exclusion';-}--export interface Shadow {- enabled: boolean;- color: string;- blur: number;- offsetX: number;- offsetY: number;-}--export interface Stroke {- enabled: boolean;- color: string;- width: number;- style: 'solid' | 'dashed' | 'dotted';-}--export interface Glow {- enabled: boolean;- color: string;- blur: number;- intensity: number;-}--export interface InnerShadow {- enabled: boolean;- color: string;- blur: number;- offsetX: number;- offsetY: number;-}--export type BlurType = 'gaussian' | 'motion' | 'radial';--export interface Filter {- brightness: number;- contrast: number;- saturation: number;- hue: number;- exposure: number;- vibrance: number;- highlights: number;- shadows: number;- clarity: number;- blur: number;- blurType: BlurType;- blurAngle: number;- sharpen: number;- vignette: number;- grain: number;- sepia: number;- invert: number;-}--export interface BaseLayer {- id: string;- name: string;- type: LayerType;- visible: boolean;- locked: boolean;- transform: Transform;- blendMode: BlendMode;- shadow: Shadow;- innerShadow: InnerShadow;- stroke: Stroke;- glow: Glow;- filters: Filter;- parentId: string | null;- flipHorizontal: boolean;- flipVertical: boolean;- mask: LayerMask | null;- clippingMask: boolean;- levels: LevelsAdjustment;- curves: CurvesAdjustment;- colorBalance: ColorBalanceAdjustment;- selectiveColor: SelectiveColorAdjustment;- blackWhite: BlackWhiteAdjustment;- photoFilter: PhotoFilterAdjustment;- channelMixer: ChannelMixerAdjustment;- gradientMap: GradientMapAdjustment;- posterize: PosterizeAdjustment;- threshold: ThresholdAdjustment;-}--export interface ImageLayer extends BaseLayer {- type: 'image';- sourceId: string;- cropRect: { x: number; y: number; width: number; height: number } | null;-}--export type TextFillType = 'solid' | 'gradient';--export interface TextShadow {- enabled: boolean;- color: string;- blur: number;- offsetX: number;- offsetY: number;-}--export interface TextStyle {- fontFamily: string;- fontSize: number;- fontWeight: number;- fontStyle: 'normal' | 'italic';- textDecoration: 'none' | 'underline' | 'line-through';- textAlign: 'left' | 'center' | 'right' | 'justify';- verticalAlign: 'top' | 'middle' | 'bottom';- lineHeight: number;- letterSpacing: number;- fillType: TextFillType;- color: string;- gradient: Gradient | null;- strokeColor: string | null;- strokeWidth: number;- backgroundColor: string | null;- backgroundPadding: number;- backgroundRadius: number;- textShadow: TextShadow;-}--export interface TextLayer extends BaseLayer {- type: 'text';- content: string;- style: TextStyle;- autoSize: boolean;-}--export type ShapeType = 'rectangle' | 'ellipse' | 'triangle' | 'polygon' | 'star' | 'line' | 'arrow' | 'path';--export interface GradientStop {- offset: number;- color: string;-}--export interface Gradient {- type: 'linear' | 'radial';- angle: number;- stops: GradientStop[];-}--export type FillType = 'solid' | 'gradient' | 'noise';--export type StrokeDashType = 'solid' | 'dashed' | 'dotted' | 'dash-dot' | 'long-dash';--export interface CornerRadius {- topLeft: number;- topRight: number;- bottomRight: number;- bottomLeft: number;-}--export interface NoiseFill {- baseColor: string;- noiseColor: string;- density: number;- size: number;-}--export interface ShapeStyle {- fillType: FillType;- fill: string | null;- gradient: Gradient | null;- noise: NoiseFill | null;- fillOpacity: number;- stroke: string | null;- strokeWidth: number;- strokeOpacity: number;- strokeDash: StrokeDashType;- cornerRadius: number;- individualCorners: boolean;- corners: CornerRadius;-}--export interface ShapeLayer extends BaseLayer {- type: 'shape';- shapeType: ShapeType;- shapeStyle: ShapeStyle;- points?: { x: number; y: number }[];- sides?: number;- innerRadius?: number;-}--export interface GroupLayer extends BaseLayer {- type: 'group';- childIds: string[];- expanded: boolean;-}--export type Layer = ImageLayer | TextLayer | ShapeLayer | GroupLayer;--export interface CanvasSize {- width: number;- height: number;-}--export interface CanvasBackground {- type: 'color' | 'gradient' | 'image' | 'transparent';- color?: string;- gradient?: {- type: 'linear' | 'radial';- angle: number;- stops: { offset: number; color: string }[];- };- imageId?: string;-}--export interface Artboard {- id: string;- name: string;- size: CanvasSize;- background: CanvasBackground;- layerIds: string[];- position: { x: number; y: number };-}--export interface MediaAsset {- id: string;- name: string;- type: 'image' | 'svg';- mimeType: string;- size: number;- width: number;- height: number;- thumbnailUrl: string;- dataUrl?: string;- blobUrl?: string;-}--export interface Project {- id: string;- name: string;- createdAt: number;- updatedAt: number;- version: number;- artboards: Artboard[];- layers: Record<string, Layer>;- assets: Record<string, MediaAsset>;- activeArtboardId: string | null;-}--export interface ProjectMetadata {- id: string;- name: string;- createdAt: number;- updatedAt: number;- thumbnailUrl: string | null;-}--export const DEFAULT_TRANSFORM: Transform = {- x: 0,- y: 0,- width: 100,- height: 100,- rotation: 0,- scaleX: 1,- scaleY: 1,- skewX: 0,- skewY: 0,- opacity: 1,-};--export const DEFAULT_BLEND_MODE: BlendMode = {- mode: 'normal',-};--export const DEFAULT_SHADOW: Shadow = {- enabled: false,- color: 'rgba(0, 0, 0, 0.5)',- blur: 10,- offsetX: 0,- offsetY: 4,-};--export const DEFAULT_STROKE: Stroke = {- enabled: false,- color: '#000000',- width: 1,- style: 'solid',-};--export const DEFAULT_GLOW: Glow = {- enabled: false,- color: '#ffffff',- blur: 20,- intensity: 1,-};--export const DEFAULT_INNER_SHADOW: InnerShadow = {- enabled: false,- color: 'rgba(0, 0, 0, 0.5)',- blur: 10,- offsetX: 2,- offsetY: 2,-};--export { DEFAULT_LAYER_MASK } from './mask';-export {- DEFAULT_LEVELS,- DEFAULT_CURVES,- DEFAULT_COLOR_BALANCE,- DEFAULT_SELECTIVE_COLOR,- DEFAULT_BLACK_WHITE,- DEFAULT_PHOTO_FILTER,- DEFAULT_CHANNEL_MIXER,- DEFAULT_GRADIENT_MAP,- DEFAULT_POSTERIZE,- DEFAULT_THRESHOLD,-} from './adjustments';--export const DEFAULT_FILTER: Filter = {- brightness: 100,- contrast: 100,- saturation: 100,- hue: 0,- exposure: 0,- vibrance: 0,- highlights: 0,- shadows: 0,- clarity: 0,- blur: 0,- blurType: 'gaussian',- blurAngle: 0,- sharpen: 0,- vignette: 0,- grain: 0,- sepia: 0,- invert: 0,-};--export const DEFAULT_TEXT_STYLE: TextStyle = {- fontFamily: 'Inter',- fontSize: 24,- fontWeight: 400,- fontStyle: 'normal',- textDecoration: 'none',- textAlign: 'left',- verticalAlign: 'top',- lineHeight: 1.4,- letterSpacing: 0,- fillType: 'solid',- color: '#ffffff',- gradient: null,- strokeColor: null,- strokeWidth: 0,- backgroundColor: null,- backgroundPadding: 8,- backgroundRadius: 4,- textShadow: {- enabled: false,- color: 'rgba(0, 0, 0, 0.5)',- blur: 4,- offsetX: 0,- offsetY: 2,- },-};--export const DEFAULT_NOISE_FILL: NoiseFill = {- baseColor: '#3b82f6',- noiseColor: '#1e40af',- density: 0.5,- size: 2,-};--export const DEFAULT_SHAPE_STYLE: ShapeStyle = {- fillType: 'solid',- fill: '#3b82f6',- gradient: null,- noise: null,- fillOpacity: 1,- stroke: null,- strokeWidth: 2,- strokeOpacity: 1,- strokeDash: 'solid',- cornerRadius: 0,- individualCorners: false,- corners: {- topLeft: 0,- topRight: 0,- bottomRight: 0,- bottomLeft: 0,- },-};--export const CANVAS_PRESETS: { name: string; width: number; height: number; category: string }[] = [- { name: 'Instagram Post', width: 1080, height: 1080, category: 'Social Media' },- { name: 'Instagram Story', width: 1080, height: 1920, category: 'Social Media' },- { name: 'Facebook Post', width: 1200, height: 630, category: 'Social Media' },- { name: 'Twitter Post', width: 1200, height: 675, category: 'Social Media' },- { name: 'LinkedIn Post', width: 1200, height: 627, category: 'Social Media' },- { name: 'YouTube Thumbnail', width: 1280, height: 720, category: 'Social Media' },- { name: 'TikTok Video', width: 1080, height: 1920, category: 'Social Media' },- { name: 'Pinterest Pin', width: 1000, height: 1500, category: 'Social Media' },- { name: 'Presentation 16:9', width: 1920, height: 1080, category: 'Presentation' },- { name: 'Presentation 4:3', width: 1024, height: 768, category: 'Presentation' },- { name: 'A4 Portrait', width: 2480, height: 3508, category: 'Print' },- { name: 'A4 Landscape', width: 3508, height: 2480, category: 'Print' },- { name: 'Letter Portrait', width: 2550, height: 3300, category: 'Print' },- { name: 'Business Card', width: 1050, height: 600, category: 'Print' },- { name: 'Poster 18x24', width: 5400, height: 7200, category: 'Print' },- { name: 'Desktop Wallpaper', width: 1920, height: 1080, category: 'Desktop' },- { name: '4K Wallpaper', width: 3840, height: 2160, category: 'Desktop' },- { name: 'Mobile Wallpaper', width: 1080, height: 1920, category: 'Mobile' },- { name: 'Logo Square', width: 500, height: 500, category: 'Logo' },- { name: 'Favicon', width: 512, height: 512, category: 'Logo' },-];+export * from '@openreel/image-core/project';diff --git a/apps/image/src/types/selection.ts b/apps/image/src/types/selection.tsindex 1e1d1fdd..458ef5e6 100644--- a/apps/image/src/types/selection.ts+++ b/apps/image/src/types/selection.ts@@ -1,187 +1 @@-export type SelectionType =- | 'rectangular'- | 'elliptical'- | 'lasso'- | 'polygonal'- | 'magic-wand'- | 'color-range';--export type SelectionMode = 'new' | 'add' | 'subtract' | 'intersect';--export interface SelectionBounds {- x: number;- y: number;- width: number;- height: number;-}--export interface Selection {- id: string;- type: SelectionType;- bounds: SelectionBounds;- path: { x: number; y: number }[];- feather: number;- antiAlias: boolean;- opacity: number;-}--export interface MagicWandOptions {- tolerance: number;- contiguous: boolean;- sampleAllLayers: boolean;-}--export interface ColorRangeOptions {- fuzziness: number;- range: 'sampled' | 'reds' | 'yellows' | 'greens' | 'cyans' | 'blues' | 'magentas' | 'highlights' | 'midtones' | 'shadows';- invert: boolean;-}--export interface SelectionState {- active: Selection | null;- saved: Selection[];- mode: SelectionMode;- isSelecting: boolean;- marching: boolean;- magicWandOptions: MagicWandOptions;- colorRangeOptions: ColorRangeOptions;- tempPath: { x: number; y: number }[];- startPoint: { x: number; y: number } | null;-}--export const DEFAULT_MAGIC_WAND_OPTIONS: MagicWandOptions = {- tolerance: 32,- contiguous: true,- sampleAllLayers: false,-};--export const DEFAULT_COLOR_RANGE_OPTIONS: ColorRangeOptions = {- fuzziness: 40,- range: 'sampled',- invert: false,-};--export function createEmptySelection(): Selection {- return {- id: '',- type: 'rectangular',- bounds: { x: 0, y: 0, width: 0, height: 0 },- path: [],- feather: 0,- antiAlias: true,- opacity: 1,- };-}--export function selectionToPath2D(selection: Selection): Path2D {- const path = new Path2D();-- if (selection.type === 'rectangular') {- path.rect(- selection.bounds.x,- selection.bounds.y,- selection.bounds.width,- selection.bounds.height- );- } else if (selection.type === 'elliptical') {- const cx = selection.bounds.x + selection.bounds.width / 2;- const cy = selection.bounds.y + selection.bounds.height / 2;- const rx = selection.bounds.width / 2;- const ry = selection.bounds.height / 2;- path.ellipse(cx, cy, rx, ry, 0, 0, Math.PI * 2);- } else if (selection.path.length > 0) {- path.moveTo(selection.path[0].x, selection.path[0].y);- for (let i = 1; i < selection.path.length; i++) {- path.lineTo(selection.path[i].x, selection.path[i].y);- }- path.closePath();- }-- return path;-}--export function boundsFromPath(points: { x: number; y: number }[]): SelectionBounds {- if (points.length === 0) {- return { x: 0, y: 0, width: 0, height: 0 };- }-- let minX = Infinity;- let minY = Infinity;- let maxX = -Infinity;- let maxY = -Infinity;-- for (const point of points) {- minX = Math.min(minX, point.x);- minY = Math.min(minY, point.y);- maxX = Math.max(maxX, point.x);- maxY = Math.max(maxY, point.y);- }-- return {- x: minX,- y: minY,- width: maxX - minX,- height: maxY - minY,- };-}--export function isPointInSelection(- x: number,- y: number,- selection: Selection,- ctx?: CanvasRenderingContext2D-): boolean {- if (!ctx) return false;-- const path = selectionToPath2D(selection);- return ctx.isPointInPath(path, x, y);-}--export function combineSelections(- existing: Selection,- newSelection: Selection,- mode: SelectionMode-): Selection {- if (mode === 'new') {- return newSelection;- }-- const combined: Selection = {- ...newSelection,- id: existing.id || newSelection.id,- };-- if (mode === 'add') {- combined.path = [...existing.path, ...newSelection.path];- combined.bounds = boundsFromPath(combined.path);- } else if (mode === 'subtract') {- combined.path = existing.path;- combined.bounds = existing.bounds;- } else if (mode === 'intersect') {- combined.path = existing.path;- combined.bounds = existing.bounds;- }-- return combined;-}--export function getSelectionMask(- selection: Selection,- width: number,- height: number-): ImageData {- const canvas = new OffscreenCanvas(width, height);- const ctx = canvas.getContext('2d')!;-- ctx.fillStyle = 'white';- const path = selectionToPath2D(selection);- ctx.fill(path);-- if (selection.feather > 0) {- ctx.filter = `blur(${selection.feather}px)`;- ctx.drawImage(canvas, 0, 0);- ctx.filter = 'none';- }-- return ctx.getImageData(0, 0, width, height);-}+export * from '@openreel/image-core/selection';diff --git a/apps/image/tsconfig.json b/apps/image/tsconfig.jsonindex 541ffab2..3af690f8 100644--- a/apps/image/tsconfig.json+++ b/apps/image/tsconfig.json@@ -9,6 +9,8 @@"baseUrl": ".","paths": {"@/*": ["./src/*"],+ "@openreel/image-core": ["../../packages/image-core/src/index.ts"],+ "@openreel/image-core/*": ["../../packages/image-core/src/*"],"@openreel/ui": ["../../packages/ui/src/index.ts"],"@openreel/ui/*": ["../../packages/ui/src/*"]}diff --git a/packages/image-core/package.json b/packages/image-core/package.jsonnew file mode 100644index 00000000..3132d98a--- /dev/null+++ b/packages/image-core/package.json@@ -0,0 +1,30 @@+{+ "name": "@openreel/image-core",+ "version": "0.1.0",+ "private": true,+ "type": "module",+ "main": "./src/index.ts",+ "types": "./src/index.ts",+ "exports": {+ ".": {+ "import": "./src/index.ts",+ "types": "./src/index.ts"+ },+ "./*": {+ "import": "./src/*.ts",+ "types": "./src/*.ts"+ }+ },+ "scripts": {+ "test": "vitest",+ "test:run": "vitest run",+ "typecheck": "tsc --noEmit"+ },+ "dependencies": {+ "zod": "^4.4.3"+ },+ "devDependencies": {+ "typescript": "^5.4.5",+ "vitest": "^1.6.0"+ }+}diff --git a/packages/image-core/src/adjustments.ts b/packages/image-core/src/adjustments.tsnew file mode 100644index 00000000..3e45d845--- /dev/null+++ b/packages/image-core/src/adjustments.ts@@ -0,0 +1,620 @@+export interface LevelsChannel {+ inputBlack: number;+ inputWhite: number;+ gamma: number;+ outputBlack: number;+ outputWhite: number;+}++export interface LevelsAdjustment {+ enabled: boolean;+ master: LevelsChannel;+ red: LevelsChannel;+ green: LevelsChannel;+ blue: LevelsChannel;+}++export interface CurvePoint {+ input: number;+ output: number;+}++export interface CurvesChannel {+ points: CurvePoint[];+}++export interface CurvesAdjustment {+ enabled: boolean;+ master: CurvesChannel;+ red: CurvesChannel;+ green: CurvesChannel;+ blue: CurvesChannel;+}++export interface ColorBalanceValues {+ cyanRed: number;+ magentaGreen: number;+ yellowBlue: number;+}++export interface ColorBalanceAdjustment {+ enabled: boolean;+ shadows: ColorBalanceValues;+ midtones: ColorBalanceValues;+ highlights: ColorBalanceValues;+ preserveLuminosity: boolean;+}++export interface SelectiveColorValues {+ cyan: number;+ magenta: number;+ yellow: number;+ black: number;+}++export type SelectiveColorTarget =+ | 'reds'+ | 'yellows'+ | 'greens'+ | 'cyans'+ | 'blues'+ | 'magentas'+ | 'whites'+ | 'neutrals'+ | 'blacks';++export interface SelectiveColorAdjustment {+ enabled: boolean;+ method: 'relative' | 'absolute';+ reds: SelectiveColorValues;+ yellows: SelectiveColorValues;+ greens: SelectiveColorValues;+ cyans: SelectiveColorValues;+ blues: SelectiveColorValues;+ magentas: SelectiveColorValues;+ whites: SelectiveColorValues;+ neutrals: SelectiveColorValues;+ blacks: SelectiveColorValues;+}++export interface BlackWhiteAdjustment {+ enabled: boolean;+ reds: number;+ yellows: number;+ greens: number;+ cyans: number;+ blues: number;+ magentas: number;+ tintEnabled: boolean;+ tintHue: number;+ tintSaturation: number;+}++export interface GradientMapStop {+ position: number;+ color: string;+}++export interface GradientMapAdjustment {+ enabled: boolean;+ stops: GradientMapStop[];+ reverse: boolean;+ dither: boolean;+}++export interface PosterizeAdjustment {+ enabled: boolean;+ levels: number;+}++export interface ThresholdAdjustment {+ enabled: boolean;+ level: number;+}++export interface PhotoFilterAdjustment {+ enabled: boolean;+ filter: 'warming-85' | 'warming-81' | 'cooling-80' | 'cooling-82' | 'custom';+ color: string;+ density: number;+ preserveLuminosity: boolean;+}++export interface ChannelMixerChannel {+ red: number;+ green: number;+ blue: number;+ constant: number;+}++export interface ChannelMixerAdjustment {+ enabled: boolean;+ monochrome: boolean;+ red: ChannelMixerChannel;+ green: ChannelMixerChannel;+ blue: ChannelMixerChannel;+}++export const DEFAULT_LEVELS_CHANNEL: LevelsChannel = {+ inputBlack: 0,+ inputWhite: 255,+ gamma: 1.0,+ outputBlack: 0,+ outputWhite: 255,+};++export const DEFAULT_LEVELS: LevelsAdjustment = {+ enabled: false,+ master: { ...DEFAULT_LEVELS_CHANNEL },+ red: { ...DEFAULT_LEVELS_CHANNEL },+ green: { ...DEFAULT_LEVELS_CHANNEL },+ blue: { ...DEFAULT_LEVELS_CHANNEL },+};++export const DEFAULT_CURVES_CHANNEL: CurvesChannel = {+ points: [+ { input: 0, output: 0 },+ { input: 255, output: 255 },+ ],+};++export const DEFAULT_CURVES: CurvesAdjustment = {+ enabled: false,+ master: { points: [{ input: 0, output: 0 }, { input: 255, output: 255 }] },+ red: { points: [{ input: 0, output: 0 }, { input: 255, output: 255 }] },+ green: { points: [{ input: 0, output: 0 }, { input: 255, output: 255 }] },+ blue: { points: [{ input: 0, output: 0 }, { input: 255, output: 255 }] },+};++export const DEFAULT_COLOR_BALANCE_VALUES: ColorBalanceValues = {+ cyanRed: 0,+ magentaGreen: 0,+ yellowBlue: 0,+};++export const DEFAULT_COLOR_BALANCE: ColorBalanceAdjustment = {+ enabled: false,+ shadows: { ...DEFAULT_COLOR_BALANCE_VALUES },+ midtones: { ...DEFAULT_COLOR_BALANCE_VALUES },+ highlights: { ...DEFAULT_COLOR_BALANCE_VALUES },+ preserveLuminosity: true,+};++export const DEFAULT_SELECTIVE_COLOR_VALUES: SelectiveColorValues = {+ cyan: 0,+ magenta: 0,+ yellow: 0,+ black: 0,+};++export const DEFAULT_SELECTIVE_COLOR: SelectiveColorAdjustment = {+ enabled: false,+ method: 'relative',+ reds: { ...DEFAULT_SELECTIVE_COLOR_VALUES },+ yellows: { ...DEFAULT_SELECTIVE_COLOR_VALUES },+ greens: { ...DEFAULT_SELECTIVE_COLOR_VALUES },+ cyans: { ...DEFAULT_SELECTIVE_COLOR_VALUES },+ blues: { ...DEFAULT_SELECTIVE_COLOR_VALUES },+ magentas: { ...DEFAULT_SELECTIVE_COLOR_VALUES },+ whites: { ...DEFAULT_SELECTIVE_COLOR_VALUES },+ neutrals: { ...DEFAULT_SELECTIVE_COLOR_VALUES },+ blacks: { ...DEFAULT_SELECTIVE_COLOR_VALUES },+};++export const DEFAULT_BLACK_WHITE: BlackWhiteAdjustment = {+ enabled: false,+ reds: 40,+ yellows: 60,+ greens: 40,+ cyans: 60,+ blues: 20,+ magentas: 80,+ tintEnabled: false,+ tintHue: 35,+ tintSaturation: 25,+};++export const DEFAULT_GRADIENT_MAP: GradientMapAdjustment = {+ enabled: false,+ stops: [+ { position: 0, color: '#000000' },+ { position: 1, color: '#ffffff' },+ ],+ reverse: false,+ dither: false,+};++export const DEFAULT_POSTERIZE: PosterizeAdjustment = {+ enabled: false,+ levels: 4,+};++export const DEFAULT_THRESHOLD: ThresholdAdjustment = {+ enabled: false,+ level: 128,+};++export const DEFAULT_PHOTO_FILTER: PhotoFilterAdjustment = {+ enabled: false,+ filter: 'warming-85',+ color: '#ec8a00',+ density: 25,+ preserveLuminosity: true,+};++export const DEFAULT_CHANNEL_MIXER: ChannelMixerAdjustment = {+ enabled: false,+ monochrome: false,+ red: { red: 100, green: 0, blue: 0, constant: 0 },+ green: { red: 0, green: 100, blue: 0, constant: 0 },+ blue: { red: 0, green: 0, blue: 100, constant: 0 },+};++export function applyLevels(value: number, channel: LevelsChannel): number {+ let v = value;++ v = Math.max(channel.inputBlack, Math.min(channel.inputWhite, v));+ v = ((v - channel.inputBlack) / (channel.inputWhite - channel.inputBlack)) * 255;++ v = 255 * Math.pow(v / 255, 1 / channel.gamma);++ v = channel.outputBlack + (v / 255) * (channel.outputWhite - channel.outputBlack);++ return Math.max(0, Math.min(255, Math.round(v)));+}++export function interpolateCurve(value: number, points: CurvePoint[]): number {+ if (points.length === 0) return value;+ if (points.length === 1) return points[0].output;++ const sortedPoints = [...points].sort((a, b) => a.input - b.input);++ if (value <= sortedPoints[0].input) return sortedPoints[0].output;+ if (value >= sortedPoints[sortedPoints.length - 1].input) {+ return sortedPoints[sortedPoints.length - 1].output;+ }++ for (let i = 0; i < sortedPoints.length - 1; i++) {+ const p1 = sortedPoints[i];+ const p2 = sortedPoints[i + 1];++ if (value >= p1.input && value <= p2.input) {+ const t = (value - p1.input) / (p2.input - p1.input);++ if (sortedPoints.length >= 4 && i > 0 && i < sortedPoints.length - 2) {+ const p0 = sortedPoints[i - 1];+ const p3 = sortedPoints[i + 2];+ return catmullRomInterpolate(p0.output, p1.output, p2.output, p3.output, t);+ }++ return p1.output + t * (p2.output - p1.output);+ }+ }++ return value;+}++function catmullRomInterpolate(+ p0: number,+ p1: number,+ p2: number,+ p3: number,+ t: number+): number {+ const t2 = t * t;+ const t3 = t2 * t;++ return (+ 0.5 *+ (2 * p1 ++ (-p0 + p2) * t ++ (2 * p0 - 5 * p1 + 4 * p2 - p3) * t2 ++ (-p0 + 3 * p1 - 3 * p2 + p3) * t3)+ );+}++export function applyLevelsToImageData(+ imageData: ImageData,+ levels: LevelsAdjustment+): ImageData {+ if (!levels.enabled) return imageData;++ const result = new ImageData(imageData.width, imageData.height);++ for (let i = 0; i < imageData.data.length; i += 4) {+ let r = imageData.data[i];+ let g = imageData.data[i + 1];+ let b = imageData.data[i + 2];++ r = applyLevels(r, levels.master);+ g = applyLevels(g, levels.master);+ b = applyLevels(b, levels.master);++ r = applyLevels(r, levels.red);+ g = applyLevels(g, levels.green);+ b = applyLevels(b, levels.blue);++ result.data[i] = r;+ result.data[i + 1] = g;+ result.data[i + 2] = b;+ result.data[i + 3] = imageData.data[i + 3];+ }++ return result;+}++export function applyCurvesToImageData(+ imageData: ImageData,+ curves: CurvesAdjustment+): ImageData {+ if (!curves.enabled) return imageData;++ const result = new ImageData(imageData.width, imageData.height);++ for (let i = 0; i < imageData.data.length; i += 4) {+ let r = imageData.data[i];+ let g = imageData.data[i + 1];+ let b = imageData.data[i + 2];++ r = interpolateCurve(r, curves.master.points);+ g = interpolateCurve(g, curves.master.points);+ b = interpolateCurve(b, curves.master.points);++ r = interpolateCurve(r, curves.red.points);+ g = interpolateCurve(g, curves.green.points);+ b = interpolateCurve(b, curves.blue.points);++ result.data[i] = Math.max(0, Math.min(255, Math.round(r)));+ result.data[i + 1] = Math.max(0, Math.min(255, Math.round(g)));+ result.data[i + 2] = Math.max(0, Math.min(255, Math.round(b)));+ result.data[i + 3] = imageData.data[i + 3];+ }++ return result;+}++export function applyColorBalanceToImageData(+ imageData: ImageData,+ colorBalance: ColorBalanceAdjustment+): ImageData {+ if (!colorBalance.enabled) return imageData;++ const result = new ImageData(imageData.width, imageData.height);++ for (let i = 0; i < imageData.data.length; i += 4) {+ let r = imageData.data[i];+ let g = imageData.data[i + 1];+ let b = imageData.data[i + 2];++ const luminance = 0.299 * r + 0.587 * g + 0.114 * b;++ const shadowWeight = Math.max(0, 1 - luminance / 128);+ const highlightWeight = Math.max(0, (luminance - 128) / 127);+ const midtoneWeight = 1 - shadowWeight - highlightWeight;++ const adjustR =+ colorBalance.shadows.cyanRed * shadowWeight ++ colorBalance.midtones.cyanRed * midtoneWeight ++ colorBalance.highlights.cyanRed * highlightWeight;++ const adjustG =+ colorBalance.shadows.magentaGreen * shadowWeight ++ colorBalance.midtones.magentaGreen * midtoneWeight ++ colorBalance.highlights.magentaGreen * highlightWeight;++ const adjustB =+ colorBalance.shadows.yellowBlue * shadowWeight ++ colorBalance.midtones.yellowBlue * midtoneWeight ++ colorBalance.highlights.yellowBlue * highlightWeight;++ r = Math.max(0, Math.min(255, r + adjustR));+ g = Math.max(0, Math.min(255, g + adjustG));+ b = Math.max(0, Math.min(255, b + adjustB));++ if (colorBalance.preserveLuminosity) {+ const newLuminance = 0.299 * r + 0.587 * g + 0.114 * b;+ if (newLuminance > 0) {+ const factor = luminance / newLuminance;+ r = Math.max(0, Math.min(255, r * factor));+ g = Math.max(0, Math.min(255, g * factor));+ b = Math.max(0, Math.min(255, b * factor));+ }+ }++ result.data[i] = Math.round(r);+ result.data[i + 1] = Math.round(g);+ result.data[i + 2] = Math.round(b);+ result.data[i + 3] = imageData.data[i + 3];+ }++ return result;+}++export function applyThresholdToImageData(+ imageData: ImageData,+ threshold: ThresholdAdjustment+): ImageData {+ if (!threshold.enabled) return imageData;++ const result = new ImageData(imageData.width, imageData.height);++ for (let i = 0; i < imageData.data.length; i += 4) {+ const r = imageData.data[i];+ const g = imageData.data[i + 1];+ const b = imageData.data[i + 2];++ const luminance = 0.299 * r + 0.587 * g + 0.114 * b;+ const value = luminance >= threshold.level ? 255 : 0;++ result.data[i] = value;+ result.data[i + 1] = value;+ result.data[i + 2] = value;+ result.data[i + 3] = imageData.data[i + 3];+ }++ return result;+}++export function applyPosterizeToImageData(+ imageData: ImageData,+ posterize: PosterizeAdjustment+): ImageData {+ if (!posterize.enabled || posterize.levels < 2) return imageData;++ const result = new ImageData(imageData.width, imageData.height);+ const step = 255 / (posterize.levels - 1);++ for (let i = 0; i < imageData.data.length; i += 4) {+ result.data[i] = Math.round(Math.round(imageData.data[i] / step) * step);+ result.data[i + 1] = Math.round(Math.round(imageData.data[i + 1] / step) * step);+ result.data[i + 2] = Math.round(Math.round(imageData.data[i + 2] / step) * step);+ result.data[i + 3] = imageData.data[i + 3];+ }++ return result;+}++export function applyBlackWhiteToImageData(+ imageData: ImageData,+ bw: BlackWhiteAdjustment+): ImageData {+ if (!bw.enabled) return imageData;++ const result = new ImageData(imageData.width, imageData.height);++ for (let i = 0; i < imageData.data.length; i += 4) {+ const r = imageData.data[i];+ const g = imageData.data[i + 1];+ const b = imageData.data[i + 2];++ const max = Math.max(r, g, b);+ const min = Math.min(r, g, b);+ const delta = max - min;++ let hue = 0;+ if (delta > 0) {+ if (max === r) {+ hue = ((g - b) / delta) % 6;+ } else if (max === g) {+ hue = (b - r) / delta + 2;+ } else {+ hue = (r - g) / delta + 4;+ }+ hue *= 60;+ if (hue < 0) hue += 360;+ }++ let weight = 0;+ if (hue < 30 || hue >= 330) {+ weight = bw.reds / 100;+ } else if (hue < 90) {+ weight = bw.yellows / 100;+ } else if (hue < 150) {+ weight = bw.greens / 100;+ } else if (hue < 210) {+ weight = bw.cyans / 100;+ } else if (hue < 270) {+ weight = bw.blues / 100;+ } else {+ weight = bw.magentas / 100;+ }++ let gray = 0.299 * r + 0.587 * g + 0.114 * b;+ gray = gray * (1 + weight * 0.5);+ gray = Math.max(0, Math.min(255, gray));++ let finalR = gray;+ let finalG = gray;+ let finalB = gray;++ if (bw.tintEnabled) {+ const tintH = bw.tintHue / 360;+ const tintS = bw.tintSaturation / 100;+ const tintL = gray / 255;++ const c = (1 - Math.abs(2 * tintL - 1)) * tintS;+ const x = c * (1 - Math.abs((tintH * 6) % 2 - 1));+ const m = tintL - c / 2;++ let rTint = 0, gTint = 0, bTint = 0;+ const h6 = tintH * 6;+ if (h6 < 1) { rTint = c; gTint = x; }+ else if (h6 < 2) { rTint = x; gTint = c; }+ else if (h6 < 3) { gTint = c; bTint = x; }+ else if (h6 < 4) { gTint = x; bTint = c; }+ else if (h6 < 5) { rTint = x; bTint = c; }+ else { rTint = c; bTint = x; }++ finalR = (rTint + m) * 255;+ finalG = (gTint + m) * 255;+ finalB = (bTint + m) * 255;+ }++ result.data[i] = Math.round(finalR);+ result.data[i + 1] = Math.round(finalG);+ result.data[i + 2] = Math.round(finalB);+ result.data[i + 3] = imageData.data[i + 3];+ }++ return result;+}++export function applyGradientMapToImageData(+ imageData: ImageData,+ gradientMap: GradientMapAdjustment+): ImageData {+ if (!gradientMap.enabled || gradientMap.stops.length < 2) return imageData;++ const result = new ImageData(imageData.width, imageData.height);++ const stops = gradientMap.reverse+ ? [...gradientMap.stops].reverse().map((s, i, arr) => ({+ ...s,+ position: 1 - arr[arr.length - 1 - i].position,+ }))+ : gradientMap.stops;++ const sortedStops = [...stops].sort((a, b) => a.position - b.position);++ for (let i = 0; i < imageData.data.length; i += 4) {+ const r = imageData.data[i];+ const g = imageData.data[i + 1];+ const b = imageData.data[i + 2];++ const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;++ let color1 = sortedStops[0];+ let color2 = sortedStops[sortedStops.length - 1];++ for (let j = 0; j < sortedStops.length - 1; j++) {+ if (luminance >= sortedStops[j].position && luminance <= sortedStops[j + 1].position) {+ color1 = sortedStops[j];+ color2 = sortedStops[j + 1];+ break;+ }+ }++ const t = (luminance - color1.position) / (color2.position - color1.position || 1);++ const c1 = hexToRgb(color1.color);+ const c2 = hexToRgb(color2.color);++ result.data[i] = Math.round(c1.r + t * (c2.r - c1.r));+ result.data[i + 1] = Math.round(c1.g + t * (c2.g - c1.g));+ result.data[i + 2] = Math.round(c1.b + t * (c2.b - c1.b));+ result.data[i + 3] = imageData.data[i + 3];+ }++ return result;+}++function hexToRgb(hex: string): { r: number; g: number; b: number } {+ const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);+ return result+ ? {+ r: parseInt(result[1], 16),+ g: parseInt(result[2], 16),+ b: parseInt(result[3], 16),+ }+ : { r: 0, g: 0, b: 0 };+}diff --git a/packages/image-core/src/index.ts b/packages/image-core/src/index.tsnew file mode 100644index 00000000..00fb180c--- /dev/null+++ b/packages/image-core/src/index.ts@@ -0,0 +1,7 @@+export * from './adjustments';+export * from './mask';+export * from './migration';+export * from './operations';+export * from './project';+export * from './schema';+export * from './selection';diff --git a/packages/image-core/src/mask.ts b/packages/image-core/src/mask.tsnew file mode 100644index 00000000..e13ae922--- /dev/null+++ b/packages/image-core/src/mask.ts@@ -0,0 +1,168 @@+export type MaskType = 'pixel' | 'vector';++export interface LayerMask {+ id: string;+ type: MaskType;+ enabled: boolean;+ linked: boolean;+ density: number;+ feather: number;+ invert: boolean;+ data: string | null;+ vectorPath: { x: number; y: number }[] | null;+}++export const DEFAULT_LAYER_MASK: LayerMask = {+ id: '',+ type: 'pixel',+ enabled: true,+ linked: true,+ density: 100,+ feather: 0,+ invert: false,+ data: null,+ vectorPath: null,+};++export function createMaskFromSelection(+ selectionPath: { x: number; y: number }[],+ width: number,+ height: number,+ feather: number = 0+): string {+ const canvas = new OffscreenCanvas(width, height);+ const ctx = canvas.getContext('2d')!;++ ctx.fillStyle = 'white';+ ctx.beginPath();++ if (selectionPath.length > 0) {+ ctx.moveTo(selectionPath[0].x, selectionPath[0].y);+ for (let i = 1; i < selectionPath.length; i++) {+ ctx.lineTo(selectionPath[i].x, selectionPath[i].y);+ }+ ctx.closePath();+ ctx.fill();+ }++ if (feather > 0) {+ const tempCanvas = new OffscreenCanvas(width, height);+ const tempCtx = tempCanvas.getContext('2d')!;+ tempCtx.filter = `blur(${feather}px)`;+ tempCtx.drawImage(canvas, 0, 0);++ ctx.clearRect(0, 0, width, height);+ ctx.drawImage(tempCanvas, 0, 0);+ }++ return canvas.convertToBlob().then(() => {+ const reader = new FileReader();+ return new Promise<string>((resolve) => {+ canvas.convertToBlob().then((blob) => {+ reader.onload = () => resolve(reader.result as string);+ reader.readAsDataURL(blob);+ });+ });+ }) as unknown as string;+}++export function createMaskFromImageData(imageData: ImageData): string {+ const canvas = new OffscreenCanvas(imageData.width, imageData.height);+ const ctx = canvas.getContext('2d')!;+ ctx.putImageData(imageData, 0, 0);++ return canvas.convertToBlob().then(() => {+ return new Promise<string>((resolve) => {+ canvas.convertToBlob().then((blob) => {+ const reader = new FileReader();+ reader.onload = () => resolve(reader.result as string);+ reader.readAsDataURL(blob);+ });+ });+ }) as unknown as string;+}++export function applyMaskToImageData(+ imageData: ImageData,+ mask: LayerMask,+ maskImage: HTMLImageElement | null+): ImageData {+ if (!mask.enabled || !maskImage) {+ return imageData;+ }++ const canvas = new OffscreenCanvas(imageData.width, imageData.height);+ const ctx = canvas.getContext('2d')!;++ ctx.drawImage(maskImage, 0, 0, imageData.width, imageData.height);+ const maskData = ctx.getImageData(0, 0, imageData.width, imageData.height);++ const result = new ImageData(imageData.width, imageData.height);+ const density = mask.density / 100;++ for (let i = 0; i < imageData.data.length; i += 4) {+ result.data[i] = imageData.data[i];+ result.data[i + 1] = imageData.data[i + 1];+ result.data[i + 2] = imageData.data[i + 2];++ let maskAlpha = maskData.data[i];+ if (mask.invert) {+ maskAlpha = 255 - maskAlpha;+ }+ maskAlpha = Math.round(maskAlpha * density);++ result.data[i + 3] = Math.round((imageData.data[i + 3] * maskAlpha) / 255);+ }++ return result;+}++export function invertMask(maskDataUrl: string, width: number, height: number): Promise<string> {+ return new Promise((resolve) => {+ const img = new Image();+ img.onload = () => {+ const canvas = new OffscreenCanvas(width, height);+ const ctx = canvas.getContext('2d')!;+ ctx.drawImage(img, 0, 0);++ const imageData = ctx.getImageData(0, 0, width, height);+ for (let i = 0; i < imageData.data.length; i += 4) {+ imageData.data[i] = 255 - imageData.data[i];+ imageData.data[i + 1] = 255 - imageData.data[i + 1];+ imageData.data[i + 2] = 255 - imageData.data[i + 2];+ }+ ctx.putImageData(imageData, 0, 0);++ canvas.convertToBlob().then((blob) => {+ const reader = new FileReader();+ reader.onload = () => resolve(reader.result as string);+ reader.readAsDataURL(blob);+ });+ };+ img.src = maskDataUrl;+ });+}++export function featherMask(+ maskDataUrl: string,+ width: number,+ height: number,+ featherAmount: number+): Promise<string> {+ return new Promise((resolve) => {+ const img = new Image();+ img.onload = () => {+ const canvas = new OffscreenCanvas(width, height);+ const ctx = canvas.getContext('2d')!;+ ctx.filter = `blur(${featherAmount}px)`;+ ctx.drawImage(img, 0, 0);++ canvas.convertToBlob().then((blob) => {+ const reader = new FileReader();+ reader.onload = () => resolve(reader.result as string);+ reader.readAsDataURL(blob);+ });+ };+ img.src = maskDataUrl;+ });+}diff --git a/packages/image-core/src/migration.ts b/packages/image-core/src/migration.tsnew file mode 100644index 00000000..37edb5a1--- /dev/null+++ b/packages/image-core/src/migration.ts@@ -0,0 +1,40 @@++/** The current document format version. Increment when the schema changes. */+export const CURRENT_VERSION = 1;++/**+ * Apply all pending migrations to bring `raw` up to the current version.+ * Unknown versions are returned as-is so callers can fail validation instead.+ */+export function migrateProject(raw: Record<string, unknown>): Record<string, unknown> {+ let doc = { ...raw };+ const version = typeof doc.version === 'number' ? doc.version : 0;++ // Version 0 → 1: add explicit `version` field and `activeArtboardId` if missing.+ if (version < 1) {+ doc = migrateV0ToV1(doc);+ }++ // Future migrations go here, e.g.:+ // if (doc.version < 2) { doc = migrateV1ToV2(doc); }++ return doc;+}++function migrateV0ToV1(doc: Record<string, unknown>): Record<string, unknown> {+ const updated: Record<string, unknown> = { ...doc };++ updated.version = 1;++ // Ensure activeArtboardId exists.+ if (updated.activeArtboardId === undefined) {+ const artboards = Array.isArray(updated.artboards) ? updated.artboards : [];+ updated.activeArtboardId =+ artboards.length > 0 && typeof artboards[0] === 'object' && artboards[0] !== null+ ? (artboards[0] as Record<string, unknown>).id ?? null+ : null;+ }++ return updated;+}+diff --git a/packages/image-core/src/operations.test.ts b/packages/image-core/src/operations.test.tsnew file mode 100644index 00000000..d13d447a--- /dev/null+++ b/packages/image-core/src/operations.test.ts@@ -0,0 +1,225 @@+import { describe, expect, it } from 'vitest';+import {+ DEFAULT_BLACK_WHITE,+ DEFAULT_BLEND_MODE,+ DEFAULT_COLOR_BALANCE,+ DEFAULT_CURVES,+ DEFAULT_CHANNEL_MIXER,+ DEFAULT_FILTER,+ DEFAULT_GRADIENT_MAP,+ DEFAULT_GLOW,+ DEFAULT_INNER_SHADOW,+ DEFAULT_LEVELS,+ DEFAULT_PHOTO_FILTER,+ DEFAULT_POSTERIZE,+ DEFAULT_SELECTIVE_COLOR,+ DEFAULT_SHADOW,+ DEFAULT_SHAPE_STYLE,+ DEFAULT_STROKE,+ DEFAULT_TEXT_STYLE,+ DEFAULT_THRESHOLD,+ DEFAULT_TRANSFORM,+ type GroupLayer,+ type ShapeLayer,+ type TextLayer,+} from './project';+import {+ addLayerToProject,+ createProjectDocument,+ deserializeProject,+ duplicateLayerInProject,+ removeLayerFromProject,+ reorderArtboardLayers,+ serializeProject,+ validateLayerTree,+} from './operations';++const DEFAULT_SIZE = { width: 1080, height: 1080 };+const DEFAULT_BG = { type: 'color' as const, color: '#ffffff' };++function createTextLayer(id: string, name = 'Text'): TextLayer {+ return {+ id,+ name,+ type: 'text',+ visible: true,+ locked: false,+ transform: { ...DEFAULT_TRANSFORM, width: 200, height: 50 },+ blendMode: { ...DEFAULT_BLEND_MODE },+ shadow: { ...DEFAULT_SHADOW },+ innerShadow: { ...DEFAULT_INNER_SHADOW },+ stroke: { ...DEFAULT_STROKE },+ glow: { ...DEFAULT_GLOW },+ filters: { ...DEFAULT_FILTER },+ parentId: null,+ flipHorizontal: false,+ flipVertical: false,+ mask: null,+ clippingMask: false,+ levels: { ...DEFAULT_LEVELS },+ curves: { ...DEFAULT_CURVES },+ colorBalance: { ...DEFAULT_COLOR_BALANCE },+ selectiveColor: { ...DEFAULT_SELECTIVE_COLOR },+ blackWhite: { ...DEFAULT_BLACK_WHITE },+ photoFilter: { ...DEFAULT_PHOTO_FILTER },+ channelMixer: { ...DEFAULT_CHANNEL_MIXER },+ gradientMap: { ...DEFAULT_GRADIENT_MAP },+ posterize: { ...DEFAULT_POSTERIZE },+ threshold: { ...DEFAULT_THRESHOLD },+ content: name,+ style: { ...DEFAULT_TEXT_STYLE },+ autoSize: true,+ };+}++function createShapeLayer(id: string, parentId: string | null = null): ShapeLayer {+ return {+ id,+ name: 'Shape',+ type: 'shape',+ visible: true,+ locked: false,+ transform: { ...DEFAULT_TRANSFORM },+ blendMode: { ...DEFAULT_BLEND_MODE },+ shadow: { ...DEFAULT_SHADOW },+ innerShadow: { ...DEFAULT_INNER_SHADOW },+ stroke: { ...DEFAULT_STROKE },+ glow: { ...DEFAULT_GLOW },+ filters: { ...DEFAULT_FILTER },+ parentId,+ flipHorizontal: false,+ flipVertical: false,+ mask: null,+ clippingMask: false,+ levels: { ...DEFAULT_LEVELS },+ curves: { ...DEFAULT_CURVES },+ colorBalance: { ...DEFAULT_COLOR_BALANCE },+ selectiveColor: { ...DEFAULT_SELECTIVE_COLOR },+ blackWhite: { ...DEFAULT_BLACK_WHITE },+ photoFilter: { ...DEFAULT_PHOTO_FILTER },+ channelMixer: { ...DEFAULT_CHANNEL_MIXER },+ gradientMap: { ...DEFAULT_GRADIENT_MAP },+ posterize: { ...DEFAULT_POSTERIZE },+ threshold: { ...DEFAULT_THRESHOLD },+ shapeType: 'rectangle',+ shapeStyle: { ...DEFAULT_SHAPE_STYLE },+ };+}++function createGroupLayer(id: string, childIds: string[]): GroupLayer {+ return {+ id,+ name: 'Group',+ type: 'group',+ visible: true,+ locked: false,+ transform: { ...DEFAULT_TRANSFORM },+ blendMode: { ...DEFAULT_BLEND_MODE },+ shadow: { ...DEFAULT_SHADOW },+ innerShadow: { ...DEFAULT_INNER_SHADOW },+ stroke: { ...DEFAULT_STROKE },+ glow: { ...DEFAULT_GLOW },+ filters: { ...DEFAULT_FILTER },+ parentId: null,+ flipHorizontal: false,+ flipVertical: false,+ mask: null,+ clippingMask: false,+ levels: { ...DEFAULT_LEVELS },+ curves: { ...DEFAULT_CURVES },+ colorBalance: { ...DEFAULT_COLOR_BALANCE },+ selectiveColor: { ...DEFAULT_SELECTIVE_COLOR },+ blackWhite: { ...DEFAULT_BLACK_WHITE },+ photoFilter: { ...DEFAULT_PHOTO_FILTER },+ channelMixer: { ...DEFAULT_CHANNEL_MIXER },+ gradientMap: { ...DEFAULT_GRADIENT_MAP },+ posterize: { ...DEFAULT_POSTERIZE },+ threshold: { ...DEFAULT_THRESHOLD },+ childIds,+ expanded: true,+ };+}++describe('image-core document operations', () => {+ it('serializes and deserializes a valid project document', () => {+ const project = createProjectDocument({+ id: 'project-1',+ artboardId: 'artboard-1',+ name: 'Document',+ size: DEFAULT_SIZE,+ background: DEFAULT_BG,+ timestamp: 1,+ });++ const withLayer = addLayerToProject(project, 'artboard-1', createTextLayer('layer-1'), 0, 2);+ const serialized = serializeProject(withLayer);+ const parsed = deserializeProject(serialized);++ expect(parsed.success).toBe(true);+ if (parsed.success) {+ expect(parsed.data.layers['layer-1']?.type).toBe('text');+ expect(parsed.data.updatedAt).toBe(2);+ }+ });++ it('duplicates, reorders, and removes layers without mutating the original project', () => {+ const project = createProjectDocument({+ id: 'project-1',+ artboardId: 'artboard-1',+ name: 'Document',+ size: DEFAULT_SIZE,+ background: DEFAULT_BG,+ timestamp: 1,+ });++ const withFirst = addLayerToProject(project, 'artboard-1', createTextLayer('layer-1'), 0, 2);+ const withSecond = addLayerToProject(withFirst, 'artboard-1', createTextLayer('layer-2'), 0, 3);+ const duplicated = duplicateLayerInProject(withSecond, 'artboard-1', 'layer-2', 'layer-3');++ expect(duplicated).not.toBeNull();+ expect(withSecond.artboards[0]?.layerIds).toEqual(['layer-2', 'layer-1']);++ const reordered = reorderArtboardLayers(+ duplicated!.project,+ 'artboard-1',+ ['layer-1', 'layer-2', 'layer-3'],+ 4,+ );+ const removed = removeLayerFromProject(reordered, 'layer-2', 5);++ expect(reordered.artboards[0]?.layerIds).toEqual(['layer-1', 'layer-2', 'layer-3']);+ expect(removed.artboards[0]?.layerIds).toEqual(['layer-1', 'layer-3']);+ expect(removed.layers['layer-2']).toBeUndefined();+ expect(duplicated!.project.layers['layer-2']).toBeDefined();+ });++ it('reports invalid layer tree invariants', () => {+ const project = createProjectDocument({+ id: 'project-1',+ artboardId: 'artboard-1',+ name: 'Document',+ size: DEFAULT_SIZE,+ background: DEFAULT_BG,+ timestamp: 1,+ });++ const child = createShapeLayer('child-1', 'group-1');+ const group = createGroupLayer('group-1', ['missing-child']);++ const broken = addLayerToProject(+ addLayerToProject(project, 'artboard-1', group, 0, 2),+ 'artboard-1',+ child,+ 1,+ 3,+ );+ broken.activeArtboardId = 'missing-artboard';++ expect(validateLayerTree(broken)).toEqual(+ expect.arrayContaining([+ 'Active artboard "missing-artboard" does not exist.',+ 'Group "group-1" references missing child "missing-child".',+ ]),+ );+ });+});diff --git a/packages/image-core/src/operations.ts b/packages/image-core/src/operations.tsnew file mode 100644index 00000000..1bc6ab9e--- /dev/null+++ b/packages/image-core/src/operations.ts@@ -0,0 +1,389 @@+import type {+ Artboard,+ CanvasBackground,+ CanvasSize,+ Layer,+ Project,+ Transform,+} from './project';+import { parseProject } from './schema';+import { migrateProject } from './migration';++export interface CreateProjectDocumentOptions {+ id: string;+ artboardId: string;+ name: string;+ size: CanvasSize;+ background?: CanvasBackground;+ timestamp?: number;+}++export interface DuplicateLayerResult {+ project: Project;+ duplicatedLayerId: string;+}++export interface DeserializeProjectResult {+ success: true;+ data: Project;+}++export interface DeserializeProjectError {+ success: false;+ error: string;+}++function cloneProject(project: Project): Project {+ return JSON.parse(JSON.stringify(project)) as Project;+}++function touchProject(project: Project, timestamp = Date.now()): Project {+ project.updatedAt = timestamp;+ return project;+}++function findArtboard(project: Project, artboardId: string): Artboard | undefined {+ return project.artboards.find((artboard) => artboard.id === artboardId);+}++function removeLayerReferences(project: Project, layerId: string) {+ project.artboards.forEach((artboard) => {+ artboard.layerIds = artboard.layerIds.filter((id) => id !== layerId);+ });++ Object.values(project.layers).forEach((layer) => {+ if (layer.type === 'group') {+ layer.childIds = layer.childIds.filter((childId) => childId !== layerId);+ }+ });+}++function removeLayerTree(project: Project, layerId: string) {+ const layer = project.layers[layerId];+ if (!layer) {+ return;+ }++ if (layer.type === 'group') {+ layer.childIds.forEach((childId) => {+ removeLayerTree(project, childId);+ });+ }++ removeLayerReferences(project, layerId);+ delete project.layers[layerId];+}++function isLayerIdKnown(project: Project, layerId: string): boolean {+ return Object.prototype.hasOwnProperty.call(project.layers, layerId);+}++export function createProjectDocument({+ id,+ artboardId,+ name,+ size,+ background,+ timestamp = Date.now(),+}: CreateProjectDocumentOptions): Project {+ return {+ id,+ name,+ createdAt: timestamp,+ updatedAt: timestamp,+ version: 1,+ artboards: [+ {+ id: artboardId,+ name: 'Artboard 1',+ size,+ background: background ?? { type: 'color', color: '#ffffff' },+ layerIds: [],+ position: { x: 0, y: 0 },+ },+ ],+ layers: {},+ assets: {},+ activeArtboardId: artboardId,+ };+}++export function addLayerToProject(+ project: Project,+ artboardId: string,+ layer: Layer,+ index = 0,+ timestamp = Date.now(),+): Project {+ const nextProject = cloneProject(project);+ const artboard = findArtboard(nextProject, artboardId);+ if (!artboard) {+ return nextProject;+ }++ nextProject.layers[layer.id] = structuredClone(layer);+ const insertionIndex = Math.max(0, Math.min(index, artboard.layerIds.length));+ artboard.layerIds.splice(insertionIndex, 0, layer.id);+ return touchProject(nextProject, timestamp);+}++export function removeLayerFromProject(+ project: Project,+ layerId: string,+ timestamp = Date.now(),+): Project {+ if (!isLayerIdKnown(project, layerId)) {+ return project;+ }++ const nextProject = cloneProject(project);+ removeLayerTree(nextProject, layerId);+ return touchProject(nextProject, timestamp);+}++export function duplicateLayerInProject(+ project: Project,+ artboardId: string,+ layerId: string,+ duplicatedLayerId: string,+ offset: Pick<Transform, 'x' | 'y'> = { x: 20, y: 20 },+ timestamp = Date.now(),+): DuplicateLayerResult | null {+ const artboard = findArtboard(project, artboardId);+ const layer = project.layers[layerId];+ if (!artboard || !layer) {+ return null;+ }++ const nextProject = cloneProject(project);+ const nextArtboard = findArtboard(nextProject, artboardId);+ if (!nextArtboard) {+ return null;+ }++ const duplicatedLayer = structuredClone(layer);+ duplicatedLayer.id = duplicatedLayerId;+ duplicatedLayer.name = `${layer.name} copy`;+ duplicatedLayer.transform.x += offset.x;+ duplicatedLayer.transform.y += offset.y;+ nextProject.layers[duplicatedLayerId] = duplicatedLayer;++ const originalIndex = nextArtboard.layerIds.indexOf(layerId);+ nextArtboard.layerIds.splice(Math.max(originalIndex, 0), 0, duplicatedLayerId);++ return {+ project: touchProject(nextProject, timestamp),+ duplicatedLayerId,+ };+}++export function reorderArtboardLayers(+ project: Project,+ artboardId: string,+ layerIds: string[],+ timestamp = Date.now(),+): Project {+ const nextProject = cloneProject(project);+ const artboard = findArtboard(nextProject, artboardId);+ if (!artboard) {+ return nextProject;+ }++ artboard.layerIds = [...layerIds];+ return touchProject(nextProject, timestamp);+}++export function renameLayer(+ project: Project,+ layerId: string,+ name: string,+ timestamp = Date.now(),+): Project {+ const nextProject = cloneProject(project);+ const layer = nextProject.layers[layerId];+ if (!layer) {+ return nextProject;+ }++ layer.name = name;+ return touchProject(nextProject, timestamp);+}++export function setLayerLocked(+ project: Project,+ layerId: string,+ locked: boolean,+ timestamp = Date.now(),+): Project {+ const nextProject = cloneProject(project);+ const layer = nextProject.layers[layerId];+ if (!layer) {+ return nextProject;+ }++ layer.locked = locked;+ return touchProject(nextProject, timestamp);+}++export function setLayerVisible(+ project: Project,+ layerId: string,+ visible: boolean,+ timestamp = Date.now(),+): Project {+ const nextProject = cloneProject(project);+ const layer = nextProject.layers[layerId];+ if (!layer) {+ return nextProject;+ }++ layer.visible = visible;+ return touchProject(nextProject, timestamp);+}++export function updateLayerTransformInProject(+ project: Project,+ layerId: string,+ transform: Partial<Transform>,+ timestamp = Date.now(),+): Project {+ const nextProject = cloneProject(project);+ const layer = nextProject.layers[layerId];+ if (!layer) {+ return nextProject;+ }++ Object.assign(layer.transform, transform);+ return touchProject(nextProject, timestamp);+}++export function updateLayerInProject<T extends Layer>(+ project: Project,+ layerId: string,+ updates: Partial<T>,+ timestamp = Date.now(),+): Project {+ const nextProject = cloneProject(project);+ const layer = nextProject.layers[layerId];+ if (!layer) {+ return nextProject;+ }++ Object.assign(layer, updates);+ return touchProject(nextProject, timestamp);+}++export function validateLayerTree(project: Project): string[] {+ const issues: string[] = [];+ const artboardIds = new Set(project.artboards.map((artboard) => artboard.id));++ if (project.activeArtboardId !== null && !artboardIds.has(project.activeArtboardId)) {+ issues.push(`Active artboard "${project.activeArtboardId}" does not exist.`);+ }++ const artboardMembership = new Map<string, string>();++ const visitLayer = (layerId: string, artboardId: string, stack: string[]) => {+ if (stack.includes(layerId)) {+ issues.push(`Layer cycle detected: ${[...stack, layerId].join(' -> ')}.`);+ return;+ }++ const layer = project.layers[layerId];+ if (!layer) {+ issues.push(`Layer "${layerId}" is referenced by artboard "${artboardId}" but missing.`);+ return;+ }++ const existingOwner = artboardMembership.get(layerId);+ if (existingOwner && existingOwner !== artboardId) {+ issues.push(`Layer "${layerId}" belongs to multiple artboards: "${existingOwner}" and "${artboardId}".`);+ } else {+ artboardMembership.set(layerId, artboardId);+ }++ if (layer.parentId !== null) {+ const parent = project.layers[layer.parentId];+ if (!parent) {+ issues.push(`Layer "${layerId}" points to missing parent "${layer.parentId}".`);+ } else if (parent.type !== 'group') {+ issues.push(`Layer "${layerId}" parent "${layer.parentId}" is not a group.`);+ } else if (!parent.childIds.includes(layerId)) {+ issues.push(`Group "${parent.id}" is missing child reference for layer "${layerId}".`);+ }+ }++ if (layer.type === 'group') {+ layer.childIds.forEach((childId) => {+ const child = project.layers[childId];+ if (!child) {+ issues.push(`Group "${layer.id}" references missing child "${childId}".`);+ return;+ }++ if (child.parentId !== layer.id) {+ issues.push(`Child "${childId}" does not point back to parent group "${layer.id}".`);+ }++ visitLayer(childId, artboardId, [...stack, layerId]);+ });+ }+ };++ project.artboards.forEach((artboard) => {+ artboard.layerIds.forEach((layerId) => {+ visitLayer(layerId, artboard.id, []);+ });+ });++ Object.values(project.layers).forEach((layer) => {+ if (!artboardMembership.has(layer.id) && layer.parentId === null) {+ issues.push(`Root layer "${layer.id}" is not attached to any artboard.`);+ }+ });++ return issues;+}++export function serializeProject(project: Project): string {+ const issues = validateLayerTree(project);+ if (issues.length > 0) {+ throw new Error(`Invalid project document: ${issues.join(' ')}`);+ }++ return JSON.stringify(project);+}++export function deserializeProject(raw: string | Record<string, unknown>): DeserializeProjectResult | DeserializeProjectError {+ let parsedValue: unknown = raw;++ if (typeof raw === 'string') {+ try {+ parsedValue = JSON.parse(raw);+ } catch (error) {+ return {+ success: false,+ error: error instanceof Error ? error.message : 'Failed to parse project JSON.',+ };+ }+ }++ const migrated = migrateProject(parsedValue as Record<string, unknown>);+ const parsed = parseProject(migrated);+ if (!parsed.success) {+ return parsed;+ }++ const issues = validateLayerTree(parsed.data);+ if (issues.length > 0) {+ return {+ success: false,+ error: issues.join(' '),+ };+ }++ return {+ success: true,+ data: parsed.data,+ };+}diff --git a/packages/image-core/src/project.ts b/packages/image-core/src/project.tsnew file mode 100644index 00000000..d1d8514d--- /dev/null+++ b/packages/image-core/src/project.ts@@ -0,0 +1,437 @@+import type { LayerMask } from './mask';+import type {+ LevelsAdjustment,+ CurvesAdjustment,+ ColorBalanceAdjustment,+ SelectiveColorAdjustment,+ BlackWhiteAdjustment,+ PhotoFilterAdjustment,+ ChannelMixerAdjustment,+ GradientMapAdjustment,+ PosterizeAdjustment,+ ThresholdAdjustment,+} from './adjustments';++export type LayerType = 'image' | 'text' | 'shape' | 'group';++export interface Transform {+ x: number;+ y: number;+ width: number;+ height: number;+ rotation: number;+ scaleX: number;+ scaleY: number;+ skewX: number;+ skewY: number;+ opacity: number;+}++export interface BlendMode {+ mode: 'normal' | 'multiply' | 'screen' | 'overlay' | 'darken' | 'lighten' | 'color-dodge' | 'color-burn' | 'hard-light' | 'soft-light' | 'difference' | 'exclusion';+}++export interface Shadow {+ enabled: boolean;+ color: string;+ blur: number;+ offsetX: number;+ offsetY: number;+}++export interface Stroke {+ enabled: boolean;+ color: string;+ width: number;+ style: 'solid' | 'dashed' | 'dotted';+}++export interface Glow {+ enabled: boolean;+ color: string;+ blur: number;+ intensity: number;+}++export interface InnerShadow {+ enabled: boolean;+ color: string;+ blur: number;+ offsetX: number;+ offsetY: number;+}++export type BlurType = 'gaussian' | 'motion' | 'radial';++export interface Filter {+ brightness: number;+ contrast: number;+ saturation: number;+ hue: number;+ exposure: number;+ vibrance: number;+ highlights: number;+ shadows: number;+ clarity: number;+ blur: number;+ blurType: BlurType;+ blurAngle: number;+ sharpen: number;+ vignette: number;+ grain: number;+ sepia: number;+ invert: number;+}++export interface BaseLayer {+ id: string;+ name: string;+ type: LayerType;+ visible: boolean;+ locked: boolean;+ transform: Transform;+ blendMode: BlendMode;+ shadow: Shadow;+ innerShadow: InnerShadow;+ stroke: Stroke;+ glow: Glow;+ filters: Filter;+ parentId: string | null;+ flipHorizontal: boolean;+ flipVertical: boolean;+ mask: LayerMask | null;+ clippingMask: boolean;+ levels: LevelsAdjustment;+ curves: CurvesAdjustment;+ colorBalance: ColorBalanceAdjustment;+ selectiveColor: SelectiveColorAdjustment;+ blackWhite: BlackWhiteAdjustment;+ photoFilter: PhotoFilterAdjustment;+ channelMixer: ChannelMixerAdjustment;+ gradientMap: GradientMapAdjustment;+ posterize: PosterizeAdjustment;+ threshold: ThresholdAdjustment;+}++export interface ImageLayer extends BaseLayer {+ type: 'image';+ sourceId: string;+ cropRect: { x: number; y: number; width: number; height: number } | null;+}++export type TextFillType = 'solid' | 'gradient';++export interface TextShadow {+ enabled: boolean;+ color: string;+ blur: number;+ offsetX: number;+ offsetY: number;+}++export interface TextStyle {+ fontFamily: string;+ fontSize: number;+ fontWeight: number;+ fontStyle: 'normal' | 'italic';+ textDecoration: 'none' | 'underline' | 'line-through';+ textAlign: 'left' | 'center' | 'right' | 'justify';+ verticalAlign: 'top' | 'middle' | 'bottom';+ lineHeight: number;+ letterSpacing: number;+ fillType: TextFillType;+ color: string;+ gradient: Gradient | null;+ strokeColor: string | null;+ strokeWidth: number;+ backgroundColor: string | null;+ backgroundPadding: number;+ backgroundRadius: number;+ textShadow: TextShadow;+}++export interface TextLayer extends BaseLayer {+ type: 'text';+ content: string;+ style: TextStyle;+ autoSize: boolean;+}++export type ShapeType = 'rectangle' | 'ellipse' | 'triangle' | 'polygon' | 'star' | 'line' | 'arrow' | 'path';++export interface GradientStop {+ offset: number;+ color: string;+}++export interface Gradient {+ type: 'linear' | 'radial';+ angle: number;+ stops: GradientStop[];+}++export type FillType = 'solid' | 'gradient' | 'noise';++export type StrokeDashType = 'solid' | 'dashed' | 'dotted' | 'dash-dot' | 'long-dash';++export interface CornerRadius {+ topLeft: number;+ topRight: number;+ bottomRight: number;+ bottomLeft: number;+}++export interface NoiseFill {+ baseColor: string;+ noiseColor: string;+ density: number;+ size: number;+}++export interface ShapeStyle {+ fillType: FillType;+ fill: string | null;+ gradient: Gradient | null;+ noise: NoiseFill | null;+ fillOpacity: number;+ stroke: string | null;+ strokeWidth: number;+ strokeOpacity: number;+ strokeDash: StrokeDashType;+ cornerRadius: number;+ individualCorners: boolean;+ corners: CornerRadius;+}++export interface ShapeLayer extends BaseLayer {+ type: 'shape';+ shapeType: ShapeType;+ shapeStyle: ShapeStyle;+ points?: { x: number; y: number }[];+ sides?: number;+ innerRadius?: number;+}++export interface GroupLayer extends BaseLayer {+ type: 'group';+ childIds: string[];+ expanded: boolean;+}++export type Layer = ImageLayer | TextLayer | ShapeLayer | GroupLayer;++export interface CanvasSize {+ width: number;+ height: number;+}++export interface CanvasBackground {+ type: 'color' | 'gradient' | 'image' | 'transparent';+ color?: string;+ gradient?: {+ type: 'linear' | 'radial';+ angle: number;+ stops: { offset: number; color: string }[];+ };+ imageId?: string;+}++export interface Artboard {+ id: string;+ name: string;+ size: CanvasSize;+ background: CanvasBackground;+ layerIds: string[];+ position: { x: number; y: number };+}++export interface MediaAsset {+ id: string;+ name: string;+ type: 'image' | 'svg';+ mimeType: string;+ size: number;+ width: number;+ height: number;+ thumbnailUrl: string;+ dataUrl?: string;+ blobUrl?: string;+}++export interface Project {+ id: string;+ name: string;+ createdAt: number;+ updatedAt: number;+ version: number;+ artboards: Artboard[];+ layers: Record<string, Layer>;+ assets: Record<string, MediaAsset>;+ activeArtboardId: string | null;+}++export interface ProjectMetadata {+ id: string;+ name: string;+ createdAt: number;+ updatedAt: number;+ thumbnailUrl: string | null;+}++export const DEFAULT_TRANSFORM: Transform = {+ x: 0,+ y: 0,+ width: 100,+ height: 100,+ rotation: 0,+ scaleX: 1,+ scaleY: 1,+ skewX: 0,+ skewY: 0,+ opacity: 1,+};++export const DEFAULT_BLEND_MODE: BlendMode = {+ mode: 'normal',+};++export const DEFAULT_SHADOW: Shadow = {+ enabled: false,+ color: 'rgba(0, 0, 0, 0.5)',+ blur: 10,+ offsetX: 0,+ offsetY: 4,+};++export const DEFAULT_STROKE: Stroke = {+ enabled: false,+ color: '#000000',+ width: 1,+ style: 'solid',+};++export const DEFAULT_GLOW: Glow = {+ enabled: false,+ color: '#ffffff',+ blur: 20,+ intensity: 1,+};++export const DEFAULT_INNER_SHADOW: InnerShadow = {+ enabled: false,+ color: 'rgba(0, 0, 0, 0.5)',+ blur: 10,+ offsetX: 2,+ offsetY: 2,+};++export { DEFAULT_LAYER_MASK } from './mask';+export {+ DEFAULT_LEVELS,+ DEFAULT_CURVES,+ DEFAULT_COLOR_BALANCE,+ DEFAULT_SELECTIVE_COLOR,+ DEFAULT_BLACK_WHITE,+ DEFAULT_PHOTO_FILTER,+ DEFAULT_CHANNEL_MIXER,+ DEFAULT_GRADIENT_MAP,+ DEFAULT_POSTERIZE,+ DEFAULT_THRESHOLD,+} from './adjustments';++export const DEFAULT_FILTER: Filter = {+ brightness: 100,+ contrast: 100,+ saturation: 100,+ hue: 0,+ exposure: 0,+ vibrance: 0,+ highlights: 0,+ shadows: 0,+ clarity: 0,+ blur: 0,+ blurType: 'gaussian',+ blurAngle: 0,+ sharpen: 0,+ vignette: 0,+ grain: 0,+ sepia: 0,+ invert: 0,+};++export const DEFAULT_TEXT_STYLE: TextStyle = {+ fontFamily: 'Inter',+ fontSize: 24,+ fontWeight: 400,+ fontStyle: 'normal',+ textDecoration: 'none',+ textAlign: 'left',+ verticalAlign: 'top',+ lineHeight: 1.4,+ letterSpacing: 0,+ fillType: 'solid',+ color: '#ffffff',+ gradient: null,+ strokeColor: null,+ strokeWidth: 0,+ backgroundColor: null,+ backgroundPadding: 8,+ backgroundRadius: 4,+ textShadow: {+ enabled: false,+ color: 'rgba(0, 0, 0, 0.5)',+ blur: 4,+ offsetX: 0,+ offsetY: 2,+ },+};++export const DEFAULT_NOISE_FILL: NoiseFill = {+ baseColor: '#3b82f6',+ noiseColor: '#1e40af',+ density: 0.5,+ size: 2,+};++export const DEFAULT_SHAPE_STYLE: ShapeStyle = {+ fillType: 'solid',+ fill: '#3b82f6',+ gradient: null,+ noise: null,+ fillOpacity: 1,+ stroke: null,+ strokeWidth: 2,+ strokeOpacity: 1,+ strokeDash: 'solid',+ cornerRadius: 0,+ individualCorners: false,+ corners: {+ topLeft: 0,+ topRight: 0,+ bottomRight: 0,+ bottomLeft: 0,+ },+};++export const CANVAS_PRESETS: { name: string; width: number; height: number; category: string }[] = [+ { name: 'Instagram Post', width: 1080, height: 1080, category: 'Social Media' },+ { name: 'Instagram Story', width: 1080, height: 1920, category: 'Social Media' },+ { name: 'Facebook Post', width: 1200, height: 630, category: 'Social Media' },+ { name: 'Twitter Post', width: 1200, height: 675, category: 'Social Media' },+ { name: 'LinkedIn Post', width: 1200, height: 627, category: 'Social Media' },+ { name: 'YouTube Thumbnail', width: 1280, height: 720, category: 'Social Media' },+ { name: 'TikTok Video', width: 1080, height: 1920, category: 'Social Media' },+ { name: 'Pinterest Pin', width: 1000, height: 1500, category: 'Social Media' },+ { name: 'Presentation 16:9', width: 1920, height: 1080, category: 'Presentation' },+ { name: 'Presentation 4:3', width: 1024, height: 768, category: 'Presentation' },+ { name: 'A4 Portrait', width: 2480, height: 3508, category: 'Print' },+ { name: 'A4 Landscape', width: 3508, height: 2480, category: 'Print' },+ { name: 'Letter Portrait', width: 2550, height: 3300, category: 'Print' },+ { name: 'Business Card', width: 1050, height: 600, category: 'Print' },+ { name: 'Poster 18x24', width: 5400, height: 7200, category: 'Print' },+ { name: 'Desktop Wallpaper', width: 1920, height: 1080, category: 'Desktop' },+ { name: '4K Wallpaper', width: 3840, height: 2160, category: 'Desktop' },+ { name: 'Mobile Wallpaper', width: 1080, height: 1920, category: 'Mobile' },+ { name: 'Logo Square', width: 500, height: 500, category: 'Logo' },+ { name: 'Favicon', width: 512, height: 512, category: 'Logo' },+];diff --git a/packages/image-core/src/schema.ts b/packages/image-core/src/schema.tsnew file mode 100644index 00000000..8433cc66--- /dev/null+++ b/packages/image-core/src/schema.ts@@ -0,0 +1,414 @@+import { z } from 'zod';++// ── Primitives ──────────────────────────────────────────────────────────────++const TransformSchema = z.object({+ x: z.number(),+ y: z.number(),+ width: z.number(),+ height: z.number(),+ rotation: z.number(),+ scaleX: z.number(),+ scaleY: z.number(),+ skewX: z.number(),+ skewY: z.number(),+ opacity: z.number(),+});++const BlendModeSchema = z.object({+ mode: z.enum([+ 'normal', 'multiply', 'screen', 'overlay', 'darken', 'lighten',+ 'color-dodge', 'color-burn', 'hard-light', 'soft-light', 'difference', 'exclusion',+ ]),+});++const ShadowSchema = z.object({+ enabled: z.boolean(),+ color: z.string(),+ blur: z.number(),+ offsetX: z.number(),+ offsetY: z.number(),+});++const InnerShadowSchema = z.object({+ enabled: z.boolean(),+ color: z.string(),+ blur: z.number(),+ offsetX: z.number(),+ offsetY: z.number(),+});++const StrokeSchema = z.object({+ enabled: z.boolean(),+ color: z.string(),+ width: z.number(),+ style: z.enum(['solid', 'dashed', 'dotted']),+});++const GlowSchema = z.object({+ enabled: z.boolean(),+ color: z.string(),+ blur: z.number(),+ intensity: z.number(),+});++const FilterSchema = z.object({+ brightness: z.number(),+ contrast: z.number(),+ saturation: z.number(),+ hue: z.number(),+ exposure: z.number(),+ vibrance: z.number(),+ highlights: z.number(),+ shadows: z.number(),+ clarity: z.number(),+ blur: z.number(),+ blurType: z.enum(['gaussian', 'motion', 'radial']),+ blurAngle: z.number(),+ sharpen: z.number(),+ vignette: z.number(),+ grain: z.number(),+ sepia: z.number(),+ invert: z.number(),+});++// ── Adjustments ──────────────────────────────────────────────────────────────++const LevelsChannelSchema = z.object({+ inputBlack: z.number(),+ inputWhite: z.number(),+ gamma: z.number(),+ outputBlack: z.number(),+ outputWhite: z.number(),+});++const LevelsSchema = z.object({+ enabled: z.boolean(),+ master: LevelsChannelSchema,+ red: LevelsChannelSchema,+ green: LevelsChannelSchema,+ blue: LevelsChannelSchema,+});++const CurvePointSchema = z.object({ input: z.number(), output: z.number() });++const CurvesChannelSchema = z.object({ points: z.array(CurvePointSchema) });++const CurvesSchema = z.object({+ enabled: z.boolean(),+ master: CurvesChannelSchema,+ red: CurvesChannelSchema,+ green: CurvesChannelSchema,+ blue: CurvesChannelSchema,+});++const ColorBalanceValuesSchema = z.object({+ cyanRed: z.number(),+ magentaGreen: z.number(),+ yellowBlue: z.number(),+});++const ColorBalanceSchema = z.object({+ enabled: z.boolean(),+ shadows: ColorBalanceValuesSchema,+ midtones: ColorBalanceValuesSchema,+ highlights: ColorBalanceValuesSchema,+ preserveLuminosity: z.boolean(),+});++const SelectiveColorValuesSchema = z.object({+ cyan: z.number(),+ magenta: z.number(),+ yellow: z.number(),+ black: z.number(),+});++const SelectiveColorSchema = z.object({+ enabled: z.boolean(),+ method: z.enum(['relative', 'absolute']),+ reds: SelectiveColorValuesSchema,+ yellows: SelectiveColorValuesSchema,+ greens: SelectiveColorValuesSchema,+ cyans: SelectiveColorValuesSchema,+ blues: SelectiveColorValuesSchema,+ magentas: SelectiveColorValuesSchema,+ whites: SelectiveColorValuesSchema,+ neutrals: SelectiveColorValuesSchema,+ blacks: SelectiveColorValuesSchema,+});++const BlackWhiteSchema = z.object({+ enabled: z.boolean(),+ reds: z.number(),+ yellows: z.number(),+ greens: z.number(),+ cyans: z.number(),+ blues: z.number(),+ magentas: z.number(),+ tintEnabled: z.boolean(),+ tintHue: z.number(),+ tintSaturation: z.number(),+});++const PhotoFilterSchema = z.object({+ enabled: z.boolean(),+ filter: z.enum(['warming-85', 'warming-81', 'cooling-80', 'cooling-82', 'custom']),+ color: z.string(),+ density: z.number(),+ preserveLuminosity: z.boolean(),+});++const ChannelMixerChannelSchema = z.object({+ red: z.number(),+ green: z.number(),+ blue: z.number(),+ constant: z.number(),+});++const ChannelMixerSchema = z.object({+ enabled: z.boolean(),+ monochrome: z.boolean(),+ red: ChannelMixerChannelSchema,+ green: ChannelMixerChannelSchema,+ blue: ChannelMixerChannelSchema,+});++const GradientMapStopSchema = z.object({ position: z.number(), color: z.string() });++const GradientMapSchema = z.object({+ enabled: z.boolean(),+ stops: z.array(GradientMapStopSchema),+ reverse: z.boolean(),+ dither: z.boolean(),+});++const PosterizeSchema = z.object({+ enabled: z.boolean(),+ levels: z.number(),+});++const ThresholdSchema = z.object({+ enabled: z.boolean(),+ level: z.number(),+});++// ── Mask ──────────────────────────────────────────────────────────────────────++const LayerMaskSchema = z.object({+ id: z.string(),+ type: z.enum(['pixel', 'vector']),+ enabled: z.boolean(),+ linked: z.boolean(),+ density: z.number(),+ feather: z.number(),+ invert: z.boolean(),+ data: z.string().nullable(),+ vectorPath: z.array(z.object({ x: z.number(), y: z.number() })).nullable(),+});++// ── Layer base ────────────────────────────────────────────────────────────────++const BaseLayerSchema = z.object({+ id: z.string(),+ name: z.string(),+ type: z.enum(['image', 'text', 'shape', 'group']),+ visible: z.boolean(),+ locked: z.boolean(),+ transform: TransformSchema,+ blendMode: BlendModeSchema,+ shadow: ShadowSchema,+ innerShadow: InnerShadowSchema,+ stroke: StrokeSchema,+ glow: GlowSchema,+ filters: FilterSchema,+ parentId: z.string().nullable(),+ flipHorizontal: z.boolean(),+ flipVertical: z.boolean(),+ mask: LayerMaskSchema.nullable(),+ clippingMask: z.boolean(),+ levels: LevelsSchema,+ curves: CurvesSchema,+ colorBalance: ColorBalanceSchema,+ selectiveColor: SelectiveColorSchema,+ blackWhite: BlackWhiteSchema,+ photoFilter: PhotoFilterSchema,+ channelMixer: ChannelMixerSchema,+ gradientMap: GradientMapSchema,+ posterize: PosterizeSchema,+ threshold: ThresholdSchema,+});++// ── Layer variants ────────────────────────────────────────────────────────────++const ImageLayerSchema = BaseLayerSchema.extend({+ type: z.literal('image'),+ sourceId: z.string(),+ cropRect: z+ .object({ x: z.number(), y: z.number(), width: z.number(), height: z.number() })+ .nullable(),+});++const GradientStopSchema = z.object({ offset: z.number(), color: z.string() });++const GradientSchema = z.object({+ type: z.enum(['linear', 'radial']),+ angle: z.number(),+ stops: z.array(GradientStopSchema),+});++const TextShadowSchema = z.object({+ enabled: z.boolean(),+ color: z.string(),+ blur: z.number(),+ offsetX: z.number(),+ offsetY: z.number(),+});++const TextStyleSchema = z.object({+ fontFamily: z.string(),+ fontSize: z.number(),+ fontWeight: z.number(),+ fontStyle: z.enum(['normal', 'italic']),+ textDecoration: z.enum(['none', 'underline', 'line-through']),+ textAlign: z.enum(['left', 'center', 'right', 'justify']),+ verticalAlign: z.enum(['top', 'middle', 'bottom']),+ lineHeight: z.number(),+ letterSpacing: z.number(),+ fillType: z.enum(['solid', 'gradient']),+ color: z.string(),+ gradient: GradientSchema.nullable(),+ strokeColor: z.string().nullable(),+ strokeWidth: z.number(),+ backgroundColor: z.string().nullable(),+ backgroundPadding: z.number(),+ backgroundRadius: z.number(),+ textShadow: TextShadowSchema,+});++const TextLayerSchema = BaseLayerSchema.extend({+ type: z.literal('text'),+ content: z.string(),+ style: TextStyleSchema,+ autoSize: z.boolean(),+});++const CornerRadiusSchema = z.object({+ topLeft: z.number(),+ topRight: z.number(),+ bottomRight: z.number(),+ bottomLeft: z.number(),+});++const NoiseFillSchema = z.object({+ baseColor: z.string(),+ noiseColor: z.string(),+ density: z.number(),+ size: z.number(),+});++const ShapeStyleSchema = z.object({+ fillType: z.enum(['solid', 'gradient', 'noise']),+ fill: z.string().nullable(),+ gradient: GradientSchema.nullable(),+ noise: NoiseFillSchema.nullable(),+ fillOpacity: z.number(),+ stroke: z.string().nullable(),+ strokeWidth: z.number(),+ strokeOpacity: z.number(),+ strokeDash: z.enum(['solid', 'dashed', 'dotted', 'dash-dot', 'long-dash']),+ cornerRadius: z.number(),+ individualCorners: z.boolean(),+ corners: CornerRadiusSchema,+});++const ShapeLayerSchema = BaseLayerSchema.extend({+ type: z.literal('shape'),+ shapeType: z.enum([+ 'rectangle', 'ellipse', 'triangle', 'polygon', 'star', 'line', 'arrow', 'path',+ ]),+ shapeStyle: ShapeStyleSchema,+ points: z.array(z.object({ x: z.number(), y: z.number() })).optional(),+ sides: z.number().optional(),+ innerRadius: z.number().optional(),+});++const GroupLayerSchema = BaseLayerSchema.extend({+ type: z.literal('group'),+ childIds: z.array(z.string()),+ expanded: z.boolean(),+});++export const LayerSchema = z.discriminatedUnion('type', [+ ImageLayerSchema,+ TextLayerSchema,+ ShapeLayerSchema,+ GroupLayerSchema,+]);++// ── Project types ─────────────────────────────────────────────────────────────++const CanvasSizeSchema = z.object({ width: z.number(), height: z.number() });++const CanvasBackgroundSchema = z.object({+ type: z.enum(['color', 'gradient', 'image', 'transparent']),+ color: z.string().optional(),+ gradient: z+ .object({+ type: z.enum(['linear', 'radial']),+ angle: z.number(),+ stops: z.array(z.object({ offset: z.number(), color: z.string() })),+ })+ .optional(),+ imageId: z.string().optional(),+});++export const ArtboardSchema = z.object({+ id: z.string(),+ name: z.string(),+ size: CanvasSizeSchema,+ background: CanvasBackgroundSchema,+ layerIds: z.array(z.string()),+ position: z.object({ x: z.number(), y: z.number() }),+});++const MediaAssetSchema = z.object({+ id: z.string(),+ name: z.string(),+ type: z.enum(['image', 'svg']),+ mimeType: z.string(),+ size: z.number(),+ width: z.number(),+ height: z.number(),+ thumbnailUrl: z.string(),+ dataUrl: z.string().optional(),+ blobUrl: z.string().optional(),+});++/** Current project schema (version 1). */+export const ProjectSchema = z.object({+ id: z.string(),+ name: z.string(),+ createdAt: z.number(),+ updatedAt: z.number(),+ version: z.number(),+ artboards: z.array(ArtboardSchema),+ layers: z.record(z.string(), LayerSchema),+ assets: z.record(z.string(), MediaAssetSchema),+ activeArtboardId: z.string().nullable(),+});++export type ParsedProject = z.infer<typeof ProjectSchema>;++/**+ * Validate an unknown value against the Project schema.+ * Returns `{ success: true, data }` on success or `{ success: false, error }` on failure.+ */+export function parseProject(+ raw: unknown,+): { success: true; data: ParsedProject } | { success: false; error: string } {+ const result = ProjectSchema.safeParse(raw);+ if (result.success) {+ return { success: true, data: result.data };+ }+ return { success: false, error: result.error.message };+}diff --git a/packages/image-core/src/selection.ts b/packages/image-core/src/selection.tsnew file mode 100644index 00000000..1e1d1fdd--- /dev/null+++ b/packages/image-core/src/selection.ts@@ -0,0 +1,187 @@+export type SelectionType =+ | 'rectangular'+ | 'elliptical'+ | 'lasso'+ | 'polygonal'+ | 'magic-wand'+ | 'color-range';++export type SelectionMode = 'new' | 'add' | 'subtract' | 'intersect';++export interface SelectionBounds {+ x: number;+ y: number;+ width: number;+ height: number;+}++export interface Selection {+ id: string;+ type: SelectionType;+ bounds: SelectionBounds;+ path: { x: number; y: number }[];+ feather: number;+ antiAlias: boolean;+ opacity: number;+}++export interface MagicWandOptions {+ tolerance: number;+ contiguous: boolean;+ sampleAllLayers: boolean;+}++export interface ColorRangeOptions {+ fuzziness: number;+ range: 'sampled' | 'reds' | 'yellows' | 'greens' | 'cyans' | 'blues' | 'magentas' | 'highlights' | 'midtones' | 'shadows';+ invert: boolean;+}++export interface SelectionState {+ active: Selection | null;+ saved: Selection[];+ mode: SelectionMode;+ isSelecting: boolean;+ marching: boolean;+ magicWandOptions: MagicWandOptions;+ colorRangeOptions: ColorRangeOptions;+ tempPath: { x: number; y: number }[];+ startPoint: { x: number; y: number } | null;+}++export const DEFAULT_MAGIC_WAND_OPTIONS: MagicWandOptions = {+ tolerance: 32,+ contiguous: true,+ sampleAllLayers: false,+};++export const DEFAULT_COLOR_RANGE_OPTIONS: ColorRangeOptions = {+ fuzziness: 40,+ range: 'sampled',+ invert: false,+};++export function createEmptySelection(): Selection {+ return {+ id: '',+ type: 'rectangular',+ bounds: { x: 0, y: 0, width: 0, height: 0 },+ path: [],+ feather: 0,+ antiAlias: true,+ opacity: 1,+ };+}++export function selectionToPath2D(selection: Selection): Path2D {+ const path = new Path2D();++ if (selection.type === 'rectangular') {+ path.rect(+ selection.bounds.x,+ selection.bounds.y,+ selection.bounds.width,+ selection.bounds.height+ );+ } else if (selection.type === 'elliptical') {+ const cx = selection.bounds.x + selection.bounds.width / 2;+ const cy = selection.bounds.y + selection.bounds.height / 2;+ const rx = selection.bounds.width / 2;+ const ry = selection.bounds.height / 2;+ path.ellipse(cx, cy, rx, ry, 0, 0, Math.PI * 2);+ } else if (selection.path.length > 0) {+ path.moveTo(selection.path[0].x, selection.path[0].y);+ for (let i = 1; i < selection.path.length; i++) {+ path.lineTo(selection.path[i].x, selection.path[i].y);+ }+ path.closePath();+ }++ return path;+}++export function boundsFromPath(points: { x: number; y: number }[]): SelectionBounds {+ if (points.length === 0) {+ return { x: 0, y: 0, width: 0, height: 0 };+ }++ let minX = Infinity;+ let minY = Infinity;+ let maxX = -Infinity;+ let maxY = -Infinity;++ for (const point of points) {+ minX = Math.min(minX, point.x);+ minY = Math.min(minY, point.y);+ maxX = Math.max(maxX, point.x);+ maxY = Math.max(maxY, point.y);+ }++ return {+ x: minX,+ y: minY,+ width: maxX - minX,+ height: maxY - minY,+ };+}++export function isPointInSelection(+ x: number,+ y: number,+ selection: Selection,+ ctx?: CanvasRenderingContext2D+): boolean {+ if (!ctx) return false;++ const path = selectionToPath2D(selection);+ return ctx.isPointInPath(path, x, y);+}++export function combineSelections(+ existing: Selection,+ newSelection: Selection,+ mode: SelectionMode+): Selection {+ if (mode === 'new') {+ return newSelection;+ }++ const combined: Selection = {+ ...newSelection,+ id: existing.id || newSelection.id,+ };++ if (mode === 'add') {+ combined.path = [...existing.path, ...newSelection.path];+ combined.bounds = boundsFromPath(combined.path);+ } else if (mode === 'subtract') {+ combined.path = existing.path;+ combined.bounds = existing.bounds;+ } else if (mode === 'intersect') {+ combined.path = existing.path;+ combined.bounds = existing.bounds;+ }++ return combined;+}++export function getSelectionMask(+ selection: Selection,+ width: number,+ height: number+): ImageData {+ const canvas = new OffscreenCanvas(width, height);+ const ctx = canvas.getContext('2d')!;++ ctx.fillStyle = 'white';+ const path = selectionToPath2D(selection);+ ctx.fill(path);++ if (selection.feather > 0) {+ ctx.filter = `blur(${selection.feather}px)`;+ ctx.drawImage(canvas, 0, 0);+ ctx.filter = 'none';+ }++ return ctx.getImageData(0, 0, width, height);+}diff --git a/packages/image-core/tsconfig.json b/packages/image-core/tsconfig.jsonnew file mode 100644index 00000000..32a1de51--- /dev/null+++ b/packages/image-core/tsconfig.json@@ -0,0 +1,7 @@+{+ "extends": "../../tsconfig.base.json",+ "compilerOptions": {+ "noEmit": true+ },+ "include": ["src"]+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 4de476d9..17496f52 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -39,6 +39,9 @@ importers:'@imgly/background-removal':specifier: ^1.7.0version: 1.7.0([email protected])+ '@openreel/image-core':+ specifier: workspace:*+ version: link:../../packages/image-core'@openreel/ui':specifier: workspace:*version: link:../../packages/ui@@ -349,6 +352,19 @@ importers:specifier: ^1.6.0version: 1.6.1(@types/[email protected])([email protected])+ packages/image-core:+ dependencies:+ zod:+ specifier: ^4.4.3+ version: 4.4.3+ devDependencies:+ typescript:+ specifier: ^5.4.5+ version: 5.9.3+ vitest:+ specifier: ^1.6.0+ version: 1.6.1(@types/[email protected])([email protected])+packages/ui:dependencies:'@radix-ui/react-checkbox':diff --git a/tsconfig.base.json b/tsconfig.base.jsonindex d5ed444a..2f371ce2 100644--- a/tsconfig.base.json+++ b/tsconfig.base.json@@ -21,6 +21,8 @@"paths": {"@openreel/core": ["./packages/core/src/index.ts"],"@openreel/core/*": ["./packages/core/src/*"],+ "@openreel/image-core": ["./packages/image-core/src/index.ts"],+ "@openreel/image-core/*": ["./packages/image-core/src/*"],"@openreel/ui": ["./packages/ui/src/index.ts"],"@openreel/ui/*": ["./packages/ui/src/*"]}