Command palette

@yasinsensoy/web

Web · Components

MediaEditor

Image and video editor: full screen and dark like WhatsApp, made for finger use.

31 exports

Live example

Preview

Code

import { MediaEditor, FileUpload } from "@yasinsensoy/web";

const [files, setFiles] = useState([] as File[]);

<MediaEditor
  open={files.length > 0}
  onOpenChange={(open) => !open && setFiles([])}
  items={files}
  tools={{ image: {  }, video: {  } }}
  output={{ image: { type: "auto" }, video: { render: true } }}
  onDone={async (results) => {
    for (const r of results) await upload(r.file); // r.original + r.edits: edit again later
  }}
/>

// With FileUpload: the editor opens on select, each file gets an "Edit" button.
<FileUpload layout="gallery" multiple accept="image/*,video/*" edit />

Events

  1. Events appear here when you interact with the preview.

FileUpload + edit: pick, edit, add (like WhatsApp)

Profile photo: square, circular crop, crop + adjust only

Import

import {
  MediaEditor,
  mediaFilterPresets,
  hasMediaEdits,
  defaultMediaEditorMessages,
  renderImage,
  canRenderVideo,
  renderVideo,
} from "@yasinsensoy/web";

MediaEditor

componentClient component

Image and video editor: full screen and dark like WhatsApp, made for finger use.

  • Image: crop (free, original, preset ratios or a fixed ratio; a circle for profiles), 90° rotation, mirroring, drawing with a pen and highlighter, a blur (pixelate) brush, draggable text (plain or boxed), preset looks and brightness/contrast/saturation/warmth adjustments.
  • Video: range selection with two handles on a frame strip (duration limit with maxDuration), mute, play/pause; all image tools (crop, rotate, draw, text, blur, color) apply to video too.
  • Multiple: with several items a thumbnail strip at the bottom; each item has its own edits and undo history. Edited ones are marked.
  • Non-destructive editing: edits are kept as MediaEdits and returned with the original file in the result; you can continue later from the same point. A file with no changes isn't reprocessed (no quality loss).
  • Performance: the on-screen preview uses a downscaled copy and color adjustment is drawn on the GPU (CSS filter); full resolution is processed only on "Done". Video is processed with the browser's own encoder (MP4 or WebM); processing can be cancelled.
  • Keyboard: Ctrl/⌘+Z undo, Ctrl/⌘+Shift+Z redo; the crop area and texts move with the arrow keys, Delete removes a text; trim handles move with the arrow keys (1 s with Shift).
  • Mobile: the phone's back button closes it; a text is deleted by dragging it to the trash; tools are at the bottom within thumb reach.

It is very small while closed; the actual editor is loaded on demand as a separate chunk when used via edit in FileUpload.

MediaEditor(props: MediaEditorProps): JSX.Element | null

Examples

const [files, setFiles] = useState<File[]>([]);
<MediaEditor
  open={files.length > 0}
  onOpenChange={(open) => !open && setFiles([])}
  items={files}
  tools={{ image: { crop: { aspectRatio: 1, shape: "circle" } }, video: { trim: { maxDuration: 30 } } }}
  onDone={async (results) => { for (const r of results) await upload(r.file); }}
/>

Built-in looks. Their names are written to MediaAdjustments.preset; the on-screen names come from the preset_<name> keys in the mediaEditor texts.

mediaFilterPresets: { /** Original. */ none: {}; /** Vivid: saturated and a bit harsh. */ vivid: { saturation: number; contrast: number; }; /** Warm: shifted toward yellow. */ warm: { warmth: number; saturation: number; }; /** Cool: shifted toward blue. */ cool: { warmth: number; saturation: number; }; /** Faded: low contrast, slightly bright. */ fade: { contrast: number; brightness: number; saturation: number; }; /** Dramatic: harsh and less saturated. */ drama: { contrast: number; saturation: number; brightness: number; }; /** Black and white. */ mono: { grayscale: number; contrast: number; }; /** Noir: harsh black and white. */ noir: { grayscale: number; contrast: number; brightness: number; }; /** Old photo. */ sepia: { sepia: number; contrast: number; }; }

