HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URLs added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
#root
.App {
font-family: sans-serif;
text-align: center;
}
* {
box-sizing: border-box;
}
body {
min-height: 100vh;
display: grid;
place-items: center;
}
const { XState, XStateReact, React, ReactDOM } = window
const { createMachine, assign, send: sendUtil } = XState
const { useMachine } = XStateReact
function assertNonNull<PossibleNullType>(
possibleNull: PossibleNullType,
errorMessage: string
): asserts possibleNull is Exclude<PossibleNullType, null> {
if (possibleNull === null) throw new Error(errorMessage);
}
const devTools = false;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (devTools && typeof window !== "undefined") {
inspect({ iframe: false });
}
function stopMediaRecorder(mediaRecorder: MediaRecorder) {
if (mediaRecorder.state !== "inactive") mediaRecorder.stop();
for (const track of mediaRecorder.stream.getAudioTracks()) {
if (track.enabled) track.stop();
}
mediaRecorder.ondataavailable = null;
}
interface RecorderContext {
mediaRecorder: MediaRecorder | null;
audioDevices: Array<MediaDeviceInfo>;
selectedAudioDevice: MediaDeviceInfo | null;
audioBlob: Blob | null;
}
const recorderMachine = createMachine<RecorderContext>(
{
id: "recorder",
context: {
mediaRecorder: null,
audioDevices: [],
selectedAudioDevice: null,
audioBlob: null
},
initial: "gettingDevices",
states: {
gettingDevices: {
invoke: {
src: "getDevices",
onDone: { target: "ready", actions: "assignAudioDevices" },
onError: "" // TODO
}
},
selecting: {
on: {
selection: { target: "ready", actions: "assignSelectedAudioDevice" }
}
},
ready: {
on: {
changeDevice: "selecting",
start: "recording"
}
},
recording: {
invoke: { src: "mediaRecorder" },
initial: "playing",
states: {
playing: {
on: {
mediaRecorderCreated: {
actions: ["assignMediaRecorder"]
},
pause: {
target: "paused",
actions: sendUtil("pause", { to: "mediaRecorder" })
},
stop: "stopping"
}
},
paused: {
on: {
resume: {
target: "playing",
actions: sendUtil("resume", { to: "mediaRecorder" })
},
stop: "stopping"
}
},
stopping: {
entry: sendUtil("stop", { to: "mediaRecorder" }),
on: {
chunks: { target: "#recorder.done", actions: "assignAudioBlob" }
}
}
}
},
done: {
on: {
restart: "ready"
}
}
}
},
{
services: {
getDevices: async () => {
const devices = await navigator.mediaDevices.enumerateDevices();
return devices.filter(({ kind }) => kind === "audioinput");
},
mediaRecorder: (context) => (sendBack, receive) => {
let mediaRecorder: MediaRecorder;
async function go() {
const chunks: Array<BlobPart> = [];
const deviceId = context.selectedAudioDevice?.deviceId;
const audio = deviceId ? { deviceId: { exact: deviceId } } : true;
const mediaStream = await window.navigator.mediaDevices.getUserMedia({
audio
});
mediaRecorder = new MediaRecorder(mediaStream);
sendBack({ type: "mediaRecorderCreated", mediaRecorder });
mediaRecorder.ondataavailable = (event) => {
chunks.push(event.data);
console.info('running')
if (mediaRecorder.state === "inactive") {
sendBack({
type: "chunks",
blob: new Blob(chunks, {
type: "audio/mp3"
})
});
}
};
mediaRecorder.start();
receive((event) => {
if (event.type === "pause") {
mediaRecorder.pause();
} else if (event.type === "resume") {
mediaRecorder.resume();
} else if (event.type === "stop") {
mediaRecorder.stop();
}
});
}
void go();
return () => {
stopMediaRecorder(mediaRecorder);
};
}
},
actions: {
assignAudioDevices: assign({
audioDevices: (context, event) => event.data
}),
assignSelectedAudioDevice: assign({
selectedAudioDevice: (context, event) => event.selectedAudioDevice
}),
assignMediaRecorder: assign({
mediaRecorder: (context, event) => event.mediaRecorder
}),
assignAudioBlob: assign({
audioBlob: (context, event) => event.blob
})
}
}
);
function CallRecorder({
onRecordingComplete
}: {
onRecordingComplete: (audio: Blob) => void;
}) {
const [state, send] = useMachine(recorderMachine, { devTools });
const { audioBlob } = state.context;
const audioURL = React.useMemo(() => {
if (audioBlob) {
return window.URL.createObjectURL(audioBlob);
} else {
return null;
}
}, [audioBlob]);
let deviceSelection = null;
if (state.matches("gettingDevices")) {
deviceSelection = <div>Loading devices</div>;
}
if (state.matches("selecting")) {
deviceSelection = (
<div>
Select your device:
<ul>
{state.context.audioDevices.length
? state.context.audioDevices.map((device) => (
<li key={device.deviceId}>
<button
onClick={() => {
send({
type: "selection",
selectedAudioDevice: device
});
}}
style={{
fontWeight:
state.context.selectedAudioDevice === device
? "bold"
: "normal"
}}
>
{device.label}
</button>
</li>
))
: "No audio devices found"}
</ul>
</div>
);
}
let audioPreview = null;
if (state.matches("done")) {
assertNonNull(
audioURL,
`The state machine is in "stopped" state but there's no audioURL. This should be impossible.`
);
assertNonNull(
audioBlob,
`The state machine is in "stopped" state but there's no audioBlob. This should be impossible.`
);
audioPreview = (
<div>
<audio src={audioURL} controls />
<button onClick={() => onRecordingComplete(audioBlob)}>Accept</button>
<button onClick={() => send({ type: "restart" })}>Re-record</button>
</div>
);
}
return (
<div>
{state.matches("ready") ? (
<button onClick={() => send({ type: "changeDevice" })}>
Change audio device from{" "}
{state.context.selectedAudioDevice?.label ?? "default"}
</button>
) : null}
{deviceSelection}
{state.matches("ready") ? (
<button onClick={() => send({ type: "start" })}>Start</button>
) : null}
{state.matches("recording") && state.context.mediaRecorder ? (
<StreamVis stream={state.context.mediaRecorder.stream} />
) : null}
{state.matches("recording.playing") ? (
<>
<button onClick={() => send({ type: "stop" })}>Stop</button>
<button onClick={() => send({ type: "pause" })}>Pause</button>
</>
) : state.matches("recording.paused") ? (
<>
<button onClick={() => send({ type: "stop" })}>Stop</button>
<button onClick={() => send({ type: "resume" })}>Resume</button>
</>
) : state.matches("recording.stopping") ? (
<div>Processing...</div>
) : null}
{audioPreview}
</div>
);
}
function visualize(canvas: HTMLCanvasElement, stream: MediaStream) {
const audioCtx = new AudioContext();
const canvasCtx = canvas.getContext("2d");
const source = audioCtx.createMediaStreamSource(stream);
const analyser = audioCtx.createAnalyser();
analyser.fftSize = 2048;
const bufferLength = analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
source.connect(analyser);
function draw() {
if (!canvasCtx) return;
const WIDTH = canvas.width;
const HEIGHT = canvas.height;
analyser.getByteTimeDomainData(dataArray);
canvasCtx.fillStyle = "rgb(180, 180, 180)";
canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
canvasCtx.lineWidth = 2;
canvasCtx.strokeStyle = "rgb(0, 0, 0)";
canvasCtx.beginPath();
const sliceWidth = (WIDTH * 1.0) / bufferLength;
let x = 0;
for (let i = 0; i < bufferLength; i++) {
const v = (dataArray[i] ?? 0) / 128.0;
const y = (v * HEIGHT) / 2;
if (i === 0) {
canvasCtx.moveTo(x, y);
} else {
canvasCtx.lineTo(x, y);
}
x += sliceWidth;
}
canvasCtx.lineTo(canvas.width, canvas.height / 2);
canvasCtx.stroke();
}
return draw;
}
function StreamVis({ stream }: { stream: MediaStream }) {
const canvasRef = React.useRef<HTMLCanvasElement | null>(null);
React.useEffect(() => {
if (!canvasRef.current) return () => {};
const draw = visualize(canvasRef.current, stream);
let lastReq: number;
function reqDraw() {
lastReq = requestAnimationFrame(() => {
draw();
reqDraw();
// TODO: this happens too frequently...
});
}
reqDraw();
return () => {
cancelAnimationFrame(lastReq);
};
}, [stream]);
return <canvas ref={canvasRef} />;
}
ReactDOM.render(
<CallRecorder
onRecordingComplete={(...args) => console.log("complete", ...args)}
/>,
document.getElementById("root")
);
Also see: Tab Triggers