Files
raucao bba9a2a444
CI / Lint (pull_request) Successful in 57s
CI / Test (pull_request) Failing after 1m9s
Open Nostr event links from the search field
The full-text search field now detects anything the /e/ handler can open
(raw 64-hex ids, note1/nevent1/naddr1 codes, nostr: URIs, kind:pubkey:d
coordinates and permalinks) and opens it instead of running a Photon or
bookmark search.

As-you-type, a pasted reference resolves through the event store while the
field shows a spinner and the popover offers a single row labelled by kind
("Place photo" / "Place review", or a generic "Nostr event"). A reference
that cannot be found shows the usual not-found toast, and an unlinked event
is flagged as such. Submitting a reference, and direct /search?q=<ref>
links, route straight to the /e/ handler.
2026-11-28 19:36:02 +04:00

316 lines
10 KiB
JavaScript

import {
decodeAddressPointer,
decodeEventPointer,
} from 'applesauce-core/helpers/pointers';
import { extractMediaHashes } from './photo-tags';
export function normalizeRelayUrl(url) {
if (!url) return '';
let normalized = url.trim().toLowerCase();
if (!normalized) return '';
if (!normalized.startsWith('ws://') && !normalized.startsWith('wss://')) {
normalized = 'wss://' + normalized;
}
while (normalized.endsWith('/')) {
normalized = normalized.slice(0, -1);
}
return normalized;
}
export function uniqNormalizedRelays(relays = []) {
return Array.from(new Set(relays.map(normalizeRelayUrl).filter(Boolean)));
}
export function mergeRequiredRelays(requiredRelays = [], customRelays = []) {
const requiredSet = new Set(requiredRelays.filter(Boolean));
const merged = [...requiredRelays.filter(Boolean)];
for (const relay of uniqNormalizedRelays(customRelays)) {
if (!requiredSet.has(relay)) {
merged.push(relay);
}
}
return merged;
}
export function excludeRequiredRelays(customRelays = [], requiredRelays = []) {
const requiredSet = new Set(requiredRelays.filter(Boolean));
return uniqNormalizedRelays(customRelays).filter((relay) => {
return !requiredSet.has(relay);
});
}
/**
* Returns true if `relayUrl` matches any entry in `trustedRelays`.
*
* Comparison is performed on normalized relay URLs (lowercased, `wss://`
* scheme ensured, trailing slashes stripped) via `normalizeRelayUrl`, so
* callers may pass raw `wss://` URLs received from relays or bare hostnames.
*
* @param {string} relayUrl The relay URL a content event was seen on
* @param {Array<string>} trustedRelays List of trusted relay URLs
* @returns {boolean}
*/
export function relayUrlMatches(relayUrl, trustedRelays = []) {
if (!relayUrl) return false;
const target = normalizeRelayUrl(relayUrl);
if (!target) return false;
const trustedSet = new Set(
uniqNormalizedRelays(trustedRelays || []).filter(Boolean)
);
return trustedSet.has(target);
}
/**
* Extracts and normalizes photo data from NIP-360 (Place Photos) events.
* Sorts chronologically and guarantees the first landscape photo (or first portrait) is at index 0.
*
* @param {Array} events NIP-360 events
* @returns {Array} Array of photo objects
*/
export function parsePlacePhotos(events) {
if (!events || events.length === 0) return [];
// Sort by created_at ascending (oldest first)
const sortedEvents = [...events].sort((a, b) => a.created_at - b.created_at);
const allPhotos = [];
for (const event of sortedEvents) {
const eventTagValues = event.tags
.filter((t) => t[0] === 't')
.map((t) => t[1])
.filter(Boolean);
// Find all imeta tags
const imetas = event.tags.filter((t) => t[0] === 'imeta');
for (const imeta of imetas) {
let url = null;
let thumbUrl = null;
let blurhash = null;
let isLandscape = false;
let aspectRatio = 16 / 9; // default
let altText = null;
let placeIdentifier = event.tags.find((t) => t[0] === 'i')?.[1];
const publishedAtRaw = event.tags.find(
(t) => t[0] === 'published_at'
)?.[1];
const publishedAt = publishedAtRaw ? Number(publishedAtRaw) : null;
for (const tag of imeta.slice(1)) {
if (tag.startsWith('url ')) {
url = tag.substring(4);
} else if (tag.startsWith('thumb ')) {
thumbUrl = tag.substring(6);
} else if (tag.startsWith('blurhash ')) {
blurhash = tag.substring(9);
} else if (tag.startsWith('dim ')) {
const dimStr = tag.substring(4);
const [width, height] = dimStr.split('x').map(Number);
if (width && height) {
aspectRatio = width / height;
if (width > height) {
isLandscape = true;
}
}
} else if (tag.startsWith('alt ')) {
const alt = tag.substring(4).trim();
// Strip the legacy placeholder we used to write on every event
altText = alt === 'A photo of a place' ? null : alt || null;
}
}
if (url) {
const mediaHashes = extractMediaHashes(event, imeta);
allPhotos.push({
eventId: event.id,
pubkey: event.pubkey,
createdAt: event.created_at,
publishedAt: publishedAt && publishedAt > 0 ? publishedAt : null,
url,
thumbUrl,
blurhash,
hash: mediaHashes.primary,
hashes: mediaHashes.hashes,
isLandscape,
aspectRatio,
placeIdentifier,
tags: eventTagValues,
alt: altText,
});
}
}
}
if (allPhotos.length === 0) return [];
// Find the first landscape photo
const firstLandscapeIndex = allPhotos.findIndex((p) => p.isLandscape);
if (firstLandscapeIndex > 0) {
// Move the first landscape photo to the front
const [firstLandscape] = allPhotos.splice(firstLandscapeIndex, 1);
allPhotos.unshift(firstLandscape);
}
return allPhotos;
}
// --- NIP-19 / NIP-21 event references (the `/e/:event_id` handler) ---------
const HEX_EVENT_ID = /^[0-9a-f]{64}$/i;
const ADDRESS_COORDINATE = /^(\d+):([0-9a-f]{64}):(.*)$/i;
const PLACE_IDENTIFIER = /^osm:(node|way|relation):\d+$/;
// Addressable ranges: NIP-01 replaceable (10xxx/10002) and parameterized
// replaceable (30000-39999). Only the latter can be referenced by `naddr`.
function isAddressableKind(kind) {
return Number.isInteger(kind) && kind >= 30000 && kind < 40000;
}
function stripNostrScheme(value) {
return value.toLowerCase().startsWith('nostr:')
? value.slice('nostr:'.length)
: value;
}
// Reduces a full permalink (e.g. https://njump.me/nevent1…) to its last path
// segment; leaves bare references untouched.
function toReference(value) {
if (!/^https?:\/\//i.test(value)) return value;
try {
const segments = new URL(value).pathname.split('/').filter(Boolean);
return segments.length
? decodeURIComponent(segments[segments.length - 1])
: '';
} catch {
return '';
}
}
// 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.
*
* Accepts a raw 64-hex event id, `note1`/`nevent1`/`naddr1` NIP-19 codes
* (relay hints included), an optional `nostr:` scheme prefix (NIP-21), a raw
* `kind:pubkey:d` coordinate, or a full permalink to any of those (resolved
* via its last path segment).
*
* @param {string} input
* @returns {{id: string, relays?: string[], author?: string, kind?: number}
* | {kind: number, pubkey: string, identifier: string, relays?: string[]}
* | null} An EventPointer or AddressPointer, or `null` if unrecognized
*/
export function parseNostrEventReference(input) {
const reference = normalizeNostrReference(input);
if (!reference) return null;
if (HEX_EVENT_ID.test(reference)) {
return { id: reference.toLowerCase() };
}
const eventPointer = decodeEventPointer(reference);
if (eventPointer) return eventPointer;
const addressPointer = decodeAddressPointer(reference);
if (addressPointer && isAddressableKind(addressPointer.kind)) {
return addressPointer;
}
const coordinate = ADDRESS_COORDINATE.exec(reference);
if (coordinate) {
const kind = Number(coordinate[1]);
if (isAddressableKind(kind)) {
return {
kind,
pubkey: coordinate[2].toLowerCase(),
identifier: coordinate[3],
};
}
}
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
* element.
*
* @param {object} event A Nostr event
* @returns {string | null}
*/
export function placeIdentifierFromEvent(event) {
if (!event || !Array.isArray(event.tags)) return null;
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 };
}