Files
raucao 543d810ab2
CI / Lint (pull_request) Successful in 55s
CI / Test (pull_request) Successful in 1m22s
Release Drafter / Update release notes draft (pull_request) Successful in 15s
Remove the unused canUseClipboard helper
canCopyText covers the same capability checks and is the one the app actually uses.
2026-11-29 17:31:45 +04:00

87 lines
2.5 KiB
JavaScript

// Helpers for sharing a place. All guards are SSR/test safe: nothing here
// touches `navigator`/`window` without a `typeof` check first.
export function canWebShare() {
return (
typeof navigator !== 'undefined' &&
typeof navigator.share === 'function' &&
typeof window !== 'undefined' &&
window.isSecureContext
);
}
function hasAsyncClipboard() {
return (
typeof navigator !== 'undefined' &&
typeof navigator.clipboard?.writeText === 'function' &&
typeof window !== 'undefined' &&
window.isSecureContext
);
}
// True when text can be copied one way or another. Falls back to the legacy
// `document.execCommand('copy')` path, which also works on non-secure origins
// (e.g. a LAN dev server over plain http) where the async Clipboard API is
// unavailable.
export function canCopyText() {
if (hasAsyncClipboard()) return true;
return (
typeof document !== 'undefined' &&
typeof document.execCommand === 'function'
);
}
export async function copyText(text) {
if (hasAsyncClipboard()) {
await navigator.clipboard.writeText(text);
return;
}
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.setAttribute('readonly', '');
textarea.style.position = 'fixed';
textarea.style.top = '0';
textarea.style.left = '0';
textarea.style.opacity = '0';
document.body.appendChild(textarea);
textarea.select();
let succeeded;
try {
succeeded = document.execCommand('copy');
} finally {
textarea.remove();
}
if (!succeeded) {
throw new Error('Clipboard copy failed');
}
}
// A Marco `/place/:id` URL only resolves publicly for explicit OSM objects.
// Custom places are private RemoteStorage data keyed by an internal id that
// means nothing to anybody else.
export function hasPublicPlaceId(place = {}) {
return Boolean(place.osmId && place.osmType);
}
export function buildCoordsText(place = {}) {
const { lat, lon } = place;
if (lat == null || lon == null) return null;
return `${Number(lat).toFixed(6)}, ${Number(lon).toFixed(6)}`;
}
// Name plus coordinates, so the coordinates survive into any share target even
// when the Marco URL renders as bare text there.
export function buildShareText(place = {}, name = '') {
const coords = buildCoordsText(place);
if (!coords) return name || null;
return name ? `${name}\n${coords}` : coords;
}
export function toAbsoluteUrl(path) {
if (typeof window === 'undefined') return path;
return `${window.location.origin}${path}`;
}