Open Nostr event links from the search field #134
No files matched your search
@@ -8,8 +8,18 @@ import { task, timeout } from 'ember-concurrency';
|
||||
import Icon from '#components/icon';
|
||||
import humanizeOsmTag from '../helpers/humanize-osm-tag';
|
||||
import { POI_CATEGORIES } from '../utils/poi-categories';
|
||||
import {
|
||||
parseNostrEventReference,
|
||||
nostrEventRouteParam,
|
||||
nostrEventLabel,
|
||||
} from '../utils/nostr';
|
||||
import { eq, or } from 'ember-truth-helpers';
|
||||
|
||||
// Interactive, as-you-type Nostr lookup. Kept short so a pasted reference
|
||||
// either resolves quickly or the field stops spinning; a later "Enter" that
|
||||
// opens /e/ benefits from the store cache populated by this attempt.
|
||||
const NOSTR_LOOKUP_TIMEOUT_MS = 5000;
|
||||
|
||||
export default class SearchBoxComponent extends Component {
|
||||
@service photon;
|
||||
@service osm;
|
||||
@@ -17,11 +27,20 @@ export default class SearchBoxComponent extends Component {
|
||||
@service router;
|
||||
@service mapUi;
|
||||
@service map; // Assuming we might need map context, but mostly we use router
|
||||
@service nostrData;
|
||||
@service toast;
|
||||
|
||||
@tracked _internalQuery = '';
|
||||
@tracked results = [];
|
||||
@tracked isFocused = false;
|
||||
@tracked isLoading = false;
|
||||
// Separate from `isLoading` so the spinner only appears while resolving a
|
||||
// Nostr reference, leaving ordinary Photon/category/saved popover UX alone.
|
||||
@tracked isNostrLookup = false;
|
||||
|
||||
// Last completed reference lookup, used to re-apply its outcome on refocus
|
||||
// without a second network round-trip (or duplicate toast). Reset in clear().
|
||||
_lastNostrRef = null;
|
||||
|
||||
get query() {
|
||||
return this.args.query ?? this._internalQuery;
|
||||
@@ -44,6 +63,9 @@ export default class SearchBoxComponent extends Component {
|
||||
}
|
||||
|
||||
if (value.length < 2) {
|
||||
// Cancel any in-flight (e.g. Nostr) lookup so it can't pop a stale row
|
||||
// or toast over an input the user has since shortened.
|
||||
this.searchTask.cancelAll();
|
||||
this.results = [];
|
||||
return;
|
||||
}
|
||||
@@ -81,6 +103,14 @@ export default class SearchBoxComponent extends Component {
|
||||
|
||||
if (query.length < 2) return;
|
||||
|
||||
// A Nostr event reference opens the /e/ handler instead of running a
|
||||
// Photon/bookmark search.
|
||||
const routeParam = nostrEventRouteParam(query);
|
||||
if (routeParam) {
|
||||
await this.resolveNostrReference(query, routeParam);
|
||||
return;
|
||||
}
|
||||
|
||||
this.isLoading = true;
|
||||
try {
|
||||
// Use map center if available for location bias
|
||||
@@ -131,6 +161,56 @@ export default class SearchBoxComponent extends Component {
|
||||
}
|
||||
});
|
||||
|
||||
nostrResult(routeParam, event) {
|
||||
const { title, description } = nostrEventLabel(event);
|
||||
return {
|
||||
source: 'nostr',
|
||||
id: routeParam,
|
||||
icon: 'nostrich',
|
||||
title,
|
||||
description,
|
||||
};
|
||||
}
|
||||
|
||||
async resolveNostrReference(query, routeParam) {
|
||||
// Re-apply the cached outcome on refocus rather than re-running a relay
|
||||
// lookup (and re-toasting) for a reference we have already resolved.
|
||||
if (this._lastNostrRef?.param === routeParam) {
|
||||
this.results = this._lastNostrRef.result
|
||||
? [this._lastNostrRef.result]
|
||||
: [];
|
||||
return;
|
||||
}
|
||||
|
||||
this.isNostrLookup = true;
|
||||
try {
|
||||
const event = await this.nostrData.loadEventByPointer(
|
||||
parseNostrEventReference(query),
|
||||
NOSTR_LOOKUP_TIMEOUT_MS
|
||||
);
|
||||
|
||||
// The query may have changed (or been cleared) while we waited. Drop a
|
||||
// stale outcome instead of toasting or showing a row for the wrong
|
||||
// input; this also covers builds where cancellation does not interrupt
|
||||
// the awaited lookup.
|
||||
if (nostrEventRouteParam(this.query) !== routeParam) {
|
||||
return;
|
||||
}
|
||||
|
||||
const result = event ? this.nostrResult(routeParam, event) : null;
|
||||
this._lastNostrRef = { param: routeParam, result };
|
||||
|
||||
if (result) {
|
||||
this.results = [result];
|
||||
} else {
|
||||
this.results = [];
|
||||
this.toast.show('Could not find this event on any relay.');
|
||||
}
|
||||
} finally {
|
||||
this.isNostrLookup = false;
|
||||
}
|
||||
}
|
||||
|
||||
@action
|
||||
handleFocus() {
|
||||
this.isFocused = true;
|
||||
@@ -154,6 +234,16 @@ export default class SearchBoxComponent extends Component {
|
||||
event.preventDefault();
|
||||
if (!this.query) return;
|
||||
|
||||
// A Nostr event reference is opened by the /e/ route; the route reports
|
||||
// its own errors ("not found" / "not linked to a place").
|
||||
const nostrRef = nostrEventRouteParam(this.query);
|
||||
if (nostrRef) {
|
||||
this.results = [];
|
||||
this.isFocused = false;
|
||||
this.router.transitionTo('event', nostrRef);
|
||||
return;
|
||||
}
|
||||
|
||||
let queryParams = { q: this.query, selected: null, category: null };
|
||||
|
||||
if (this.mapUi.currentCenter) {
|
||||
@@ -195,6 +285,14 @@ export default class SearchBoxComponent extends Component {
|
||||
return;
|
||||
}
|
||||
|
||||
if (place.source === 'nostr') {
|
||||
// Open the /e/ handler. Intentionally skip the shared lines below so we
|
||||
// don't overwrite the input with the result label.
|
||||
this.results = [];
|
||||
this.router.transitionTo('event', place.id);
|
||||
return;
|
||||
}
|
||||
|
||||
this.query = place.title;
|
||||
if (this.args.onQueryChange) {
|
||||
this.args.onQueryChange(place.title);
|
||||
@@ -233,6 +331,7 @@ export default class SearchBoxComponent extends Component {
|
||||
this.osm.cancelAll();
|
||||
this.photon.cancelAll();
|
||||
|
||||
this._lastNostrRef = null;
|
||||
this.query = '';
|
||||
this.results = [];
|
||||
if (this.args.onQueryChange) {
|
||||
@@ -271,9 +370,10 @@ export default class SearchBoxComponent extends Component {
|
||||
(eq this.mapUi.loadingState.type "text")
|
||||
(eq this.mapUi.loadingState.type "category")
|
||||
(eq this.mapUi.loadingState.type "nearby")
|
||||
this.isNostrLookup
|
||||
)
|
||||
}}
|
||||
<Icon @name="loading-ring" @size={{20}} />
|
||||
<Icon @name="loading-ring" @size={{20}} class="search-spinner" />
|
||||
{{else}}
|
||||
<Icon @name="search" @size={{20}} @color="#5f6368" />
|
||||
{{/if}}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { service } from '@ember/service';
|
||||
import { task } from 'ember-concurrency';
|
||||
import { getDistance } from '../utils/geo';
|
||||
import { NEARBY_CATEGORY } from '../utils/poi-categories';
|
||||
import { nostrEventRouteParam } from '../utils/nostr';
|
||||
|
||||
export default class SearchController extends Controller {
|
||||
@service osm;
|
||||
@@ -55,6 +56,16 @@ export default class SearchController extends Controller {
|
||||
}
|
||||
|
||||
fetchResultsTask = task({ restartable: true }, async (params) => {
|
||||
// A Nostr event reference (typed into the search field or reached via a
|
||||
// direct /search?q=<ref> link) is handled by the /e/ route, never by a
|
||||
// Photon/bookmark search. Do this before any sidebar or loading state is
|
||||
// touched so references never flash search UI.
|
||||
const nostrRef = params.q ? nostrEventRouteParam(params.q) : null;
|
||||
if (nostrRef) {
|
||||
this.router.replaceWith('event', nostrRef);
|
||||
return;
|
||||
}
|
||||
|
||||
// 1. Check if the incoming parameters match our currently loaded search
|
||||
const isSameSearch =
|
||||
this.mapUi.currentSearch &&
|
||||
|
||||
+64
-6
@@ -193,6 +193,17 @@ function toReference(value) {
|
||||
}
|
||||
}
|
||||
|
||||
// Normalizes a user-supplied reference to its bare, single-segment form: drops
|
||||
// an optional `nostr:` scheme and reduces a permalink to its last path segment.
|
||||
// Returns an empty string for anything that isn't a usable string. Shared by
|
||||
// `parseNostrEventReference` and `nostrEventRouteParam` so both agree on what
|
||||
// counts as a reference.
|
||||
function normalizeNostrReference(input) {
|
||||
if (typeof input !== 'string') return '';
|
||||
const candidate = toReference(stripNostrScheme(input.trim()));
|
||||
return candidate ? stripNostrScheme(candidate) : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a user-supplied event reference into an Applesauce pointer that
|
||||
* `EventStore.event()` / the event loader can resolve.
|
||||
@@ -208,12 +219,8 @@ function toReference(value) {
|
||||
* | null} An EventPointer or AddressPointer, or `null` if unrecognized
|
||||
*/
|
||||
export function parseNostrEventReference(input) {
|
||||
if (typeof input !== 'string') return null;
|
||||
|
||||
const candidate = toReference(stripNostrScheme(input.trim()));
|
||||
if (!candidate) return null;
|
||||
|
||||
const reference = stripNostrScheme(candidate);
|
||||
const reference = normalizeNostrReference(input);
|
||||
if (!reference) return null;
|
||||
|
||||
if (HEX_EVENT_ID.test(reference)) {
|
||||
return { id: reference.toLowerCase() };
|
||||
@@ -242,6 +249,21 @@ export function parseNostrEventReference(input) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the single, URL-safe reference suitable for the `/e/:event_id`
|
||||
* route when `input` is a Nostr event reference Marco can open, or `null`
|
||||
* otherwise. Unlike `parseNostrEventReference`, a pasted `nostr:` prefix or
|
||||
* full permalink is reduced to its bare path segment so it can be used
|
||||
* directly as a router dynamic segment.
|
||||
*
|
||||
* @param {string} input
|
||||
* @returns {string | null}
|
||||
*/
|
||||
export function nostrEventRouteParam(input) {
|
||||
const reference = normalizeNostrReference(input);
|
||||
return reference && parseNostrEventReference(reference) ? reference : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the place identifier (e.g. `osm:node:123`) from a place photo or
|
||||
* review event's `i` tag, or `null` when the event is not linked to an OSM
|
||||
@@ -255,3 +277,39 @@ export function placeIdentifierFromEvent(event) {
|
||||
const value = event.tags.find((tag) => tag[0] === 'i')?.[1];
|
||||
return value && PLACE_IDENTIFIER.test(value) ? value : null;
|
||||
}
|
||||
|
||||
// Event-kind labels for the search field's "Open …" row. Kept here so the
|
||||
// (kind + place-link) rules are testable independently of the component.
|
||||
export const NOSTR_PLACE_PHOTO_KIND = 360;
|
||||
export const NOSTR_PLACE_REVIEW_KIND = 30360;
|
||||
|
||||
/**
|
||||
* Builds the title/description for the search field's result row of a resolved
|
||||
* Nostr event, reflecting what kind of event it is and whether it is linked to
|
||||
* a place.
|
||||
*
|
||||
* @param {object} event A resolved Nostr event
|
||||
* @returns {{title: string, description: string}}
|
||||
*/
|
||||
export function nostrEventLabel(event) {
|
||||
const kind = event?.kind;
|
||||
let title = 'Nostr event';
|
||||
if (kind === NOSTR_PLACE_PHOTO_KIND) {
|
||||
title = 'Place photo';
|
||||
} else if (kind === NOSTR_PLACE_REVIEW_KIND) {
|
||||
title = 'Place review';
|
||||
}
|
||||
|
||||
let description;
|
||||
if (!placeIdentifierFromEvent(event)) {
|
||||
description = 'Not linked to a place';
|
||||
} else if (kind === NOSTR_PLACE_PHOTO_KIND) {
|
||||
description = 'Opens the linked place and photo';
|
||||
} else if (kind === NOSTR_PLACE_REVIEW_KIND) {
|
||||
description = 'Opens the linked place and review';
|
||||
} else {
|
||||
description = 'Opens the linked place';
|
||||
}
|
||||
|
||||
return { title, description };
|
||||
}
|
||||
@@ -1,7 +1,17 @@
|
||||
import { module, test } from 'qunit';
|
||||
import { visit, currentURL, click } from '@ember/test-helpers';
|
||||
import {
|
||||
visit,
|
||||
currentURL,
|
||||
click,
|
||||
waitFor,
|
||||
waitUntil,
|
||||
} from '@ember/test-helpers';
|
||||
import { setupApplicationTest } from 'marco/tests/helpers';
|
||||
import Service from '@ember/service';
|
||||
import { MockNostrDataService } from 'marco/tests/helpers/mock-nostr';
|
||||
|
||||
const NOSTR_EVENT_ID =
|
||||
'1f79058c77a224e5be226c8f024cacdad4d741855d75ed9f11473ba8eb86e1cb';
|
||||
|
||||
module('Acceptance | search', function (hooks) {
|
||||
setupApplicationTest(hooks);
|
||||
@@ -452,4 +462,122 @@ module('Acceptance | search', function (hooks) {
|
||||
assert.strictEqual(currentURL(), '/', 'Dismissing nearby clears the route');
|
||||
assert.strictEqual(mapUi.searchResults.length, 0, 'Results are cleared');
|
||||
});
|
||||
|
||||
test('a /search?q=<hex> link opens the linked place via the /e/ handler', async function (assert) {
|
||||
class StubNostrDataService extends MockNostrDataService {
|
||||
async loadEventByPointer() {
|
||||
return { id: NOSTR_EVENT_ID, kind: 360, tags: [['i', 'osm:node:123']] };
|
||||
}
|
||||
}
|
||||
this.owner.register('service:nostr-data', StubNostrDataService);
|
||||
|
||||
class MockOsmService extends Service {
|
||||
async fetchOsmObject(id, type) {
|
||||
return {
|
||||
osmId: id,
|
||||
osmType: type,
|
||||
lat: 1,
|
||||
lon: 1,
|
||||
osmTags: { name: 'Test Place' },
|
||||
title: 'Test Place',
|
||||
};
|
||||
}
|
||||
}
|
||||
this.owner.register('service:osm', MockOsmService);
|
||||
|
||||
class MockStorageService extends Service {
|
||||
initialSyncDone = true;
|
||||
savedPlaces = [];
|
||||
findPlaceById() {
|
||||
return null;
|
||||
}
|
||||
isPlaceSaved() {
|
||||
return false;
|
||||
}
|
||||
loadPlacesInBounds() {
|
||||
return [];
|
||||
}
|
||||
get placesInView() {
|
||||
return [];
|
||||
}
|
||||
rs = { on: () => {} };
|
||||
}
|
||||
this.owner.register('service:storage', MockStorageService);
|
||||
|
||||
let photonCalled = false;
|
||||
class MockPhotonService extends Service {
|
||||
async search() {
|
||||
photonCalled = true;
|
||||
return [];
|
||||
}
|
||||
}
|
||||
this.owner.register('service:photon', MockPhotonService);
|
||||
|
||||
try {
|
||||
await visit(`/search?q=${NOSTR_EVENT_ID}`);
|
||||
} catch {
|
||||
// The /search transition is aborted by the redirect to /e/; expected.
|
||||
}
|
||||
|
||||
await waitUntil(
|
||||
() => currentURL() === `/place/osm:node:123?photo=${NOSTR_EVENT_ID}`,
|
||||
{ timeout: 5000 }
|
||||
);
|
||||
|
||||
assert.strictEqual(
|
||||
currentURL(),
|
||||
`/place/osm:node:123?photo=${NOSTR_EVENT_ID}`,
|
||||
'ends on the place with the focused photo'
|
||||
);
|
||||
assert.false(photonCalled, 'Photon was never called for a reference');
|
||||
});
|
||||
|
||||
test('a /search?q=<hex> link to an unknown event returns to the map with a toast', async function (assert) {
|
||||
class StubNostrDataService extends MockNostrDataService {
|
||||
async loadEventByPointer() {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
this.owner.register('service:nostr-data', StubNostrDataService);
|
||||
|
||||
class MockStorageService extends Service {
|
||||
initialSyncDone = true;
|
||||
savedPlaces = [];
|
||||
findPlaceById() {
|
||||
return null;
|
||||
}
|
||||
isPlaceSaved() {
|
||||
return false;
|
||||
}
|
||||
loadPlacesInBounds() {
|
||||
return [];
|
||||
}
|
||||
get placesInView() {
|
||||
return [];
|
||||
}
|
||||
rs = { on: () => {} };
|
||||
}
|
||||
this.owner.register('service:storage', MockStorageService);
|
||||
|
||||
let photonCalled = false;
|
||||
class MockPhotonService extends Service {
|
||||
async search() {
|
||||
photonCalled = true;
|
||||
return [];
|
||||
}
|
||||
}
|
||||
this.owner.register('service:photon', MockPhotonService);
|
||||
|
||||
try {
|
||||
await visit(`/search?q=${NOSTR_EVENT_ID}`);
|
||||
} catch {
|
||||
// The /search transition is aborted by the redirect to /e/; expected.
|
||||
}
|
||||
|
||||
await waitUntil(() => currentURL() === '/', { timeout: 5000 });
|
||||
assert.strictEqual(currentURL(), '/', 'returns to the map');
|
||||
await waitFor('.toast-notification', { timeout: 5000 });
|
||||
assert.dom('.toast-notification').exists('a toast reports the failure');
|
||||
assert.false(photonCalled, 'Photon was never called for a reference');
|
||||
});
|
||||
});
|
||||
@@ -108,6 +108,10 @@ export class MockNostrDataService extends Service {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
loadEventByPointer() {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
|
||||
loadPlacePhotos() {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
@@ -1,9 +1,20 @@
|
||||
import { module, test } from 'qunit';
|
||||
import { setupRenderingTest } from 'marco/tests/helpers';
|
||||
import { render, fillIn, click, waitFor, focus } from '@ember/test-helpers';
|
||||
import {
|
||||
render,
|
||||
fillIn,
|
||||
click,
|
||||
waitFor,
|
||||
focus,
|
||||
blur,
|
||||
waitUntil,
|
||||
} from '@ember/test-helpers';
|
||||
import SearchBox from 'marco/components/search-box';
|
||||
import Service from '@ember/service';
|
||||
|
||||
const NOSTR_EVENT_ID =
|
||||
'1f79058c77a224e5be226c8f024cacdad4d741855d75ed9f11473ba8eb86e1cb';
|
||||
|
||||
module('Integration | Component | search-box', function (hooks) {
|
||||
setupRenderingTest(hooks);
|
||||
|
||||
@@ -506,4 +517,274 @@ module('Integration | Component | search-box', function (hooks) {
|
||||
// Verify it navigated using the internal ID, NOT a search query
|
||||
assert.verifySteps(['transitionTo: place ["custom-1234"]']);
|
||||
});
|
||||
|
||||
test('it resolves a Nostr reference inline and opens it on click', async function (assert) {
|
||||
let resolveLookup;
|
||||
let loadedPointer;
|
||||
|
||||
class MockNostrDataService extends Service {
|
||||
loadEventByPointer(pointer) {
|
||||
loadedPointer = pointer;
|
||||
return new Promise((resolve) => {
|
||||
resolveLookup = resolve;
|
||||
});
|
||||
}
|
||||
}
|
||||
this.owner.register('service:nostr-data', MockNostrDataService);
|
||||
|
||||
let photonCalled = false;
|
||||
class MockPhotonService extends Service {
|
||||
async search() {
|
||||
photonCalled = true;
|
||||
return [];
|
||||
}
|
||||
}
|
||||
this.owner.register('service:photon', MockPhotonService);
|
||||
|
||||
class MockRouterService extends Service {
|
||||
transitionTo(routeName, ...args) {
|
||||
assert.step(`transitionTo: ${routeName} ${JSON.stringify(args)}`);
|
||||
}
|
||||
}
|
||||
this.owner.register('service:router', MockRouterService);
|
||||
|
||||
this.noop = () => {};
|
||||
await render(
|
||||
<template><SearchBox @onToggleMenu={{this.noop}} /></template>
|
||||
);
|
||||
|
||||
await fillIn('.search-input', NOSTR_EVENT_ID);
|
||||
|
||||
// The spinner appears while the event is being resolved.
|
||||
await waitFor('.search-spinner', { timeout: 2000 });
|
||||
assert.dom('.search-spinner').exists('shows a spinner while resolving');
|
||||
|
||||
resolveLookup({
|
||||
id: NOSTR_EVENT_ID,
|
||||
kind: 360,
|
||||
tags: [['i', 'osm:node:123']],
|
||||
});
|
||||
await waitFor('.search-result-item', { timeout: 2000 });
|
||||
|
||||
assert.deepEqual(
|
||||
loadedPointer,
|
||||
{ id: NOSTR_EVENT_ID },
|
||||
'resolves the parsed event pointer'
|
||||
);
|
||||
assert.dom('.search-result-item').exists({ count: 1 });
|
||||
assert.dom('.result-title').hasText('Place photo');
|
||||
assert.dom('.result-desc').hasText('Opens the linked place and photo');
|
||||
assert.false(photonCalled, 'Photon is not called for a reference');
|
||||
|
||||
await click('.search-result-item');
|
||||
|
||||
assert.verifySteps([`transitionTo: event ["${NOSTR_EVENT_ID}"]`]);
|
||||
});
|
||||
|
||||
test('it labels a place review and an unlinked event by kind', async function (assert) {
|
||||
const eventsByQuery = {};
|
||||
const reviewId = `${'a'.repeat(63)}b`;
|
||||
const noteId = `${'c'.repeat(63)}d`;
|
||||
|
||||
class MockNostrDataService extends Service {
|
||||
async loadEventByPointer(pointer) {
|
||||
return eventsByQuery[pointer.id];
|
||||
}
|
||||
}
|
||||
this.owner.register('service:nostr-data', MockNostrDataService);
|
||||
|
||||
class MockPhotonService extends Service {
|
||||
async search() {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
this.owner.register('service:photon', MockPhotonService);
|
||||
|
||||
this.noop = () => {};
|
||||
await render(
|
||||
<template><SearchBox @onToggleMenu={{this.noop}} /></template>
|
||||
);
|
||||
|
||||
// Kind 30360 (place review) linked to a place.
|
||||
eventsByQuery[reviewId] = {
|
||||
id: reviewId,
|
||||
kind: 30360,
|
||||
tags: [['i', 'osm:way:9']],
|
||||
};
|
||||
await fillIn('.search-input', reviewId);
|
||||
await waitFor('.search-result-item', { timeout: 2000 });
|
||||
assert.dom('.result-title').hasText('Place review');
|
||||
assert.dom('.result-desc').hasText('Opens the linked place and review');
|
||||
|
||||
// Kind 1 (a plain note) with no place link. Clear first so the previous
|
||||
// row is gone before we wait for the new one.
|
||||
eventsByQuery[noteId] = { id: noteId, kind: 1, tags: [] };
|
||||
await fillIn('.search-input', '');
|
||||
await fillIn('.search-input', noteId);
|
||||
await waitFor('.search-result-item', { timeout: 2000 });
|
||||
assert.dom('.result-title').hasText('Nostr event');
|
||||
assert.dom('.result-desc').hasText('Not linked to a place');
|
||||
});
|
||||
|
||||
test('it toasts and shows no results when a Nostr reference is not found', async function (assert) {
|
||||
class MockNostrDataService extends Service {
|
||||
async loadEventByPointer() {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
this.owner.register('service:nostr-data', MockNostrDataService);
|
||||
|
||||
let toastMessage;
|
||||
class MockToastService extends Service {
|
||||
show(message) {
|
||||
toastMessage = message;
|
||||
}
|
||||
}
|
||||
this.owner.register('service:toast', MockToastService);
|
||||
|
||||
let photonCalled = false;
|
||||
class MockPhotonService extends Service {
|
||||
async search() {
|
||||
photonCalled = true;
|
||||
return [];
|
||||
}
|
||||
}
|
||||
this.owner.register('service:photon', MockPhotonService);
|
||||
|
||||
this.noop = () => {};
|
||||
await render(
|
||||
<template><SearchBox @onToggleMenu={{this.noop}} /></template>
|
||||
);
|
||||
|
||||
await fillIn('.search-input', NOSTR_EVENT_ID);
|
||||
await waitUntil(() => toastMessage !== undefined, { timeout: 3000 });
|
||||
|
||||
assert.strictEqual(toastMessage, 'Could not find this event on any relay.');
|
||||
assert.dom('.search-result-item').doesNotExist('no results are shown');
|
||||
assert.false(photonCalled, 'Photon is not called for a reference');
|
||||
});
|
||||
|
||||
test('it opens a Nostr reference on submit without a search', async function (assert) {
|
||||
class MockNostrDataService extends Service {
|
||||
async loadEventByPointer() {
|
||||
return { id: NOSTR_EVENT_ID, tags: [['i', 'osm:node:123']] };
|
||||
}
|
||||
}
|
||||
this.owner.register('service:nostr-data', MockNostrDataService);
|
||||
|
||||
let photonCalled = false;
|
||||
class MockPhotonService extends Service {
|
||||
async search() {
|
||||
photonCalled = true;
|
||||
return [];
|
||||
}
|
||||
}
|
||||
this.owner.register('service:photon', MockPhotonService);
|
||||
|
||||
class MockRouterService extends Service {
|
||||
transitionTo(routeName, ...args) {
|
||||
assert.step(`transitionTo: ${routeName} ${JSON.stringify(args)}`);
|
||||
}
|
||||
}
|
||||
this.owner.register('service:router', MockRouterService);
|
||||
|
||||
this.noop = () => {};
|
||||
await render(
|
||||
<template><SearchBox @onToggleMenu={{this.noop}} /></template>
|
||||
);
|
||||
|
||||
await fillIn('.search-input', NOSTR_EVENT_ID);
|
||||
await this.element
|
||||
.querySelector('form')
|
||||
.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
|
||||
|
||||
assert.verifySteps([`transitionTo: event ["${NOSTR_EVENT_ID}"]`]);
|
||||
assert.false(photonCalled, 'Photon is not called for a reference');
|
||||
});
|
||||
|
||||
test('it does not re-query an unresolved reference on refocus', async function (assert) {
|
||||
let loadCalls = 0;
|
||||
class MockNostrDataService extends Service {
|
||||
async loadEventByPointer() {
|
||||
loadCalls++;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
this.owner.register('service:nostr-data', MockNostrDataService);
|
||||
|
||||
class MockPhotonService extends Service {
|
||||
async search() {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
this.owner.register('service:photon', MockPhotonService);
|
||||
|
||||
class MockRouterService extends Service {
|
||||
transitionTo() {}
|
||||
}
|
||||
this.owner.register('service:router', MockRouterService);
|
||||
|
||||
this.noop = () => {};
|
||||
await render(
|
||||
<template><SearchBox @onToggleMenu={{this.noop}} /></template>
|
||||
);
|
||||
|
||||
await fillIn('.search-input', NOSTR_EVENT_ID);
|
||||
await waitUntil(() => loadCalls === 1, { timeout: 3000 });
|
||||
assert.strictEqual(loadCalls, 1, 'resolved once');
|
||||
|
||||
// Refocus the empty field: handleFocus retries, but the cached outcome is
|
||||
// re-applied instead of hitting the relays again.
|
||||
await blur('.search-input');
|
||||
await focus('.search-input');
|
||||
await new Promise((resolve) => setTimeout(resolve, 400));
|
||||
|
||||
assert.strictEqual(loadCalls, 1, 'no second lookup on refocus');
|
||||
});
|
||||
|
||||
test('it cancels an in-flight reference lookup when the query is shortened', async function (assert) {
|
||||
let toastMessage;
|
||||
let releaseLookup;
|
||||
class MockNostrDataService extends Service {
|
||||
loadEventByPointer() {
|
||||
// Hold the lookup open until the test releases it, so it is always
|
||||
// still pending when the query is shortened (no timing race).
|
||||
return new Promise((resolve) => {
|
||||
releaseLookup = () => resolve(null);
|
||||
});
|
||||
}
|
||||
}
|
||||
this.owner.register('service:nostr-data', MockNostrDataService);
|
||||
|
||||
class MockToastService extends Service {
|
||||
show(message) {
|
||||
toastMessage = message;
|
||||
}
|
||||
}
|
||||
this.owner.register('service:toast', MockToastService);
|
||||
|
||||
class MockPhotonService extends Service {
|
||||
async search() {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
this.owner.register('service:photon', MockPhotonService);
|
||||
|
||||
this.noop = () => {};
|
||||
await render(
|
||||
<template><SearchBox @onToggleMenu={{this.noop}} /></template>
|
||||
);
|
||||
|
||||
await fillIn('.search-input', NOSTR_EVENT_ID);
|
||||
await waitFor('.search-spinner', { timeout: 2000 });
|
||||
|
||||
// Shorten below the 2-character threshold while the lookup is pending,
|
||||
// then let the (now stale) lookup resolve.
|
||||
await fillIn('.search-input', 'n');
|
||||
releaseLookup();
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
|
||||
assert.notOk(toastMessage, 'the cancelled lookup never toasts');
|
||||
assert.dom('.search-result-item').doesNotExist();
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,8 @@ import {
|
||||
excludeRequiredRelays,
|
||||
mergeRequiredRelays,
|
||||
normalizeRelayUrl,
|
||||
nostrEventLabel,
|
||||
nostrEventRouteParam,
|
||||
parseNostrEventReference,
|
||||
parsePlacePhotos,
|
||||
placeIdentifierFromEvent,
|
||||
@@ -513,6 +515,76 @@ module('Unit | Utility | nostr', function () {
|
||||
null
|
||||
);
|
||||
});
|
||||
|
||||
test('rejects profile identifiers (npub/nprofile)', function (assert) {
|
||||
// Only event references are openable by the /e/ handler; profiles are
|
||||
// intentionally out of scope and must fall through to a normal search.
|
||||
assert.strictEqual(
|
||||
parseNostrEventReference(
|
||||
'npub1raustrrh5gjwt03zdj8syn9vmt2dwsv9t467m8c3gua636uxu89svgdees'
|
||||
),
|
||||
null
|
||||
);
|
||||
assert.strictEqual(
|
||||
parseNostrEventReference(
|
||||
'nprofile1qqsp77g933m6yf89hc3xerczfjkd44xhgxz46a0dnug5wwagawrwrjc267jp9'
|
||||
),
|
||||
null
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
module('nostrEventRouteParam', function () {
|
||||
const EVENT_ID =
|
||||
'1f79058c77a224e5be226c8f024cacdad4d741855d75ed9f11473ba8eb86e1cb';
|
||||
const NOTE =
|
||||
'note1raustrrh5gjwt03zdj8syn9vmt2dwsv9t467m8c3gua636uxu89sazwyqc';
|
||||
const NEVENT =
|
||||
'nevent1qvzqqqqpdqpzq8meqkx80g3yuklzymy0qfx2ekk56aqc2ht4ak03z3em4r4cdcwtqyfhwumn8ghj7un9d3shjtn90psk6urvv5qzq8meqkx80g3yuklzymy0qfx2ekk56aqc2ht4ak03z3em4r4cdcwtzltwfa';
|
||||
|
||||
test('returns a bare reference unchanged', function (assert) {
|
||||
assert.strictEqual(nostrEventRouteParam(EVENT_ID), EVENT_ID);
|
||||
assert.strictEqual(nostrEventRouteParam(NOTE), NOTE);
|
||||
assert.strictEqual(nostrEventRouteParam(NEVENT), NEVENT);
|
||||
});
|
||||
|
||||
test('strips a nostr: scheme prefix', function (assert) {
|
||||
assert.strictEqual(nostrEventRouteParam(`nostr:${NOTE}`), NOTE);
|
||||
assert.strictEqual(nostrEventRouteParam(`NOSTR:${NOTE}`), NOTE);
|
||||
});
|
||||
|
||||
test('reduces a permalink to its last path segment', function (assert) {
|
||||
assert.strictEqual(
|
||||
nostrEventRouteParam(`https://njump.me/${NEVENT}`),
|
||||
NEVENT
|
||||
);
|
||||
assert.strictEqual(
|
||||
nostrEventRouteParam(`https://primal.net/e/${EVENT_ID}`),
|
||||
EVENT_ID
|
||||
);
|
||||
});
|
||||
|
||||
test('passes a raw address coordinate through as one segment', function (assert) {
|
||||
const coordinate = `30360:${EVENT_ID}:osm:node:123`;
|
||||
assert.strictEqual(nostrEventRouteParam(coordinate), coordinate);
|
||||
|
||||
// Identifiers may themselves contain colons, slashes and spaces and must
|
||||
// survive as a single dynamic segment.
|
||||
const messy = `30360:${EVENT_ID}:some/id with:colons`;
|
||||
assert.strictEqual(nostrEventRouteParam(messy), messy);
|
||||
});
|
||||
|
||||
test('returns null for anything not openable by /e/', function (assert) {
|
||||
assert.strictEqual(nostrEventRouteParam('Berlin'), null);
|
||||
assert.strictEqual(nostrEventRouteParam(''), null);
|
||||
assert.strictEqual(nostrEventRouteParam(null), null);
|
||||
assert.strictEqual(
|
||||
nostrEventRouteParam(
|
||||
'npub1raustrrh5gjwt03zdj8syn9vmt2dwsv9t467m8c3gua636uxu89svgdees'
|
||||
),
|
||||
null
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
module('placeIdentifierFromEvent', function () {
|
||||
@@ -546,4 +618,44 @@ module('Unit | Utility | nostr', function () {
|
||||
assert.strictEqual(placeIdentifierFromEvent({}), null);
|
||||
});
|
||||
});
|
||||
|
||||
module('nostrEventLabel', function () {
|
||||
test('labels a linked place photo', function (assert) {
|
||||
assert.deepEqual(
|
||||
nostrEventLabel({ kind: 360, tags: [['i', 'osm:node:123']] }),
|
||||
{
|
||||
title: 'Place photo',
|
||||
description: 'Opens the linked place and photo',
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
test('labels a linked place review', function (assert) {
|
||||
assert.deepEqual(
|
||||
nostrEventLabel({ kind: 30360, tags: [['i', 'osm:way:9']] }),
|
||||
{
|
||||
title: 'Place review',
|
||||
description: 'Opens the linked place and review',
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
test('keeps the kind title but flags an unlinked event', function (assert) {
|
||||
assert.deepEqual(nostrEventLabel({ kind: 360, tags: [] }), {
|
||||
title: 'Place photo',
|
||||
description: 'Not linked to a place',
|
||||
});
|
||||
});
|
||||
|
||||
test('falls back to a generic label for other kinds', function (assert) {
|
||||
assert.deepEqual(
|
||||
nostrEventLabel({ kind: 1, tags: [['i', 'osm:node:123']] }),
|
||||
{ title: 'Nostr event', description: 'Opens the linked place' }
|
||||
);
|
||||
assert.deepEqual(nostrEventLabel(null), {
|
||||
title: 'Nostr event',
|
||||
description: 'Not linked to a place',
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user