components.ts
This file
Path
src/jsx/intrinsic-element/components.ts
210 lines · 6.7 KiB · TypeScript
Last changed by
Merge commit from forkTaku Amanobefore adoption2b8ed40
History of this fileTake it
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–2why, one step back1import { raw } from '../../helper/html'2import type { HtmlEscapedCallback, HtmlEscapedString } from '../../utils/html'Merge commit from forkTaku Amanobefore adoption2b8ed40
line 3why, one step back3import { JSXNode, getNameSpaceContext, renderChildren } from '../base'Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 4–88why, one step back4import type { Child, Props } from '../base'5import { toArray } from '../children'6import { PERMALINK } from '../constants'7import { useContext } from '../context'8import type { IntrinsicElements } from '../intrinsic-elements'9import type { FC, PropsWithChildren } from '../types'10import {11 dataPrecedenceAttr,12 deDupeKeyMap,13 isStylesheetLinkWithPrecedence,14 shouldDeDupeByKey,15} from './common'1617const metaTagMap: WeakMap<18 object,19 Record<string, [string, Props, string | undefined][]>20> = new WeakMap()21const insertIntoHead: (22 tagName: string,23 tag: string,24 props: Props,25 precedence: string | undefined26) => HtmlEscapedCallback =27 (tagName, tag, props, precedence) =>28 ({ buffer, context }): undefined => {29 if (!buffer) {30 return31 }32 const map = metaTagMap.get(context) || {}33 metaTagMap.set(context, map)34 const tags = (map[tagName] ||= [])3536 let duped = false37 const deDupeKeys = deDupeKeyMap[tagName]38 const deDupeByKey = shouldDeDupeByKey(tagName, precedence !== undefined)39 if (deDupeByKey) {40 LOOP: for (const [, tagProps] of tags) {41 if (42 tagName === 'link' &&43 !(tagProps.rel === 'stylesheet' && tagProps[dataPrecedenceAttr] !== undefined)44 ) {45 continue46 }47 for (const key of deDupeKeys) {48 if ((tagProps?.[key] ?? null) === props?.[key]) {49 duped = true50 break LOOP51 }52 }53 }54 }5556 if (duped) {57 buffer[0] = buffer[0].replaceAll(tag, '')58 } else if (deDupeByKey || tagName === 'link') {59 tags.push([tag, props, precedence])60 } else {61 tags.unshift([tag, props, precedence])62 }6364 if (buffer[0].indexOf('</head>') !== -1) {65 let insertTags66 if (tagName === 'link' || precedence !== undefined) {67 const precedences: string[] = []68 insertTags = tags69 .map(([tag, , tagPrecedence], index) => {70 if (tagPrecedence === undefined) {71 return [tag, Number.MAX_SAFE_INTEGER, index] as [string, number, number]72 }73 let order = precedences.indexOf(tagPrecedence as string)74 if (order === -1) {75 precedences.push(tagPrecedence as string)76 order = precedences.length - 177 }78 return [tag, order, index] as [string, number, number]79 })80 .sort((a, b) => a[1] - b[1] || a[2] - b[2])81 .map(([tag]) => tag)82 } else {83 insertTags = tags.map(([tag]) => tag)84 }8586 insertTags.forEach((tag) => {87 buffer[0] = buffer[0].replaceAll(tag, '')88 })Merge commit from forkTaku Amanobefore adoption2b8ed40
line 89why, one step back89 buffer[0] = buffer[0].replace(/(?=<\/head>)/, () => insertTags.join(''))Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 90–93why, one step back90 }91 }9293const returnWithoutSpecialBehavior = (tag: string, children: Child, props: Props) =>Merge commit from forkTaku Amanobefore adoption2b8ed40
line 94why, one step back94 renderChildren([new JSXNode(tag, props, toArray(children ?? []))])Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 95–110why, one step back9596const documentMetadataTag = (tag: string, children: Child, props: Props, sort: boolean) => {97 if ('itemProp' in props) {98 return returnWithoutSpecialBehavior(tag, children, props)99 }100101 let { precedence, blocking, ...restProps } = props102 precedence = sort ? (precedence ?? '') : undefined103 if (sort) {104 restProps[dataPrecedenceAttr] = precedence105 }106107 const string = new JSXNode(tag, restProps, toArray(children || [])).toString()108109 if (string instanceof Promise) {110 return string.then((resString) =>fix(jsx): render async children of document metadata tags instead of [object Promise] (#5204)Paco Cartonesbefore adoption765d13b
line 111why, one step back111 raw(resString, [Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 112–210why, one step back112 ...((resString as HtmlEscapedString).callbacks || []),113 insertIntoHead(tag, resString, restProps, precedence),114 ])115 )116 } else {117 return raw(string, [insertIntoHead(tag, string, restProps, precedence)])118 }119}120121export const title: FC<PropsWithChildren> = ({ children, ...props }) => {122 const nameSpaceContext = getNameSpaceContext()123 if (nameSpaceContext) {124 const context = useContext(nameSpaceContext)125 if (context === 'svg' || context === 'head') {126 return new JSXNode(127 'title',128 props,129 toArray(children ?? []) as Child[]130 ) as unknown as HtmlEscapedString131 }132 }133134 return documentMetadataTag('title', children, props, false)135}136export const script: FC<PropsWithChildren<IntrinsicElements['script']>> = ({137 children,138 ...props139}) => {140 const nameSpaceContext = getNameSpaceContext()141 if (142 ['src', 'async'].some((k) => !props[k]) ||143 (nameSpaceContext && useContext(nameSpaceContext) === 'head')144 ) {145 return returnWithoutSpecialBehavior('script', children, props)146 }147148 return documentMetadataTag('script', children, props, false)149}150151export const style: FC<PropsWithChildren<IntrinsicElements['style']>> = ({152 children,153 ...props154}) => {155 if (!['href', 'precedence'].every((k) => k in props)) {156 return returnWithoutSpecialBehavior('style', children, props)157 }158 props['data-href'] = props.href159 delete props.href160 return documentMetadataTag('style', children, props, true)161}162export const link: FC<PropsWithChildren<IntrinsicElements['link']>> = ({ children, ...props }) => {163 if (164 ['onLoad', 'onError'].some((k) => k in props) ||165 (props.rel === 'stylesheet' && (!('precedence' in props) || 'disabled' in props))166 ) {167 return returnWithoutSpecialBehavior('link', children, props)168 }169 return documentMetadataTag('link', children, props, isStylesheetLinkWithPrecedence(props))170}171export const meta: FC<PropsWithChildren> = ({ children, ...props }) => {172 const nameSpaceContext = getNameSpaceContext()173 if (nameSpaceContext && useContext(nameSpaceContext) === 'head') {174 return returnWithoutSpecialBehavior('meta', children, props)175 }176 return documentMetadataTag('meta', children, props, false)177}178179const newJSXNode = (tag: string, { children, ...props }: PropsWithChildren<unknown>) =>180 // eslint-disable-next-line @typescript-eslint/no-explicit-any181 new JSXNode(tag, props, toArray(children ?? []) as Child[]) as any182export const form: FC<183 PropsWithChildren<{184 action?: Function | string185 method?: 'get' | 'post'186 }>187> = (props) => {188 if (typeof props.action === 'function') {189 props.action = PERMALINK in props.action ? (props.action[PERMALINK] as string) : undefined190 }191 return newJSXNode('form', props)192}193194const formActionableElement = (195 tag: string,196 props: PropsWithChildren<{197 formAction?: Function | string198 }>199) => {200 if (typeof props.formAction === 'function') {201 props.formAction =202 PERMALINK in props.formAction ? (props.formAction[PERMALINK] as string) : undefined203 }204 return newJSXNode(tag, props)205}206207export const input: (props: PropsWithChildren) => unknown = (props) =>208 formActionableElement('input', props)209export const button: (props: PropsWithChildren) => unknown = (props) =>210 formActionableElement('button', props)