Skip to content
Lucent
SEARCH LUCENT

Search guides, APIs, and examples.

GitHub

Very early and experimental. The language, the generated native code and every package API change without notice. Do not use Lucent in production.

Clipboard

expo-clipboard's text API on UIPasteboard and Android's ClipboardManager.

  • iOS: UIPasteboard.general, read and written like a property.
  • Android: ClipboardManager, called inside main() because Android lets only the focused app read the clipboard.
  • error(code, message) from lucent:core throws an error JavaScript can tell apart by its code.
clipboard.lucent.ts
import { PLATFORM } from "lucent:platform";
import { UIPasteboard } from "lucent:ios/UIKit";
import { ClipboardManager, ClipData, ClipDescription } from "lucent:android/android.content";
import { appContext } from "lucent:android";
import { main } from "lucent:thread";
import { error } from "lucent:core";
function clipboard(): ClipboardManager {
const manager = appContext().getSystemService(ClipboardManager);
if (!manager) throw error("ERR_CLIPBOARD_UNAVAILABLE", "The clipboard is not available");
return manager;
}
// Android only lets the focused app read the clipboard; its callbacks run on the main thread.
export async function getStringAsync(): Promise<string> {
if (PLATFORM === "ios") {
return UIPasteboard.general.string ?? "";
} else {
return main(() => {
const clip = clipboard().getPrimaryClip();
if (!clip || clip.getItemCount() === 0) return "";
return clip.getItemAt(0)?.coerceToText(appContext()) ?? "";
});
}
}
export async function setStringAsync(text: string): Promise<boolean> {
if (PLATFORM === "ios") {
UIPasteboard.general.string = text;
return true;
} else {
return main(() => {
const clip = ClipData.newPlainText(null, text);
if (!clip) return false;
clipboard().setPrimaryClip(clip);
return true;
});
}
}
export async function hasStringAsync(): Promise<boolean> {
if (PLATFORM === "ios") {
return UIPasteboard.general.hasStrings;
} else {
return main(
() =>
clipboard().getPrimaryClipDescription()?.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN) ??
false,
);
}
}

Source: clipboard.lucent.ts.