Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 23 additions & 5 deletions src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,35 @@
import Page from '@/app/share/[id]/page';

const APPLE_LOGO_ID = '01JMFPY99JXXKRQWDAHBY0ARQH';


const APPLE_LOGO_ID = '01JMFPY99JXXKRQWDAHBY0ARQH';

export default function Home() {


return (


<Page


params={


new Promise((resolve) =>


resolve({


id: APPLE_LOGO_ID,


})


)
}
/>
);
}
}
/>
);
}
193 changes: 193 additions & 0 deletions src/app/recorder.tsx
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not all browsers support vp9. Consider fallback

mimeType: MediaRecorder.isTypeSupported('video/webm;codecs=vp9') 
  ? 'video/webm;codecs=vp9' 
  : 'video/webm';

Also for the following code,

useEffect(() => {
    return () => {
        if (recordingRef.current) {
            recordingRef.current.stop();
        }
    };
}, []);

If the component unmounts mid-recording, this is helpful, but consider stopping the stopwatch too.

useEffect(() => {
    return () => {
        recordingRef.current?.stop();
        stopStopWatch();
    };
}, []);

Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
'use client';

import { useStopWatch } from '@/hooks/use-stop-watch';
import { useState, useRef, useEffect, type JSX } from 'react';
import { toast } from 'sonner';

type RecordingControls = {
stop: () => void;
};

function record(
canvasRef: React.RefObject<HTMLCanvasElement | null>,
onStop: () => void
): RecordingControls | null {
const canvas = canvasRef.current;
console.log('Attempting to record canvas:', canvas);

if (!canvas) {
console.warn('No canvas element found');
return null;
}

try {
console.log('Capturing stream from canvas');
const stream = canvas.captureStream(30);
console.log('Stream obtained:', stream);

const mediaRecorder = new MediaRecorder(stream, {
mimeType: 'video/webm;codecs=vp9',
videoBitsPerSecond: 10_000_000
});

const chunks: Blob[] = [];

mediaRecorder.ondataavailable = (event) => {
if (event.data.size > 0) {
chunks.push(event.data);
console.log('Received chunk:', event.data.size);
}
};

mediaRecorder.onstop = () => {
if (chunks.length > 0) {
console.log('Starting export with', chunks.length, 'chunks');

const blob = new Blob(chunks, { type: 'video/webm' });
console.log('Blob created:', blob.size);

const url = URL.createObjectURL(blob);
console.log('Object URL created:', url);

const a = document.createElement('a');
a.href = url;
a.download = `recording-${Date.now()}.webm`;

document.body.appendChild(a);
const clickEvent = new MouseEvent('click', {
bubbles: true,
cancelable: true,
view: window
});

a.dispatchEvent(clickEvent);
document.body.removeChild(a);

URL.revokeObjectURL(url);
chunks.length = 0;

console.log('Export completed');
} else {
console.log('No chunks available for export');
toast.error('No video data recorded');
}

onStop();
};

mediaRecorder.start(1000);
return { stop: () => mediaRecorder.stop() };
} catch (error) {
toast.error(`Recording failed: ${error}`);
return null;
}
}

interface RecorderProps {
className?: string;
canvasRef: React.RefObject<HTMLCanvasElement | null>;
}

function Recorder({ className, canvasRef }: RecorderProps): JSX.Element {
const [isRecording, setIsRecording] = useState(false);
const { timeElapsed, startStopWatch, stopStopWatch } = useStopWatch();
const [exporting, setExporting] = useState(false);
const recordingRef = useRef<RecordingControls | null>(null);

const toggleRecording = () => {
console.log('Toggle recording called');
console.log('Canvas ref:', canvasRef.current);

if (!canvasRef.current) {
console.log('Error: No canvas element found');
toast.error('No canvas element found');
return;
}

if (isRecording) {
console.log('Stopping recording...');
stopStopWatch();
recordingRef.current?.stop();
setIsRecording(false);
setExporting(true);
} else {
console.log('Starting recording...');
startStopWatch();
recordingRef.current = record(canvasRef, () => setExporting(false));
setIsRecording(true);
setExporting(false);
}
};

useEffect(() => {
return () => {
if (recordingRef.current) {
recordingRef.current.stop();
}
};
}, []);

const formatTime = (seconds: number): string => {
const minutes = Math.floor(seconds / 60);
const remainingSeconds = seconds % 60;
return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
};

return (
<div className={`flex items-center gap-20 overflow-hidden ${className || ''}`}>
{exporting && (
<div className="text-white text-sm mb-2">
Exporting video...
</div>
)}

<div className={`text-2xl font-mono font-bold text-white w-40 ${isRecording ? 'visible' : 'invisible'}`}>
{formatTime(timeElapsed)}
</div>

<RecordButton
isRecording={isRecording}
exporting={exporting}
toggleRecording={toggleRecording}
/>
</div>
);
}

