import { FileType, GeneratedFile, ProjectPluginStructure } from '@teleporthq/teleport-types' /** * Adds a CSS block to the project's global stylesheet; when the project has * none (no tokens, no style sets) every page carries it inline instead. * Shared by the behavior plugins (Snap into view, scroll rail). */ export const appendGlobalCss = (structure: ProjectPluginStructure, css: string): void => { const styleSheet = structure.files.get('projectStyleSheet') const globalCss = styleSheet?.files.find((file) => file.fileType === FileType.CSS) if (styleSheet && globalCss) { structure.files.set('projectStyleSheet', { ...styleSheet, files: styleSheet.files.map((file: GeneratedFile) => file === globalCss ? { ...file, content: `${file.content.trimEnd()}\n\n${css}` } : file ), }) return } const styleTag = `\n` mapHtmlPages( structure, (html) => insertBeforeClosingTag(html, 'head', styleTag) ?? `${styleTag}${html}` ) } /** Adds an inline script to the end of every page. */ export const appendPageScript = (structure: ProjectPluginStructure, script: string): void => { const scriptTag = `\n` mapHtmlPages( structure, (html) => insertBeforeClosingTag(html, 'body', scriptTag) ?? `${html}\n${scriptTag}` ) } const CLOSING_TAG = { head: /<\/head\s*>/i, body: /<\/body\s*>/i } /** * Puts markup right before a document's closing head or body tag; undefined * when there is none (a component fragment). Prettier's strict whitespace (the * editor's "strict white spacing for HTML" setting) can write that tag as * ``, so it is matched, never looked up as ``. */ export const insertBeforeClosingTag = ( html: string, tag: keyof typeof CLOSING_TAG, markup: string ): string | undefined => { const closing = CLOSING_TAG[tag].exec(html) return closing ? `${html.slice(0, closing.index)}${markup}${html.slice(closing.index)}` : undefined } const mapHtmlPages = ( structure: ProjectPluginStructure, transform: (html: string) => string ): void => { structure.files.forEach((entry, key) => { structure.files.set(key, { ...entry, files: entry.files.map((file: GeneratedFile) => file.fileType === FileType.HTML ? { ...file, content: transform(file.content) } : file ), }) }) }