UNPKG

svelte-search-engine

Version:

A wrapper for Google's Programmable Search Engine, providing a Svelte-friendly interface.

36 lines (35 loc) 1.24 kB
import { getContext } from 'svelte'; export function assert(condition, msg) { if (!condition) { throw new Error(msg); } } export const randomString = () => Math.random().toString(16).slice(2); export function buildParams(baseTag, only, attributes, components) { const id = randomString(); const { gname } = attributes; const paramBase = { div: id, gname, attributes, components }; let param = undefined; if (only) { param = { ...paramBase, tag: `${baseTag}-only` }; } else { const context = getContext('gcse'); const contextValue = context[gname]; if (contextValue) { if (baseTag === 'searchbox') { assert(contextValue.tag === 'searchresults', 'Context value should be ParamOptConf'); param = [{ ...paramBase, tag: baseTag }, contextValue]; } else { assert(contextValue.tag === 'searchbox', 'Context value should be ParamConf'); param = [contextValue, { ...paramBase, tag: baseTag }]; } delete context[gname]; } else { context[gname] = { ...paramBase, tag: baseTag }; } } return { id, param }; }