Whether the edits change the appearance; if not, the file isn't reprocessed (no quality loss and no waiting).

hasMediaEdits(edits: MediaEdits | undefined, duration?: number): boolean

Turkish texts of MediaEditor.

defaultMediaEditorMessages: MediaEditorMessages

renderImage

function

Applies edits to an image and produces a new file. The editor calls it itself on "Done"; it can also be used directly in your own flow (e.g. to apply stored edits before sending to the server).

renderImage(file: Blob & { name?: string; }, edits: MediaEdits, output?: MediaImageOutput): Promise<File>

Examples

const cropped = await renderImage(file, { crop: { x: 0.1, y: 0, width: 0.8, height: 1 } });

Can the browser reprocess the video (MediaRecorder and canvas.captureStream)? If not, the editor returns the original file and the edits.

canRenderVideo(): boolean

renderVideo

function

Applies edits (trim, mute, crop, rotate, color, drawing, text) to a video and produces a new file. Works in real time with the browser's own encoder (MediaRecorder): a 10-second clip takes about 10 seconds. The output is MP4 (H.264/AAC) if supported, otherwise WebM.

If the tab goes to the background the browser may slow down frames; the page should stay open while processing.

renderVideo(file: Blob & { name?: string; }, edits: MediaEdits, options?: RenderVideoOptions): Promise<File>

Examples

const short = await renderVideo(file, { trim: { start: 2, end: 12 }, muted: true }, {
  onProgress: (p) => setPercent(Math.round(p * 100)),
});

Built-in look name.

type MediaFilterPreset = keyof typeof mediaFilterPresets

File given to the editor: a File or an object with a URL/edit info.

NameTypeDescription
id?stringUnique key; returned as is in the result. If omitted, the index.
file?BlobFile to edit. If missing, it is downloaded from url.
url?stringURL of a file on the server (if there is no file). It must be same-origin or CORS-enabled so it can be drawn on a canvas.
name?stringFile name.
type?stringMIME type; the kind (image/video) is chosen by it.
edits?MediaEditsPrevious edits; the editor opens with them and they can be undone.

Result the editor returns for a file.

NameTypeDescription
idstringThe item's id (the index if not given).
kindMediaKindImage or video.
fileFileResult file: the new file if edited, the original if not. For video, it is the original if output.video.render is false or the browser can't process it; the edits are in edits.
originalFileOriginal file; store it with edits to re-edit.
editsMediaEditsApplied edits (an empty object: no edits).
editedbooleanDid the look change?
renderedbooleanDoes file include the edits? (false: the server should apply them.)

Props of the MediaEditor component.

NameTypeDefaultDescription
openbooleanIs it open? Nothing renders while closed, and the state resets.
onOpenChange(open: boolean) => voidCalled when the open state wants to change (close, cancel, done).
itemsreadonly (File | MediaEditorItem)[]Images and videos to edit. With one item the single view opens, with several the multi view with a thumbnail strip at the bottom. Files other than images and videos are ignored. Changes while open are not taken into account.
tools?MediaEditorToolsWhich tools are enabled. See MediaEditorTools.
output?MediaEditorOutputOutput settings (type, quality, size, video processing). See MediaEditorOutput.
onDone(results: MediaEditorResult[]) => unknownCalled when "Done" is pressed, after the files are processed. If it returns a Promise, the editor stays open until it settles.
onCancel?() => voidCalled when the user cancels editing.
removable?booleantrueIn the multi view files can be removed from the strip (removed ones are not in the result).
doneLabel?ReactNodea check iconContent of the Done button.
defaultIndex?number0Index of the item opened first.
confirmDiscard?booleantrueAsk when closing with unsaved changes?
messages?Partial<MediaEditorMessages>Texts. See MediaEditorMessages.
className?stringClasses added to the window.

MediaEditor texts. Placeholders like {name} are filled in. Changed app-wide in the dictionary's ui.mediaEditor namespace, or for one editor with the messages prop.

