UNPKG

@astro-utils/forms

Version:

Server component for Astro (call server functions from client side with validation and state management)

82 lines (81 loc) 2.64 kB
export default class FormsReact { constructor(_astro) { this._astro = _astro; this.scriptToRun = ''; this.overrideResponse = null; } redirectTimeoutSeconds(location, timeoutSec = 2) { this.scriptToRun += ` setTimeout(function() { window.location.href = new URL("${this._escapeParentheses(location)}", window.location.href).href; }, ${timeoutSec * 1000}); `.trim(); } redirect(location, status) { this.overrideResponse = new Response(null, { status: status || 302, headers: { Location: location, }, }); } updateSearchParams() { const url = new URL(this._astro.request.url, 'http://example.com'); const search = url.searchParams; const self = this; return { search, redirect(status, removeEmptyParams = true) { const copySearch = new URLSearchParams(search); if (removeEmptyParams) { for (const [key, value] of copySearch.entries()) { if (value === '' || value == null) { copySearch.delete(key); } } } const searchString = copySearch.toString(); let pathWithSearch = url.pathname.split('/').pop(); if (searchString) { pathWithSearch += '?' + searchString; } self.overrideResponse = new Response(null, { status: status || 302, headers: { Location: pathWithSearch, }, }); } }; } updateOneSearchParam(key, value, status) { const { search, redirect } = this.updateSearchParams(); if (value == null) { search.delete(key); } else { search.set(key, value); } redirect(status); } alert(message) { this.callFunction('alert', message); } console(type, ...messages) { if (!(type in console)) { throw new Error(`Invalid console type: ${type}`); } this.callFunction(`console.${type}`, ...messages); } consoleLog(...messages) { this.console('log', ...messages); } callFunction(func, ...args) { this.scriptToRun += ` ${func}(...${JSON.stringify(args)}); `.trim(); } _escapeParentheses(str) { return str.replace(/"/g, '\\"'); } }