'use client' import { ChangeEvent, createElement, forwardRef, HTMLProps, ReactNode } from 'react' import { PktButton } from '../button/Button' interface SearchSuggestion { title?: string text?: string href?: string onClick?: () => void } interface ISearch extends HTMLProps { appearance?: 'local' | 'local-with-button' | 'global' disabled?: boolean fullwidth?: boolean id: string label?: string name?: string placeholder?: string suggestions?: SearchSuggestion[] value?: string | undefined onSearch?: (value: string) => void onSuggestionClick?: (index: number) => void action?: string method?: 'get' | 'post' | 'dialog' } interface ISearchForm extends ISearch { action?: string method?: 'get' | 'post' | 'dialog' } interface ISearchInput extends ISearch { onChange: (event: ChangeEvent) => void disabled?: boolean } export const PktSearchInput = forwardRef( ( { appearance = 'local', disabled = false, fullwidth = false, id, label, name, placeholder = 'Søk…', suggestions, value = '', action, method, onChange, onSearch, onSuggestionClick, ...props }, ref, ) => { const handleSuggestionClick = (cb: (() => void) | undefined, index: number) => { if (cb) { cb() } else if (onSuggestionClick) { onSuggestionClick(index) } } const handleNoOnChange = (e: ChangeEvent) => { value = e.target.value } const wrapperClass = `pkt-searchinput pkt-searchinput--${appearance} ${ fullwidth ? 'pkt-searchinput--fullwidth' : '' }` let WrapperElement if (action) { // eslint-disable-next-line react/display-name WrapperElement = (children: ReactNode) => (
{children}
) } else { // eslint-disable-next-line react/display-name WrapperElement = (children: ReactNode) => (
{children}
) } return WrapperElement( <> {label && ( )}
{ if (event.key === 'Enter') { event.preventDefault() onSearch(value) } }) } {...props} /> { event.preventDefault() onSearch(value) }) } > {label || placeholder}
{suggestions && (
    {suggestions.map((suggestion, index) => (
  • {createElement( suggestion.href ? 'a' : suggestion.onClick ? 'button' : 'div', { href: suggestion.href, className: `pkt-searchinput__suggestion ${suggestion.onClick ? 'pkt-link-button' : ''} ${ suggestion.href || suggestion.onClick ? 'pkt-searchinput__suggestion--has-hover' : '' }`, type: suggestion.onClick ? 'button' : undefined, onClick: () => handleSuggestionClick(suggestion.onClick, index), onKeyUp: (event: { key: string }) => event.key === 'Enter' && handleSuggestionClick(suggestion.onClick, index), }, <> {suggestion.title &&

    {suggestion.title}

    } {suggestion.text &&

    {suggestion.text}

    } , )}
  • ))}
)} , ) }, ) PktSearchInput.displayName = 'PktSearchInput'