function RecordButton({
isRecording,
exporting,
toggleRecording
}: {
isRecording: boolean;
exporting: boolean;
toggleRecording: () => void;
}): JSX.Element {
return (
<button
className={`relative flex h-35 w-35 items-center justify-center rounded-full bg-white transition-all duration-300 ${
isRecording ? 'bg-red-500 hover:bg-red-600' : ''
}`}
onClick={toggleRecording}
aria-label={exporting ? 'Exporting...' : isRecording ? 'Stop recording' : 'Start recording'}
disabled={exporting}
>
<div className={`flex h-[calc(100%-4px)] w-[calc(100%-4px)] items-center justify-center rounded-full bg-button transition-all duration-300 ${
isRecording ? 'scale-[0.6]' : ''
}`}>
{exporting && (
<div className="w-4 h-4 border-t-2 border-white rounded-full animate-spin" />
)}
</div>

{isRecording && (
<div className="absolute -top-1 -right-1 h-2 w-2">
<div className="bg-red-500 animate-ping absolute h-full w-full rounded-full opacity-75"></div>
<div className="bg-red-500 absolute h-full w-full rounded-full"></div>
</div>
)}
</button>
);
}

export default Recorder;
11 changes: 9 additions & 2 deletions src/hero/canvas.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
'use client';

import { liquidFragSource } from '@/app/hero/liquid-frag';
import { useEffect, useRef, useState } from 'react';
import { useEffect, useRef, useState, type Ref, type RefObject} from 'react';
import { toast } from 'sonner';

// uniform sampler2D u_image_texture;
// uniform float u_time;
// uniform float u_ratio;
Expand Down Expand Up @@ -38,10 +37,12 @@ export function Canvas({
imageData,
params,
processing,
ref
}: {
imageData: ImageData;
params: ShaderParams;
processing: boolean;
ref: RefObject<HTMLCanvasElement | null>
}) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const [gl, setGl] = useState<WebGL2RenderingContext | null>(null);
Expand Down Expand Up @@ -251,5 +252,11 @@ export function Canvas({
};
}, [gl, uniforms, imageData]);

useEffect(() => {
if(ref && canvasRef.current){
ref.current = canvasRef.current;
}
},[canvasRef,ref])

return <canvas ref={canvasRef} className="block h-full w-full object-contain" />;
}
41 changes: 26 additions & 15 deletions src/hero/hero.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { toast } from 'sonner';
import { parseLogoImage } from './parse-logo-image';
import { uploadImage } from '@/hero/upload-image';
import isEqual from 'lodash-es/isEqual';
import Recorder from '@/app/recorder';

interface HeroProps {
imageId: string;
Expand All @@ -35,8 +36,10 @@ export function Hero({ imageId }: HeroProps) {
const [imageData, setImageData] = useState<ImageData | null>(null);
const [processing, setProcessing] = useState<boolean>(true);

const canvasRef = useRef<HTMLCanvasElement>(null);
// Check URL for image ID on mount
useEffect(() => {
console.log(canvasRef);
setProcessing(true);

async function updateImageData() {
Expand All @@ -61,7 +64,7 @@ export function Hero({ imageId }: HeroProps) {
}

updateImageData();
}, [imageId]);
}, [imageId, canvasRef]);

useEffect(() => {
stateRef.current = state;
Expand Down Expand Up @@ -189,20 +192,25 @@ export function Hero({ imageId }: HeroProps) {
handleFiles(files);
}}
>
<div
className="flex aspect-square w-full items-center justify-center rounded-10"
style={{
background: (() => {
switch (state.background) {
case 'metal':
return 'linear-gradient(to bottom, #eee, #b8b8b8)';
}
return state.background;
})(),
}}
>
<div className="aspect-square w-400">
{imageData && <Canvas imageData={imageData} params={state} processing={processing} />}
<div className='flex flex-col relative h-full'>
<div className='-top-45 right-0 absolute'>
<Recorder canvasRef={canvasRef} className=""></Recorder>
</div>
<div
className="flex aspect-square w-full items-center justify-center rounded-10 h-full"
style={{
background: (() => {
switch (state.background) {
case 'metal':
return 'linear-gradient(to bottom, #eee, #b8b8b8)';
}
return state.background;
})(),
}}
>
<div className="aspect-square w-400">
{imageData && <Canvas ref={canvasRef} imageData={imageData} params={state} processing={processing} />}
</div>
</div>
</div>

Expand Down Expand Up @@ -327,6 +335,9 @@ export function Hero({ imageId }: HeroProps) {
Tips: transparent or white background is required. Shapes work better than words. Use an SVG or a
high-resolution image.
</p>
<p className="w-fill text-sm text-white/80" style={{ fontSize: '12px', color: 'gray' }}>
Export function improved by <a href="https://instagram.com/yaboyraz/">@yaboyraz on instagram</a>
</p>
</div>
</div>
</div>
Expand Down
Loading