Files
akkounts/app/javascript/controllers/nostr_profile_editor_controller.js
raucao be133af6fa
CI / Test (pull_request) Successful in 49s
Release Drafter / Update release notes draft (pull_request) Successful in 37s
Upload avatar and header images from the Nostr profile editor
The editor gains edit affordances over the avatar and header image and an upload panel that stores the image (previewing the server-cropped result) and records it as pending. Saving the profile signs a Blossom upload token, flushes the pending images, merges the returned URLs into the kind-0 content, and keeps pending state until the publish succeeds so a retry re-flushes.
2026-11-19 21:58:12 +04:00

195 lines
5.7 KiB
JavaScript

import { Controller } from "@hotwired/stimulus"
import { signAndPublish, hasNostrExtension } from "lib/nostr_publish"
import { csrfToken } from "lib/csrf"
const PROFILE_KIND = 0
const AUTH_KIND = 24242
const TOKEN_TTL = 5 * 60
const ADDRESS_PATTERN = /^[^@\s]+@[^@\s]+\.[^@\s]+$/
const URL_PATTERN = /^https?:\/\/\S+$/i
export default class extends Controller {
static targets = [ "error", "submit", "picturePreview", "picturePlaceholder", "bannerPreview" ]
static values = {
profile: { type: Object, default: {} },
handle: String,
displayNameKeys: { type: Array, default: [ "display_name" ] },
pictureValue: { type: String, default: "" },
bannerValue: { type: String, default: "" },
flushUrl: String
}
connect () {
this.pending = {}
}
async save (event) {
event.preventDefault()
this.clearError()
const nip05 = this.field("nip05_address")
const lud16 = this.field("lud16_address")
const website = this.field("website")
if (nip05 && !ADDRESS_PATTERN.test(nip05)) {
this.showError("Please enter a valid NIP-05 address, e.g. name@example.com.")
return
}
if (lud16 && !ADDRESS_PATTERN.test(lud16)) {
this.showError("Please enter a valid Lightning address, e.g. name@example.com.")
return
}
if (website && !URL_PATTERN.test(website)) {
this.showError("Please enter a valid website URL, e.g. https://example.com.")
return
}
if (!hasNostrExtension()) {
this.showError("No Nostr extension (NIP-07) found.")
return
}
this.setBusy(true)
try {
const content = this.content()
await this.uploadPendingImages(content)
const signedEvent = await signAndPublish({
kind: PROFILE_KIND,
created_at: Math.floor(Date.now() / 1000),
tags: [],
content: JSON.stringify(content)
})
this.pending = {}
this.element.dispatchEvent(new CustomEvent("nostr:publish", {
bubbles: true,
detail: { kind: PROFILE_KIND, eventId: signedEvent.id }
}))
} catch (error) {
this.showError(error.message)
} finally {
this.setBusy(false)
}
}
setPending (field, sha256, previewUrl) {
this.pending[field] = { sha256, previewUrl }
this.showPreview(field, previewUrl)
}
showPreview (field, url) {
if (!url) return
if (field === "picture") {
if (this.hasPicturePreviewTarget) {
this.picturePreviewTarget.src = url
this.picturePreviewTarget.classList.remove("hidden")
}
if (this.hasPicturePlaceholderTarget) this.picturePlaceholderTarget.classList.add("hidden")
} else if (field === "banner") {
if (this.hasBannerPreviewTarget) {
this.bannerPreviewTarget.style.backgroundImage = `url('${url}')`
}
}
}
async uploadPendingImages (content) {
const fields = Object.keys(this.pending)
if (fields.length === 0) return
const now = Math.floor(Date.now() / 1000)
const signedEvent = await window.nostr.signEvent({
kind: AUTH_KIND,
created_at: now,
tags: [
[ "t", "upload" ],
...fields.map((field) => [ "x", this.pending[field].sha256 ]),
[ "expiration", String(now + TOKEN_TTL) ]
],
content: "Upload profile images"
})
const response = await fetch(this.flushUrlValue, {
method: "POST",
credentials: "include",
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"X-CSRF-Token": csrfToken()
},
body: JSON.stringify({ signed_event: signedEvent })
})
const data = await response.json().catch(() => ({}))
if (!response.ok) throw new Error(data.error || `Upload failed (HTTP ${response.status})`)
const uploads = data.uploads || []
const uploaded = new Set(uploads.map((upload) => upload.field))
uploads.forEach(({ field, url }) => { content[field] = url })
fields.forEach((field) => {
if (!uploaded.has(field)) throw new Error("Could not upload the image. Please try again.")
})
}
content () {
const content = { ...(this.profileValue || {}) }
const displayName = this.field("display_name")
this.displayNameKeysValue.forEach((key) => this.assign(content, key, displayName))
this.assign(content, "nip05", this.field("nip05_address"))
this.assign(content, "lud16", this.field("lud16_address"))
this.assign(content, "about", this.field("about"))
this.assign(content, "website", this.field("website"))
this.assignIfPresent(content, "picture", this.pictureValue)
this.assignIfPresent(content, "banner", this.bannerValue)
if (!content.name && this.handleValue) {
content.name = this.handleValue
}
return content
}
assign (content, key, value) {
if (value) {
content[key] = value
} else {
delete content[key]
}
}
assignIfPresent (content, key, value) {
if (value) content[key] = value
}
field (name) {
const input = this.element.querySelector(`[name='user[${name}]']`)
return input ? input.value.trim() : ""
}
setBusy (busy) {
if (!this.hasSubmitTarget) return
if (busy) {
this.submitTarget.dataset.originalValue = this.submitTarget.value
this.submitTarget.disabled = true
this.submitTarget.value = "Saving…"
} else {
this.submitTarget.disabled = false
this.submitTarget.value = this.submitTarget.dataset.originalValue || this.submitTarget.value
}
}
showError (message) {
if (!this.hasErrorTarget) return
this.errorTarget.textContent = message
this.errorTarget.classList.remove("hidden")
}
clearError () {
if (!this.hasErrorTarget) return
this.errorTarget.textContent = ""
this.errorTarget.classList.add("hidden")
}
}