ssrTransformComponent.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. import {
  2. CREATE_VNODE,
  3. type CallExpression,
  4. type CompilerOptions,
  5. type ComponentNode,
  6. DOMDirectiveTransforms,
  7. DOMNodeTransforms,
  8. type DirectiveNode,
  9. ElementTypes,
  10. type ExpressionNode,
  11. type FunctionExpression,
  12. type JSChildNode,
  13. Namespaces,
  14. type NodeTransform,
  15. NodeTypes,
  16. RESOLVE_DYNAMIC_COMPONENT,
  17. type ReturnStatement,
  18. type RootNode,
  19. SUSPENSE,
  20. type SlotFnBuilder,
  21. TELEPORT,
  22. TRANSITION,
  23. TRANSITION_GROUP,
  24. type TemplateChildNode,
  25. type TemplateNode,
  26. type TransformContext,
  27. type TransformOptions,
  28. buildProps,
  29. buildSlots,
  30. createCallExpression,
  31. createFunctionExpression,
  32. createIfStatement,
  33. createReturnStatement,
  34. createRoot,
  35. createSimpleExpression,
  36. createTransformContext,
  37. getBaseTransformPreset,
  38. locStub,
  39. resolveComponentType,
  40. stringifyExpression,
  41. traverseNode,
  42. } from '@vue/compiler-dom'
  43. import { SSR_RENDER_COMPONENT, SSR_RENDER_VNODE } from '../runtimeHelpers'
  44. import {
  45. type SSRTransformContext,
  46. processChildren,
  47. processChildrenAsStatement,
  48. } from '../ssrCodegenTransform'
  49. import { ssrProcessTeleport } from './ssrTransformTeleport'
  50. import {
  51. ssrProcessSuspense,
  52. ssrTransformSuspense,
  53. } from './ssrTransformSuspense'
  54. import {
  55. ssrProcessTransitionGroup,
  56. ssrTransformTransitionGroup,
  57. } from './ssrTransformTransitionGroup'
  58. import { extend, isArray, isObject, isPlainObject, isSymbol } from '@vue/shared'
  59. import { buildSSRProps } from './ssrTransformElement'
  60. import {
  61. ssrProcessTransition,
  62. ssrTransformTransition,
  63. } from './ssrTransformTransition'
  64. // We need to construct the slot functions in the 1st pass to ensure proper
  65. // scope tracking, but the children of each slot cannot be processed until
  66. // the 2nd pass, so we store the WIP slot functions in a weakMap during the 1st
  67. // pass and complete them in the 2nd pass.
  68. const wipMap = new WeakMap<ComponentNode, WIPSlotEntry[]>()
  69. const WIP_SLOT = Symbol()
  70. interface WIPSlotEntry {
  71. type: typeof WIP_SLOT
  72. fn: FunctionExpression
  73. children: TemplateChildNode[]
  74. vnodeBranch: ReturnStatement
  75. }
  76. const componentTypeMap = new WeakMap<
  77. ComponentNode,
  78. string | symbol | CallExpression
  79. >()
  80. // ssr component transform is done in two phases:
  81. // In phase 1. we use `buildSlot` to analyze the children of the component into
  82. // WIP slot functions (it must be done in phase 1 because `buildSlot` relies on
  83. // the core transform context).
  84. // In phase 2. we convert the WIP slots from phase 1 into ssr-specific codegen
  85. // nodes.
  86. export const ssrTransformComponent: NodeTransform = (node, context) => {
  87. if (
  88. node.type !== NodeTypes.ELEMENT ||
  89. node.tagType !== ElementTypes.COMPONENT
  90. ) {
  91. return
  92. }
  93. const component = resolveComponentType(node, context, true /* ssr */)
  94. const isDynamicComponent =
  95. isObject(component) && component.callee === RESOLVE_DYNAMIC_COMPONENT
  96. componentTypeMap.set(node, component)
  97. if (isSymbol(component)) {
  98. if (component === SUSPENSE) {
  99. return ssrTransformSuspense(node, context)
  100. } else if (component === TRANSITION_GROUP) {
  101. return ssrTransformTransitionGroup(node, context)
  102. } else if (component === TRANSITION) {
  103. return ssrTransformTransition(node, context)
  104. }
  105. return // other built-in components: fallthrough
  106. }
  107. // Build the fallback vnode-based branch for the component's slots.
  108. // We need to clone the node into a fresh copy and use the buildSlots' logic
  109. // to get access to the children of each slot. We then compile them with
  110. // a child transform pipeline using vnode-based transforms (instead of ssr-
  111. // based ones), and save the result branch (a ReturnStatement) in an array.
  112. // The branch is retrieved when processing slots again in ssr mode.
  113. const vnodeBranches: ReturnStatement[] = []
  114. const clonedNode = clone(node)
  115. return function ssrPostTransformComponent() {
  116. // Using the cloned node, build the normal VNode-based branches (for
  117. // fallback in case the child is render-fn based). Store them in an array
  118. // for later use.
  119. if (clonedNode.children.length) {
  120. buildSlots(clonedNode, context, (props, vFor, children) => {
  121. vnodeBranches.push(
  122. createVNodeSlotBranch(props, vFor, children, context),
  123. )
  124. return createFunctionExpression(undefined)
  125. })
  126. }
  127. let propsExp: string | JSChildNode = `null`
  128. if (node.props.length) {
  129. // note we are not passing ssr: true here because for components, v-on
  130. // handlers should still be passed
  131. const { props, directives } = buildProps(
  132. node,
  133. context,
  134. undefined,
  135. true,
  136. isDynamicComponent,
  137. )
  138. if (props || directives.length) {
  139. propsExp = buildSSRProps(props, directives, context)
  140. }
  141. }
  142. const wipEntries: WIPSlotEntry[] = []
  143. wipMap.set(node, wipEntries)
  144. const buildSSRSlotFn: SlotFnBuilder = (props, _vForExp, children, loc) => {
  145. const param0 = (props && stringifyExpression(props)) || `_`
  146. const fn = createFunctionExpression(
  147. [param0, `_push`, `_parent`, `_scopeId`],
  148. undefined, // no return, assign body later
  149. true, // newline
  150. true, // isSlot
  151. loc,
  152. )
  153. wipEntries.push({
  154. type: WIP_SLOT,
  155. fn,
  156. children,
  157. // also collect the corresponding vnode branch built earlier
  158. vnodeBranch: vnodeBranches[wipEntries.length],
  159. })
  160. return fn
  161. }
  162. const slots = node.children.length
  163. ? buildSlots(node, context, buildSSRSlotFn).slots
  164. : `null`
  165. if (typeof component !== 'string') {
  166. // dynamic component that resolved to a `resolveDynamicComponent` call
  167. // expression - since the resolved result may be a plain element (string)
  168. // or a VNode, handle it with `renderVNode`.
  169. node.ssrCodegenNode = createCallExpression(
  170. context.helper(SSR_RENDER_VNODE),
  171. [
  172. `_push`,
  173. createCallExpression(context.helper(CREATE_VNODE), [
  174. component,
  175. propsExp,
  176. slots,
  177. ]),
  178. `_parent`,
  179. ],
  180. )
  181. } else {
  182. node.ssrCodegenNode = createCallExpression(
  183. context.helper(SSR_RENDER_COMPONENT),
  184. [component, propsExp, slots, `_parent`],
  185. )
  186. }
  187. }
  188. }
  189. export function ssrProcessComponent(
  190. node: ComponentNode,
  191. context: SSRTransformContext,
  192. parent: { children: TemplateChildNode[] },
  193. ): void {
  194. const component = componentTypeMap.get(node)!
  195. if (!node.ssrCodegenNode) {
  196. // this is a built-in component that fell-through.
  197. if (component === TELEPORT) {
  198. return ssrProcessTeleport(node, context)
  199. } else if (component === SUSPENSE) {
  200. return ssrProcessSuspense(node, context)
  201. } else if (component === TRANSITION_GROUP) {
  202. return ssrProcessTransitionGroup(node, context)
  203. } else {
  204. // real fall-through: Transition / KeepAlive
  205. // just render its children.
  206. // #5352: if is at root level of a slot, push an empty string.
  207. // this does not affect the final output, but avoids all-comment slot
  208. // content of being treated as empty by ssrRenderSlot().
  209. if ((parent as WIPSlotEntry).type === WIP_SLOT) {
  210. context.pushStringPart(``)
  211. }
  212. if (component === TRANSITION) {
  213. return ssrProcessTransition(node, context)
  214. }
  215. processChildren(node, context)
  216. }
  217. } else {
  218. // finish up slot function expressions from the 1st pass.
  219. const wipEntries = wipMap.get(node) || []
  220. for (let i = 0; i < wipEntries.length; i++) {
  221. const { fn, vnodeBranch } = wipEntries[i]
  222. // For each slot, we generate two branches: one SSR-optimized branch and
  223. // one normal vnode-based branch. The branches are taken based on the
  224. // presence of the 2nd `_push` argument (which is only present if the slot
  225. // is called by `_ssrRenderSlot`.
  226. fn.body = createIfStatement(
  227. createSimpleExpression(`_push`, false),
  228. processChildrenAsStatement(
  229. wipEntries[i],
  230. context,
  231. false,
  232. true /* withSlotScopeId */,
  233. ),
  234. vnodeBranch,
  235. )
  236. }
  237. // component is inside a slot, inherit slot scope Id
  238. if (context.withSlotScopeId) {
  239. node.ssrCodegenNode.arguments.push(`_scopeId`)
  240. }
  241. if (typeof component === 'string') {
  242. // static component
  243. context.pushStatement(
  244. createCallExpression(`_push`, [node.ssrCodegenNode]),
  245. )
  246. } else {
  247. // dynamic component (`resolveDynamicComponent` call)
  248. // the codegen node is a `renderVNode` call
  249. context.pushStatement(node.ssrCodegenNode)
  250. }
  251. }
  252. }
  253. export const rawOptionsMap: WeakMap<RootNode, CompilerOptions> = new WeakMap<
  254. RootNode,
  255. CompilerOptions
  256. >()
  257. const [baseNodeTransforms, baseDirectiveTransforms] =
  258. getBaseTransformPreset(true)
  259. const vnodeNodeTransforms = [...baseNodeTransforms, ...DOMNodeTransforms]
  260. const vnodeDirectiveTransforms = {
  261. ...baseDirectiveTransforms,
  262. ...DOMDirectiveTransforms,
  263. }
  264. function createVNodeSlotBranch(
  265. slotProps: ExpressionNode | undefined,
  266. vFor: DirectiveNode | undefined,
  267. children: TemplateChildNode[],
  268. parentContext: TransformContext,
  269. ): ReturnStatement {
  270. // apply a sub-transform using vnode-based transforms.
  271. const rawOptions = rawOptionsMap.get(parentContext.root)!
  272. const subOptions = {
  273. ...rawOptions,
  274. // overwrite with vnode-based transforms
  275. nodeTransforms: [
  276. ...vnodeNodeTransforms,
  277. ...(rawOptions.nodeTransforms || []),
  278. ],
  279. directiveTransforms: {
  280. ...vnodeDirectiveTransforms,
  281. ...(rawOptions.directiveTransforms || {}),
  282. },
  283. }
  284. // wrap the children with a wrapper template for proper children treatment.
  285. // important: provide v-slot="props" and v-for="exp" on the wrapper for
  286. // proper scope analysis
  287. const wrapperProps: TemplateNode['props'] = []
  288. if (slotProps) {
  289. wrapperProps.push({
  290. type: NodeTypes.DIRECTIVE,
  291. name: 'slot',
  292. exp: slotProps,
  293. arg: undefined,
  294. modifiers: [],
  295. loc: locStub,
  296. })
  297. }
  298. if (vFor) {
  299. wrapperProps.push(extend({}, vFor))
  300. }
  301. const wrapperNode: TemplateNode = {
  302. type: NodeTypes.ELEMENT,
  303. ns: Namespaces.HTML,
  304. tag: 'template',
  305. tagType: ElementTypes.TEMPLATE,
  306. props: wrapperProps,
  307. children,
  308. loc: locStub,
  309. codegenNode: undefined,
  310. }
  311. subTransform(wrapperNode, subOptions, parentContext)
  312. return createReturnStatement(children)
  313. }
  314. function subTransform(
  315. node: TemplateChildNode,
  316. options: TransformOptions,
  317. parentContext: TransformContext,
  318. ) {
  319. const childRoot = createRoot([node])
  320. const childContext = createTransformContext(childRoot, options)
  321. // this sub transform is for vnode fallback branch so it should be handled
  322. // like normal render functions
  323. childContext.ssr = false
  324. // inherit parent scope analysis state
  325. childContext.scopes = { ...parentContext.scopes }
  326. childContext.identifiers = { ...parentContext.identifiers }
  327. childContext.imports = parentContext.imports
  328. // traverse
  329. traverseNode(childRoot, childContext)
  330. // merge helpers/components/directives into parent context
  331. ;(['helpers', 'components', 'directives'] as const).forEach(key => {
  332. childContext[key].forEach((value: any, helperKey: any) => {
  333. if (key === 'helpers') {
  334. const parentCount = parentContext.helpers.get(helperKey)
  335. if (parentCount === undefined) {
  336. parentContext.helpers.set(helperKey, value)
  337. } else {
  338. parentContext.helpers.set(helperKey, value + parentCount)
  339. }
  340. } else {
  341. ;(parentContext[key] as any).add(value)
  342. }
  343. })
  344. })
  345. // imports/hoists are not merged because:
  346. // - imports are only used for asset urls and should be consistent between
  347. // node/client branches
  348. // - hoists are not enabled for the client branch here
  349. }
  350. function clone(v: any): any {
  351. if (isArray(v)) {
  352. return v.map(clone)
  353. } else if (isPlainObject(v)) {
  354. const res: any = {}
  355. for (const key in v) {
  356. res[key] = clone(v[key as keyof typeof v])
  357. }
  358. return res
  359. } else {
  360. return v
  361. }
  362. }