Add place sharing via Web Share API and Marco link #117

Merged
raucao merged 2 commits from feature/share_button into master 2026-11-16 09:25:36 +00:00
8 changed files with 707 additions and 17 deletions

No files matched your search

+90 -11
View File
@@ -16,6 +16,15 @@ import Modal from './modal';
import PhotoCarousel from './photo-carousel';
import PhotoGallery from './photo-gallery';
import PlacePaymentMethods from './place-payment-methods';
import PlaceShareMenu from './place-share-menu';
import {
canWebShare,
canCopyText,
hasPublicPlaceId,
buildShareText,
buildCoordsText,
toAbsoluteUrl,
} from '../utils/share';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
@@ -25,8 +34,11 @@ export default class PlaceDetails extends Component {
@service nostrAuth;
@service nostrData;
@service mapUi;
@service toast;
@service router;
@tracked isEditing = false;
@tracked showLists = false;
@tracked showShareMenu = false;
@tracked isPhotoUploadActive = false;
@tracked isConnectingNostr = false;
@tracked isGalleryOpen = false;
@@ -96,6 +108,21 @@ export default class PlaceDetails extends Component {
return mapToStorageSchema(this.place);
}
get marcoUrl() {
if (!hasPublicPlaceId(this.place)) return null;
return toAbsoluteUrl(this.router.urlFor('place', this.place));
}
get shareCoordsText() {
return buildCoordsText(this.place);
}
get showShareButton() {
if (this.isEditing) return false;
if (!this.marcoUrl && !this.shareCoordsText) return false;
return canWebShare() || canCopyText();
}
get tags() {
return this.place.osmTags || {};
}
@@ -151,6 +178,47 @@ export default class PlaceDetails extends Component {
this.showLists = false;
}
@action
async share(event) {
if (event) {
event.stopPropagation();
}
// No native share sheet (e.g. Firefox desktop, Chrome on Linux):
// fall back to the copy menu instead.
if (!canWebShare()) {
this.showShareMenu = !this.showShareMenu;
return;
}
const data = {
title: this.name,
text: buildShareText(this.place, this.name),
};
if (this.marcoUrl) {
data.url = this.marcoUrl;
}
if (navigator.canShare && !navigator.canShare(data)) {
this.showShareMenu = true;
return;
}
try {
await navigator.share(data);
} catch (e) {
// AbortError means the user dismissed the sheet; stay silent.
if (e?.name !== 'AbortError') {
this.toast.show('Could not share this place');
}
}
}
@action
closeShareMenu() {
this.showShareMenu = false;
}
@action
async saveChanges(changes) {
if (this.args.onSave) {
@@ -513,22 +581,33 @@ export default class PlaceDetails extends Component {
<PlaceListsManager
@place={{this.saveablePlace}}
@onClose={{this.closeLists}}
@onEdit={{this.startEditing}}
@isSaved={{this.isSaved}}
/>
{{/if}}
</div>
{{#if this.isSaved}}
<button
type="button"
class="btn btn-outline"
title="Edit"
disabled={{this.isEditing}}
{{on "click" this.startEditing}}
>
<Icon @name="edit" @color="var(--link-color)" />
Edit
</button>
{{#if this.showShareButton}}
<div class="share-button-wrapper">
<button
type="button"
class="btn btn-outline"
aria-haspopup="menu"
aria-expanded={{if this.showShareMenu "true" "false"}}
{{on "click" this.share}}
>
<Icon @name="share" @color="var(--link-color)" />
Share
</button>
{{#if this.showShareMenu}}
<PlaceShareMenu
@url={{this.marcoUrl}}
@coordsText={{this.shareCoordsText}}
@onClose={{this.closeShareMenu}}
/>
{{/if}}
</div>
{{/if}}
</div>
+15
View File
@@ -6,6 +6,7 @@ import { on } from '@ember/modifier';
import { fn } from '@ember/helper';
import { htmlSafe } from '@ember/template';
import onClickOutside from '../modifiers/on-click-outside';
import Icon from './icon';
export default class PlaceListsManager extends Component {
@service storage;
@@ -94,6 +95,12 @@ export default class PlaceListsManager extends Component {
}
}
@action
editPlace() {
this.args.onClose?.();
this.args.onEdit?.();
}
<template>
<div class="place-lists-manager" {{onClickOutside @onClose}}>
<div class="list-item master-toggle">
@@ -130,6 +137,14 @@ export default class PlaceListsManager extends Component {
</div>
{{/each}}
</div>
{{#if this.isSaved}}
<div class="divider"></div>
<button type="button" class="edit-item" {{on "click" this.editPlace}}>
<Icon @name="edit" />
<span class="list-name">Edit saved place</span>
</button>
{{/if}}
</div>
</template>
}
+84
View File
@@ -0,0 +1,84 @@
import Component from '@glimmer/component';
import { service } from '@ember/service';
import { action } from '@ember/object';
import { on } from '@ember/modifier';
import onClickOutside from '../modifiers/on-click-outside';
import { canCopyText, copyText } from '../utils/share';
import Icon from './icon';
// Fallback share menu, shown only when the Web Share API is unavailable
// (e.g. Firefox desktop, Chrome on Linux). Each item is hidden when the
// browser can't perform it, so no dead controls are rendered.
export default class PlaceShareMenu extends Component {
@service toast;
get showCopyLink() {
return Boolean(this.args.url) && canCopyText();
}
get showCopyCoords() {
return Boolean(this.args.coordsText) && canCopyText();
}
@action
async copy(text, message) {
try {
await copyText(text);
this.toast.show(message);
} catch {
this.toast.show('Could not copy to clipboard');
}
this.args.onClose?.();
}
@action
copyLink() {
return this.copy(this.args.url, 'Link copied to clipboard');
}
@action
copyCoords() {
return this.copy(this.args.coordsText, 'Coordinates copied to clipboard');
}
@action
onKeydown(event) {
if (event.key === 'Escape') {
event.stopPropagation();
this.args.onClose?.();
}
}
<template>
<div
class="place-share-menu"
role="menu"
aria-label="Share place"
{{onClickOutside @onClose}}
>
{{#if this.showCopyLink}}
<button
type="button"
role="menuitem"
{{on "click" this.copyLink}}
{{on "keydown" this.onKeydown}}
>
<Icon @name="link" />
Copy link
</button>
{{/if}}
{{#if this.showCopyCoords}}
<button
type="button"
role="menuitem"
{{on "click" this.copyCoords}}
{{on "keydown" this.onKeydown}}
>
<Icon @name="map-pin" />
Copy coordinates
</button>
{{/if}}
</div>
</template>
}
+57
View File
@@ -1831,6 +1831,25 @@ button.create-place {
background: var(--hover-bg);
}
.place-lists-manager .edit-item {
padding: 0.5rem 1rem;
display: flex;
align-items: center;
gap: 0.75rem;
width: 100%;
background: none;
border: none;
text-align: left;
font-family: inherit;
font-size: 0.95rem;
color: var(--body-text-color);
cursor: pointer;
}
.place-lists-manager .edit-item:hover {
background: var(--hover-bg);
}
.place-lists-manager label {
display: flex;
align-items: center;
@@ -1865,6 +1884,44 @@ button.create-place {
margin: 0.5rem 0;
}
/* Place Share Menu */
.share-button-wrapper {
position: relative;
}
.place-share-menu {
position: absolute;
top: 100%;
left: 0;
margin-top: 0.5rem;
background: white;
border-radius: 8px;
box-shadow: 0 4px 12px rgb(0 0 0 / 15%);
width: 200px;
z-index: 10;
padding: 0.5rem 0;
display: flex;
flex-direction: column;
}
.place-share-menu button {
padding: 0.5rem 1rem;
display: flex;
align-items: center;
gap: 0.5rem;
width: 100%;
background: none;
border: none;
text-align: left;
font-size: 0.95rem;
color: var(--body-text-color);
cursor: pointer;
}
.place-share-menu button:hover {
background: var(--hover-bg);
}
/* Category Chips */
.category-chips-scroll {
width: 100%;
+4
View File
@@ -21,6 +21,7 @@ import heart from 'feather-icons/dist/icons/heart.svg?raw';
import home from 'feather-icons/dist/icons/home.svg?raw';
import info from 'feather-icons/dist/icons/info.svg?raw';
import instagram from 'feather-icons/dist/icons/instagram.svg?raw';
import link from 'feather-icons/dist/icons/link.svg?raw';
import logIn from 'feather-icons/dist/icons/log-in.svg?raw';
import logOut from 'feather-icons/dist/icons/log-out.svg?raw';
import mail from 'feather-icons/dist/icons/mail.svg?raw';
@@ -35,6 +36,7 @@ import plus from 'feather-icons/dist/icons/plus.svg?raw';
import search from 'feather-icons/dist/icons/search.svg?raw';
import server from 'feather-icons/dist/icons/server.svg?raw';
import settings from 'feather-icons/dist/icons/settings.svg?raw';
import share from 'feather-icons/dist/icons/share.svg?raw';
import shield from 'feather-icons/dist/icons/shield.svg?raw';
import target from 'feather-icons/dist/icons/target.svg?raw';
import trash2 from 'feather-icons/dist/icons/trash-2.svg?raw';
@@ -243,6 +245,7 @@ const ICONS = {
'info-i': infoI,
instagram,
jewel,
link,
'log-in': logIn,
'log-out': logOut,
'lowrise-building': lowriseBuilding,
@@ -288,6 +291,7 @@ const ICONS = {
search,
server,
settings,
share,
'shopping-basket': shoppingBasket,
'shopping-cart': shoppingCart,
'table-tennis-paddle': tableTennisPaddle,
+90
View File
@@ -0,0 +1,90 @@
// 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
);
}
export function canUseClipboard() {
return hasAsyncClipboard();
}
// 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}`;
}
@@ -7,6 +7,47 @@ import PlaceDetails from 'marco/components/place-details';
module('Integration | Component | place-details', function (hooks) {
setupRenderingTest(hooks);
let copiedText = null;
let originalClipboard;
let originalIsSecureContext;
function restoreProperty(target, key, descriptor) {
if (descriptor) {
Object.defineProperty(target, key, descriptor);
} else {
delete target[key];
}
}
// Opt-in stub so the Share fallback menu renders its copy items in tests.
function enableClipboard() {
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: {
writeText: async (text) => {
copiedText = text;
},
},
});
Object.defineProperty(window, 'isSecureContext', {
configurable: true,
value: true,
});
}
// Simulate a non-secure origin without the async Clipboard API, to exercise
// the legacy execCommand copy fallback.
function disableClipboard() {
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: undefined,
});
Object.defineProperty(window, 'isSecureContext', {
configurable: true,
value: false,
});
}
class StorageService extends Service {
lists = [
{ id: 'to-go', title: 'Want to go', color: '#2e9e4f' },
@@ -37,13 +78,28 @@ module('Integration | Component | place-details', function (hooks) {
hooks.beforeEach(function () {
this.owner.register('service:storage', StorageService);
copiedText = null;
originalClipboard = Object.getOwnPropertyDescriptor(navigator, 'clipboard');
originalIsSecureContext = Object.getOwnPropertyDescriptor(
window,
'isSecureContext'
);
// Mock Router for all tests
class MockRouter extends Service {
transitionTo() {}
urlFor(routeName, model) {
return `/place/osm:${model.osmType}:${model.osmId}`;
}
}
this.owner.register('service:router', MockRouter);
});
hooks.afterEach(function () {
restoreProperty(navigator, 'clipboard', originalClipboard);
restoreProperty(window, 'isSecureContext', originalIsSecureContext);
});
test('it formats coordinates correctly', async function (assert) {
const place = {
title: 'Test Place',
@@ -87,7 +143,7 @@ module('Integration | Component | place-details', function (hooks) {
// Find the Save button
// It's the first button in .actions
const saveBtn = this.element.querySelector('.actions button');
const saveBtn = this.element.querySelector('.save-button-wrapper button');
await click(saveBtn);
// Manager should be visible now
@@ -127,7 +183,7 @@ module('Integration | Component | place-details', function (hooks) {
await render(<template><PlaceDetails @place={{place}} /></template>);
// Open manager
await click('.actions button');
await click('.save-button-wrapper button');
// Find master "Saved" toggle
const masterToggle = this.element.querySelector(
@@ -170,7 +226,7 @@ module('Integration | Component | place-details', function (hooks) {
await render(<template><PlaceDetails @place={{place}} /></template>);
// Open manager
await click('.actions button');
await click('.save-button-wrapper button');
// Find master "Saved" toggle
const masterToggle = this.element.querySelector(
@@ -217,7 +273,7 @@ module('Integration | Component | place-details', function (hooks) {
await render(<template><PlaceDetails @place={{place}} /></template>);
// Open manager
await click('.actions button');
await click('.save-button-wrapper button');
// Find the checkbox for "Favorites"
const checkbox = this.element.querySelectorAll(
@@ -252,8 +308,8 @@ module('Integration | Component | place-details', function (hooks) {
await render(<template><PlaceDetails @place={{place}} /></template>);
// Button should say "Save", not "Saved" because isPlaceSaved returns false
assert.dom('.actions button').hasText('Save');
assert.dom('.actions button').doesNotHaveClass('btn-secondary');
assert.dom('.save-button-wrapper button').hasText('Save');
assert.dom('.save-button-wrapper button').doesNotHaveClass('btn-secondary');
});
test('it aggregates phone and mobile tags without duplicates', async function (assert) {
@@ -565,4 +621,189 @@ module('Integration | Component | place-details', function (hooks) {
.dom('a[href="https://www.wikidata.org/wiki/Q42"]')
.exists('Wikidata link is rendered');
});
test('it shows a Share button and fallback menu for an OSM place', async function (assert) {
enableClipboard();
const place = {
title: 'OSM Place',
osmId: '123',
osmType: 'node',
lat: 52.520006789,
lon: 13.404954123,
};
await render(<template><PlaceDetails @place={{place}} /></template>);
assert.dom('.share-button-wrapper button').exists();
assert.dom('.share-button-wrapper button').hasText(/Share/);
await click('.share-button-wrapper button');
assert.dom('.place-share-menu').exists();
assert.dom('.place-share-menu').includesText('Copy link');
assert.dom('.place-share-menu').includesText('Copy coordinates');
// A second click on the trigger closes the fallback menu again.
await click('.share-button-wrapper button');
assert.dom('.place-share-menu').doesNotExist();
});
test('it copies the public Marco URL for an OSM place', async function (assert) {
enableClipboard();
const place = {
title: 'OSM Place',
osmId: '123',
osmType: 'node',
lat: 52.52,
lon: 13.4,
};
await render(<template><PlaceDetails @place={{place}} /></template>);
await click('.share-button-wrapper button');
const linkButton = Array.from(
this.element.querySelectorAll('.place-share-menu button')
).find((el) => el.textContent.includes('Copy link'));
await click(linkButton);
assert.strictEqual(
copiedText,
`${window.location.origin}/place/osm:node:123`
);
});
test('it never copies a Marco URL for a custom place', async function (assert) {
enableClipboard();
const place = {
id: 'private-1',
title: 'My Secret Spot',
lat: 52.520006789,
lon: 13.404954123,
};
await render(<template><PlaceDetails @place={{place}} /></template>);
await click('.share-button-wrapper button');
assert.dom('.place-share-menu').exists();
assert.dom('.place-share-menu').doesNotIncludeText('Copy link');
const coordsButton = Array.from(
this.element.querySelectorAll('.place-share-menu button')
).find((el) => el.textContent.includes('Copy coordinates'));
await click(coordsButton);
assert.strictEqual(copiedText, '52.520007, 13.404954');
});
test('it hides the Share button while editing', async function (assert) {
enableClipboard();
class MockStorage extends Service {
lists = [];
isPlaceSaved() {
return true;
}
}
this.owner.register('service:storage', MockStorage);
const place = {
id: 'saved-1',
title: 'Saved Spot',
lat: 40,
lon: 40,
createdAt: '2023-01-01',
};
await render(<template><PlaceDetails @place={{place}} /></template>);
assert.dom('.share-button-wrapper').exists();
await click('.save-button-wrapper button');
await click('.place-lists-manager .edit-item');
assert.dom('.share-button-wrapper').doesNotExist();
});
test('it hides the Share button when nothing is shareable', async function (assert) {
const place = {
title: 'Nothing to share',
};
await render(<template><PlaceDetails @place={{place}} /></template>);
assert.dom('.share-button-wrapper').doesNotExist();
});
test('it still offers the Share menu without a secure context', async function (assert) {
disableClipboard();
const place = {
title: 'LAN Place',
osmId: '123',
osmType: 'node',
lat: 52.52,
lon: 13.4,
};
await render(<template><PlaceDetails @place={{place}} /></template>);
assert.dom('.share-button-wrapper button').exists();
await click('.share-button-wrapper button');
assert.dom('.place-share-menu').exists();
assert.dom('.place-share-menu').includesText('Copy link');
assert.dom('.place-share-menu').includesText('Copy coordinates');
});
test('it opens the edit form from the saved-place dropdown', async function (assert) {
class SavedStorage extends Service {
lists = [];
isPlaceSaved() {
return true;
}
}
this.owner.register('service:storage', SavedStorage);
const place = {
id: 'saved-1',
title: 'Saved Spot',
lat: 40,
lon: 40,
createdAt: '2023-01-01',
};
await render(<template><PlaceDetails @place={{place}} /></template>);
assert.dom('.place-lists-manager').doesNotExist();
assert.dom('.edit-form').doesNotExist();
await click('.save-button-wrapper button');
assert.dom('.place-lists-manager .edit-item').exists();
assert
.dom('.place-lists-manager .edit-item')
.includesText('Edit saved place');
await click('.place-lists-manager .edit-item');
assert.dom('.place-lists-manager').doesNotExist();
assert.dom('.edit-form').exists();
});
test('it does not offer the edit item for an unsaved place', async function (assert) {
const place = { title: 'New Spot', lat: 41, lon: 41 };
await render(<template><PlaceDetails @place={{place}} /></template>);
await click('.save-button-wrapper button');
assert.dom('.place-lists-manager').exists();
assert.dom('.place-lists-manager .edit-item').doesNotExist();
});
});
+120
View File
@@ -0,0 +1,120 @@
import { module, test } from 'qunit';
import {
canUseClipboard,
canCopyText,
canWebShare,
copyText,
hasPublicPlaceId,
buildCoordsText,
buildShareText,
toAbsoluteUrl,
} from 'marco/utils/share';
module('Unit | Utility | share', function () {
test('hasPublicPlaceId is only true for explicit OSM objects', function (assert) {
assert.true(hasPublicPlaceId({ osmId: '123', osmType: 'node' }));
assert.false(hasPublicPlaceId({ id: 'private-1', lat: 1, lon: 2 }));
assert.false(hasPublicPlaceId({ osmId: '123' }));
assert.false(hasPublicPlaceId({}));
});
test('buildCoordsText formats coordinates to 6 decimals', function (assert) {
assert.strictEqual(
buildCoordsText({ lat: 52.520006789, lon: 13.404954123 }),
'52.520007, 13.404954'
);
assert.strictEqual(buildCoordsText({ lat: 52.52 }), null);
assert.strictEqual(buildCoordsText({}), null);
});
test('buildShareText includes name and coordinates', function (assert) {
assert.strictEqual(
buildShareText({ lat: 52.520006789, lon: 13.404954123 }, 'Café'),
'Café\n52.520007, 13.404954'
);
});
test('buildShareText falls back to the name without coordinates', function (assert) {
assert.strictEqual(buildShareText({}, 'Name'), 'Name');
assert.strictEqual(buildShareText({}, ''), null);
});
test('buildShareText returns only coordinates when there is no name', function (assert) {
assert.strictEqual(
buildShareText({ lat: 1, lon: 2 }, ''),
'1.000000, 2.000000'
);
});
test('toAbsoluteUrl prefixes the current origin', function (assert) {
assert.strictEqual(
toAbsoluteUrl('/place/osm:node:123'),
`${window.location.origin}/place/osm:node:123`
);
});
test('capability guards return booleans without throwing', function (assert) {
assert.strictEqual(typeof canWebShare(), 'boolean');
assert.strictEqual(typeof canUseClipboard(), 'boolean');
assert.strictEqual(typeof canCopyText(), 'boolean');
});
module('copyText fallback without a secure context', function (hooks) {
let originalClipboard;
let originalIsSecureContext;
let originalExecCommand;
hooks.beforeEach(function () {
originalClipboard = Object.getOwnPropertyDescriptor(
navigator,
'clipboard'
);
originalIsSecureContext = Object.getOwnPropertyDescriptor(
window,
'isSecureContext'
);
originalExecCommand = document.execCommand;
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: undefined,
});
Object.defineProperty(window, 'isSecureContext', {
configurable: true,
value: false,
});
});
hooks.afterEach(function () {
restoreProperty(navigator, 'clipboard', originalClipboard);
restoreProperty(window, 'isSecureContext', originalIsSecureContext);
document.execCommand = originalExecCommand;
});
test('it uses document.execCommand when the async Clipboard API is missing', async function (assert) {
let usedExecCommand = false;
document.execCommand = (command) => {
usedExecCommand = command === 'copy';
return true;
};
await copyText('52.520007, 13.404954');
assert.true(usedExecCommand, 'execCommand("copy") was invoked');
});
test('it rejects when execCommand reports failure', async function (assert) {
document.execCommand = () => false;
await assert.rejects(copyText('52.520007, 13.404954'));
});
});
});
function restoreProperty(target, key, descriptor) {
if (descriptor) {
Object.defineProperty(target, key, descriptor);
} else {
delete target[key];
}
}