Command palette

@yasinsensoy/native

React Native · Components

MediaEditor

Image and video editor: full screen, dark, suited to finger use.

34 exports

Live example

The preview runs in the browser with the web component; the native component takes the same props and looks the same on iOS and Android.

Preview

Code

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

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,
  enMediaEditorMessages,
  canRenderMedia,
  renderImage,
  renderVideo,
} from "@yasinsensoy/native";

MediaEditor

component

Image and video editor: full screen, dark, suited to finger use. The same tools and the same edit format (MediaEdits) as MediaEditor on web; an edit saved on one platform gives the same result on the other.

  • Image: cropping (free, original, preset ratios or a fixed ratio; a circle for profiles), 90° rotation, flipping, drawing with a pen and a highlighter, a blur (pixelate) brush, texts that can be dragged and resized from the corner (plain or boxed), preset looks and brightness/contrast/saturation/temperature adjustments.
  • Video: range selection with two handles on a frame strip (a duration limit with maxDuration), muting, play/pause; all image tools apply to videos too and are visible while playing in the preview.
  • Multiple: a thumbnail strip at the bottom for multiple items; each item has its own edits and undo history. Edited ones are marked.
  • Non-destructive editing: edits are returned in the result together with the original file; a file with no changes is not reprocessed.
  • Performance: the preview and the output are drawn on the GPU with the same native code (Android OpenGL ES, iOS Core Image); video is processed with the device's hardware encoder, and processing can be cancelled.
  • Mobile: the back button closes the text first, then the operation, then the editor; a text is deleted by dragging it onto the trash; tools are at the bottom within thumb reach.

The native module is added to the build automatically when @yasinsensoy/native/media-editor is imported.

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

Examples

const [files, setFiles] = useState<PickedFile[]>([]);
<Button onPress={async () => setFiles(await FileSystem.pickMedia({ multiple: true }))}>Pick</Button>
<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.uri); }}
/>

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

Built-in English texts for MediaEditorMessages.

enMediaEditorMessages: MediaEditorMessages

Whether media processing is in this build. When the MediaEditor feature is used (when this subpath is imported), the native module is added to the build automatically.

canRenderMedia(): boolean

renderImage

function

Applies edits to an image and produces a new file (in the app's cache folder). The editor calls it itself on "Done"; it can also be used directly to apply stored edits later.

renderImage(input: MediaSource, edits: MediaEdits, output?: MediaImageOutput): Promise<MediaFile>

Examples

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

renderVideo

function

Applies edits to a video and produces a new MP4 (H.264) file. Cropping, rotation, flipping, color, drawing, text and blur are applied to every frame; trimming and muting are applied. Processing uses the device's hardware encoder, faster than real time, and can be cancelled.

On Android the audio is not re-encoded (no quality loss); on iOS the bit rate is chosen by the system (bitrate applies only on Android).

renderVideo(input: MediaSource, edits: MediaEdits, options?: RenderVideoOptions): Promise<MediaFile>

Examples

const trimmed = await renderVideo(video.uri, { trim: { start: 2, end: 12 } }, {
  onProgress: (p) => setPercent(Math.round(p * 100)),
});

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.

Built-in look name.

type MediaFilterPreset = keyof typeof mediaFilterPresets

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.

A file given to the editor. A FileSystem.pickMedia result can be passed directly.

NameTypeDescription
id?stringUnique key; returned unchanged in the result. Defaults to the index.
uristringAddress of the file: file://, content:// on Android, or http(s)://.
name?string | nullFile name. If omitted it is derived from the address.
type?string | nullMIME type; the kind (image/video) is picked from it (or from the extension).
headers?Record<string, string>Request headers for a remote address (protected files).
edits?MediaEditsPrevious edits; the editor opens with them and they can be undone.

The result the editor returns for a file.

NameTypeDescription
idstringThe item's id (the index if not given).
kindMediaKindImage or video.
fileMediaFileResult file: a new file (in the app's cache folder) if edited, otherwise the original file. For a video with output.video.render false it is the original file; the edits are in edits.
originalMediaFileThe original file; keep it together with edits for re-editing.
editsMediaEditsApplied edits (an empty object: no edits).
editedbooleanWhether the look changed.
renderedbooleanWhether file contains the edits (false: the server applies them).

Props of the MediaEditor component.

NameTypeDefaultDescription
openbooleanWhether it is open. While closed nothing is drawn and the state resets.
onOpenChange(open: boolean) => voidCalled when the open state wants to change (close, cancel, done).
itemsreadonly MediaEditorItem[]Images and videos to edit. A single item opens the single view; multiple items open 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 finishes.
onCancel?() => voidCalled when the user gives up 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 before closing with unsaved changes?
messages?Partial<MediaEditorMessages>Texts. See MediaEditorMessages; enMediaEditorMessages for English.
testID?stringTest id.

MediaFile

interface

A file the editor reads or produces.

NameTypeDescription
uristringAddress: file://, content:// on Android, or http(s)://.
namestringFile name.
typestringMIME type.
width?numberWidth (pixels); if known.
height?numberHeight (pixels); if known.
size?numberBytes; if known.
duration?numberVideo duration (s); if known.

Source to process: an address or file info.

type MediaSource = string | { uri: string; name?: string | null | undefined; type?: string | null | undefined; /** Request headers for a remote address (protected files). */ headers?: Record<string, string> | undefined; }

Options of renderVideo.

Extends: Omit<MediaVideoOutput, "render">

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