NameTypeDescription
titlestringScreen reader name of the window.
closestringClose button.
donestringDone button.
undostringUndo.
redostringRedo.
cropstringCrop tool.
drawstringDraw tool.
blurstringBlur tool.
textstringText tool.
adjuststringColor adjustment tool.
mutestringMute the video's audio.
unmutestringUnmute the video.
cropAreastringCrop area (moved with arrow keys).
rotatestringRotate left.
flipstringMirror.
resetstringReset the tool's edits.
aspectFreestringFree crop ratio.
aspectOriginalstringOriginal crop ratio.
penstringPen brush.
markerstringHighlighter brush.
sizestringBrush size.
colorstringColor selection.
textPlaceholderstringPlaceholder of the text box.
textSizestringText size slider.
textStylestringButton that changes the text style.
deleteTextstringText delete zone.
textHandlestringMove hint for text (screen reader): {text}.
presetsstringBuilt-in looks tab.
adjustmentsstringSettings tab.
brightnessstringBrightness.
contraststringContrast.
saturationstringSaturation.
warmthstringWarmth.
preset{ /** Original. */ none: string; /** Vivid. */ vivid: string; /** Warm. */ warm: string; /** Cool. */ cool: string; /** Faded. */ fade: string; /** Dramatik. */ drama: string; /** Black and white. */ mono: string; /** Noir. */ noir: string; /** Sepya. */ sepia: string; }Built-in look names (by mediaFilterPresets keys).
playstringPlay.
pausestringPause.
trimStartstringTrim start handle.
trimEndstringTrim end handle.
maxDurationstringMaximum trimmed duration: {duration}.
itemOfstringName of the file in the queue: {index}, {count}.
removestringRemove the file from the list: {name}.
editedstringScreen reader state of an edited file.
itemsstringName of the file strip.
processingstringWhile processing.
processingOfstringProcessing percentage: {index}, {count}, {percent}.
cancelstringCancel processing.
discardTitlestringQuestion when closing with unsaved changes.
discardDescriptionstringDescription of the close question.
discardstringDiscard changes and close.
loadErrorstringThe file could not be opened.
renderErrorstringThe file could not be processed.

MediaRect

interface

Rectangle given as fractions (0 – 1) of the source. Regardless of rotation and mirroring it is always in the coordinates of the original image/video, so it shows the same region even when rotated later.

NameTypeDescription
xnumberLeft edge (0 – 1).
ynumberTop edge (0 – 1).
widthnumberWidth (0 – 1).
heightnumberHeight (0 – 1).

Clockwise rotation angle.

type MediaRotation = 0 | 90 | 180 | 270

Brush kind.

  • pen: plain pen.
  • marker: semi-transparent, thick highlighter.
  • blur: pixelates where it passes (to hide faces, plates, addresses).
type MediaBrush = "pen" | "marker" | "blur"

MediaStroke

interface

A brush stroke. Points are fractions of the original source.

NameTypeDescription
brushMediaBrushBrush. See MediaBrush.
colorstringColor (CSS color); not used for blur.
sizenumberThickness: fraction of the source's short edge (e.g. 0.01).
pointsnumber[]Points in order [x0, y0, x1, y1, …] (0 – 1).

Text style.

  • plain: plain text with a shadow.
  • box: text inside a colored box (text color black or white depending on the box).
type MediaTextStyle = "plain" | "box"

MediaText

interface

Text added over the image.

NameTypeDescription
idstringUnique key.
textstringText; lines are separated with \n.
xnumberCenter of the text: fractions of the original source (0 – 1).
ynumberCenter of the text (vertical).
sizenumberFont size: fraction of the source's short edge (e.g. 0.06).
colorstringColor (CSS color).
styleMediaTextStyleStyle. See MediaTextStyle.

Color adjustments. Each is between -1 and 1 around 0 (unchanged); preset picks a built-in look and the adjustments are added on top.

