import React, { CSSProperties } from 'react'; import { useNode, UserComponent } from '@craftjs/core'; import { cssPropsToString } from '../../utils/style-helpers'; import { escapeHtml, escapeAttr, safeUrl } from '../../utils/escape'; interface SearchBarProps { placeholder?: string; buttonText?: string; showButton?: boolean; /** Where the search GET request is submitted -- a real search-results page * if the site has one, or '/' (site root) by default. The query is sent * as `?q=...`, the conventional param name search-results pages look for. */ action?: string; style?: CSSProperties; animation?: string; animationDelay?: string; hideOnDesktop?: boolean; hideOnTablet?: boolean; hideOnMobile?: boolean; } export const SearchBar: UserComponent = ({ placeholder = 'Search...', buttonText = 'Search', showButton = true, action = '/', style = {}, }) => { const { connectors: { connect, drag }, selected, } = useNode((node) => ({ selected: node.events.selected, })); return (
{ if (ref) connect(drag(ref)); }} role="search" action={action} method="GET" onSubmit={(e) => e.preventDefault()} style={{ display: 'flex', alignItems: 'center', maxWidth: '560px', outline: selected ? '2px solid #3b82f6' : 'none', ...style, }} >
{showButton && ( )} ); }; /* ---------- Craft config ---------- */ SearchBar.craft = { displayName: 'Search Bar', props: { placeholder: 'Search...', buttonText: 'Search', showButton: true, action: '/', style: {}, animation: '', animationDelay: '', hideOnDesktop: false, hideOnTablet: false, hideOnMobile: false, }, rules: { canDrag: () => true, canMoveIn: () => false, canMoveOut: () => true, }, }; /* ---------- HTML export ---------- */ (SearchBar as any).toHtml = (props: SearchBarProps, _childrenHtml: string) => { const { placeholder = 'Search...', buttonText = 'Search', showButton = true, action = '/', style = {}, } = props; const formStyle = cssPropsToString({ display: 'flex', alignItems: 'center', maxWidth: '560px', ...style, }); const inputStyleStr = `width:100%;padding:12px 16px 12px 40px;font-size:15px;font-family:Inter,sans-serif;border:1px solid #d1d5db;border-radius:${showButton ? '8px 0 0 8px' : '8px'};background-color:#ffffff;color:#1f2937;outline:none;box-sizing:border-box`; const btnHtml = showButton ? `` : ''; // F2: previously a purely decorative
-- no action/method/input // name at all, so submitting did nothing. A real GET to `action` with the // query in the conventional `q` param makes this a functioning search // form on publish (routes to a real search-results page if the site has // one, or reloads '/' with ?q=... by default). `safeUrl` blocks // javascript:/vbscript:/data:text/html breakout via the action attribute. const actionAttr = escapeAttr(safeUrl(action) || '/'); return { html: `
${btnHtml}
`, }; };