NameTypeDescription
preset?string | undefinedBuilt-in look name (e.g. "vivid"). See mediaFilterPresets.
brightness?number | undefinedBrightness.
contrast?number | undefinedContrast.
saturation?number | undefinedSaturation.
warmth?number | undefinedWarmth: negative is cool (blue), positive warm (yellow).

MediaEdits

interface

Edits of an image or video. Stored non-destructively (the original file is untouched); the same edits can be reopened and changed later, or applied on the server. An empty object means no edits.

NameTypeDefaultDescription
rotation?MediaRotation | undefined0Clockwise rotation.
flip?boolean | undefinedHorizontal mirroring (after rotation).
crop?MediaRect | undefinedCropped region (relative to the original source). Everything when absent.
adjust?MediaAdjustments | undefinedColor adjustments.
strokes?readonly MediaStroke[] | undefinedDrawings (in the order added).
texts?readonly MediaText[] | undefinedTexts.
trim?{ start: number; end: number; } | undefinedTrimmed range of a video (seconds).
muted?boolean | undefinedThe video is muted.

Media type.

type MediaKind = "image" | "video"

Crop ratio option: a number (width / height), "original" (the original ratio) or "free".

type MediaAspectRatio = number | "original" | "free"

Crop tool options.

NameTypeDefaultDescription
aspectRatio?numberFixed ratio (e.g. 1 for a profile picture). When given, the user can't change the ratio and the editor center-crops to it on open.
aspectRatios?readonly MediaAspectRatio[]["free", "original", 1, 4 / 5, 16 / 9]Ratios the user can choose.
shape?"rect" | "circle"Show the crop area as a circle (profile picture). The output is still square.
rotate?booleantrueRotate and mirror buttons.

Video trim tool options.

NameTypeDefaultDescription
maxDuration?numberMaximum duration (seconds). Longer videos are trimmed to it on open.
minDuration?number0.5Minimum duration (seconds).

Tools available for images. Each is true (default) or false; crop can also take an options object.

NameTypeDescription
crop?boolean | MediaCropOptionsCrop, rotate, mirror. See MediaCropOptions.
draw?booleanPen drawing.
blur?booleanBlur (pixelate) brush.
text?booleanAdding text.
adjust?booleanBuilt-in looks and brightness/contrast/saturation/warmth.

Tools available for videos; trim and sound in addition to the image tools.

Extends: MediaImageTools

NameTypeDescription
trim?boolean | MediaTrimOptionsTrimming by selecting a range. See MediaTrimOptions.
mute?booleanMute button.

Which tools are enabled for which type. true enables all tools, false means that type isn't edited; an object picks tool by tool.

NameTypeDefaultDescription
image?boolean | MediaImageToolstrueImage tools.
video?boolean | MediaVideoToolstrueVideo tools.

Examples

`{ image: { crop: { aspectRatio: 1, shape: "circle" }, text: false }, video: false }`

Image output options.

NameTypeDefaultDescription
type?"auto" | "image/jpeg" | "image/png" | "image/webp""auto"File type. "auto" keeps the original type (JPEG, PNG, WebP) and makes everything else JPEG.
quality?number0.92JPEG/WebP quality (0 – 1).
maxSize?number4096Maximum size of the long edge (pixels); larger images are downscaled.

Video output options.

NameTypeDefaultDescription
render?booleantrueRender the edits into a new video in the browser? Rendering is real time (a 10 s clip takes ≈ 10 s). With false the original file and edits are returned and the server applies the edits (e.g. ffmpeg).
maxSize?number1920Maximum size of the long edge (pixels).
bitrate?numberBitrate (bits/s). Chosen from the resolution when omitted.
frameRate?number30Frame rate.

Output options for edited files.

NameTypeDescription
image?MediaImageOutputImages. See MediaImageOutput.
video?MediaVideoOutputVideos. See MediaVideoOutput.

renderVideo options.

Extends: MediaVideoOutput

NameTypeDescription
signal?AbortSignalCancels the process; the promise rejects with AbortError.
onProgress?(progress: number) => voidProgress (0 – 1).