render.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. import {
  2. Comment,
  3. Component,
  4. ComponentInternalInstance,
  5. ComponentOptions,
  6. DirectiveBinding,
  7. Fragment,
  8. mergeProps,
  9. ssrUtils,
  10. Static,
  11. Text,
  12. VNode,
  13. VNodeArrayChildren,
  14. VNodeProps,
  15. warn
  16. } from 'vue'
  17. import {
  18. escapeHtml,
  19. escapeHtmlComment,
  20. isFunction,
  21. isPromise,
  22. isString,
  23. isVoidTag,
  24. ShapeFlags,
  25. isArray
  26. } from '@vue/shared'
  27. import { ssrRenderAttrs } from './helpers/ssrRenderAttrs'
  28. import { ssrCompile } from './helpers/ssrCompile'
  29. import { ssrRenderTeleport } from './helpers/ssrRenderTeleport'
  30. const {
  31. createComponentInstance,
  32. setCurrentRenderingInstance,
  33. setupComponent,
  34. renderComponentRoot,
  35. normalizeVNode
  36. } = ssrUtils
  37. export type SSRBuffer = SSRBufferItem[] & { hasAsync?: boolean }
  38. export type SSRBufferItem = string | SSRBuffer | Promise<SSRBuffer>
  39. export type PushFn = (item: SSRBufferItem) => void
  40. export type Props = Record<string, unknown>
  41. export type SSRContext = {
  42. [key: string]: any
  43. teleports?: Record<string, string>
  44. __teleportBuffers?: Record<string, SSRBuffer>
  45. }
  46. // Each component has a buffer array.
  47. // A buffer array can contain one of the following:
  48. // - plain string
  49. // - A resolved buffer (recursive arrays of strings that can be unrolled
  50. // synchronously)
  51. // - An async buffer (a Promise that resolves to a resolved buffer)
  52. export function createBuffer() {
  53. let appendable = false
  54. const buffer: SSRBuffer = []
  55. return {
  56. getBuffer(): SSRBuffer {
  57. // Return static buffer and await on items during unroll stage
  58. return buffer
  59. },
  60. push(item: SSRBufferItem) {
  61. const isStringItem = isString(item)
  62. if (appendable && isStringItem) {
  63. buffer[buffer.length - 1] += item as string
  64. } else {
  65. buffer.push(item)
  66. }
  67. appendable = isStringItem
  68. if (isPromise(item) || (isArray(item) && item.hasAsync)) {
  69. // promise, or child buffer with async, mark as async.
  70. // this allows skipping unnecessary await ticks during unroll stage
  71. buffer.hasAsync = true
  72. }
  73. }
  74. }
  75. }
  76. export function renderComponentVNode(
  77. vnode: VNode,
  78. parentComponent: ComponentInternalInstance | null = null
  79. ): SSRBuffer | Promise<SSRBuffer> {
  80. const instance = createComponentInstance(vnode, parentComponent, null)
  81. const res = setupComponent(instance, true /* isSSR */)
  82. const hasAsyncSetup = isPromise(res)
  83. const prefetch = (vnode.type as ComponentOptions).serverPrefetch
  84. if (hasAsyncSetup || prefetch) {
  85. let p = hasAsyncSetup
  86. ? (res as Promise<void>).catch(err => {
  87. warn(`[@vue/server-renderer]: Uncaught error in async setup:\n`, err)
  88. })
  89. : Promise.resolve()
  90. if (prefetch) {
  91. p = p.then(() => prefetch.call(instance.proxy)).catch(err => {
  92. warn(`[@vue/server-renderer]: Uncaught error in serverPrefetch:\n`, err)
  93. })
  94. }
  95. return p.then(() => renderComponentSubTree(instance))
  96. } else {
  97. return renderComponentSubTree(instance)
  98. }
  99. }
  100. function renderComponentSubTree(
  101. instance: ComponentInternalInstance
  102. ): SSRBuffer | Promise<SSRBuffer> {
  103. const comp = instance.type as Component
  104. const { getBuffer, push } = createBuffer()
  105. if (isFunction(comp)) {
  106. renderVNode(
  107. push,
  108. (instance.subTree = renderComponentRoot(instance)),
  109. instance
  110. )
  111. } else {
  112. if (
  113. !instance.render &&
  114. !instance.ssrRender &&
  115. !comp.ssrRender &&
  116. isString(comp.template)
  117. ) {
  118. comp.ssrRender = ssrCompile(comp.template, instance)
  119. }
  120. const ssrRender = instance.ssrRender || comp.ssrRender
  121. if (ssrRender) {
  122. // optimized
  123. // resolve fallthrough attrs
  124. let attrs =
  125. instance.type.inheritAttrs !== false ? instance.attrs : undefined
  126. // inherited scopeId
  127. const scopeId = instance.vnode.scopeId
  128. const treeOwnerId = instance.parent && instance.parent.type.__scopeId
  129. const slotScopeId =
  130. treeOwnerId && treeOwnerId !== scopeId ? treeOwnerId + '-s' : null
  131. if (scopeId || slotScopeId) {
  132. attrs = { ...attrs }
  133. if (scopeId) attrs[scopeId] = ''
  134. if (slotScopeId) attrs[slotScopeId] = ''
  135. }
  136. // set current rendering instance for asset resolution
  137. setCurrentRenderingInstance(instance)
  138. ssrRender(
  139. instance.proxy,
  140. push,
  141. instance,
  142. attrs,
  143. // compiler-optimized bindings
  144. instance.props,
  145. instance.setupState,
  146. instance.data,
  147. instance.ctx
  148. )
  149. setCurrentRenderingInstance(null)
  150. } else if (instance.render) {
  151. renderVNode(
  152. push,
  153. (instance.subTree = renderComponentRoot(instance)),
  154. instance
  155. )
  156. } else {
  157. warn(
  158. `Component ${
  159. comp.name ? `${comp.name} ` : ``
  160. } is missing template or render function.`
  161. )
  162. push(`<!---->`)
  163. }
  164. }
  165. return getBuffer()
  166. }
  167. export function renderVNode(
  168. push: PushFn,
  169. vnode: VNode,
  170. parentComponent: ComponentInternalInstance
  171. ) {
  172. const { type, shapeFlag, children } = vnode
  173. switch (type) {
  174. case Text:
  175. push(escapeHtml(children as string))
  176. break
  177. case Comment:
  178. push(
  179. children ? `<!--${escapeHtmlComment(children as string)}-->` : `<!---->`
  180. )
  181. break
  182. case Static:
  183. push(children as string)
  184. break
  185. case Fragment:
  186. push(`<!--[-->`) // open
  187. renderVNodeChildren(push, children as VNodeArrayChildren, parentComponent)
  188. push(`<!--]-->`) // close
  189. break
  190. default:
  191. if (shapeFlag & ShapeFlags.ELEMENT) {
  192. renderElementVNode(push, vnode, parentComponent)
  193. } else if (shapeFlag & ShapeFlags.COMPONENT) {
  194. push(renderComponentVNode(vnode, parentComponent))
  195. } else if (shapeFlag & ShapeFlags.TELEPORT) {
  196. renderTeleportVNode(push, vnode, parentComponent)
  197. } else if (shapeFlag & ShapeFlags.SUSPENSE) {
  198. renderVNode(push, vnode.ssContent!, parentComponent)
  199. } else {
  200. warn(
  201. '[@vue/server-renderer] Invalid VNode type:',
  202. type,
  203. `(${typeof type})`
  204. )
  205. }
  206. }
  207. }
  208. export function renderVNodeChildren(
  209. push: PushFn,
  210. children: VNodeArrayChildren,
  211. parentComponent: ComponentInternalInstance
  212. ) {
  213. for (let i = 0; i < children.length; i++) {
  214. renderVNode(push, normalizeVNode(children[i]), parentComponent)
  215. }
  216. }
  217. function renderElementVNode(
  218. push: PushFn,
  219. vnode: VNode,
  220. parentComponent: ComponentInternalInstance
  221. ) {
  222. const tag = vnode.type as string
  223. let { props, children, shapeFlag, scopeId, dirs } = vnode
  224. let openTag = `<${tag}`
  225. if (dirs) {
  226. props = applySSRDirectives(vnode, props, dirs)
  227. }
  228. if (props) {
  229. openTag += ssrRenderAttrs(props, tag)
  230. }
  231. openTag += resolveScopeId(scopeId, vnode, parentComponent)
  232. push(openTag + `>`)
  233. if (!isVoidTag(tag)) {
  234. let hasChildrenOverride = false
  235. if (props) {
  236. if (props.innerHTML) {
  237. hasChildrenOverride = true
  238. push(props.innerHTML)
  239. } else if (props.textContent) {
  240. hasChildrenOverride = true
  241. push(escapeHtml(props.textContent))
  242. } else if (tag === 'textarea' && props.value) {
  243. hasChildrenOverride = true
  244. push(escapeHtml(props.value))
  245. }
  246. }
  247. if (!hasChildrenOverride) {
  248. if (shapeFlag & ShapeFlags.TEXT_CHILDREN) {
  249. push(escapeHtml(children as string))
  250. } else if (shapeFlag & ShapeFlags.ARRAY_CHILDREN) {
  251. renderVNodeChildren(
  252. push,
  253. children as VNodeArrayChildren,
  254. parentComponent
  255. )
  256. }
  257. }
  258. push(`</${tag}>`)
  259. }
  260. }
  261. function resolveScopeId(
  262. scopeId: string | null,
  263. vnode: VNode,
  264. parentComponent: ComponentInternalInstance | null
  265. ) {
  266. let res = ``
  267. if (scopeId) {
  268. res = ` ${scopeId}`
  269. }
  270. if (parentComponent) {
  271. const treeOwnerId = parentComponent.type.__scopeId
  272. // vnode's own scopeId and the current rendering component's scopeId is
  273. // different - this is a slot content node.
  274. if (treeOwnerId && treeOwnerId !== scopeId) {
  275. res += ` ${treeOwnerId}-s`
  276. }
  277. if (vnode === parentComponent.subTree) {
  278. res += resolveScopeId(
  279. parentComponent.vnode.scopeId,
  280. parentComponent.vnode,
  281. parentComponent.parent
  282. )
  283. }
  284. }
  285. return res
  286. }
  287. function applySSRDirectives(
  288. vnode: VNode,
  289. rawProps: VNodeProps | null,
  290. dirs: DirectiveBinding[]
  291. ): VNodeProps {
  292. const toMerge: VNodeProps[] = []
  293. for (let i = 0; i < dirs.length; i++) {
  294. const binding = dirs[i]
  295. const {
  296. dir: { getSSRProps }
  297. } = binding
  298. if (getSSRProps) {
  299. const props = getSSRProps(binding, vnode)
  300. if (props) toMerge.push(props)
  301. }
  302. }
  303. return mergeProps(rawProps || {}, ...toMerge)
  304. }
  305. function renderTeleportVNode(
  306. push: PushFn,
  307. vnode: VNode,
  308. parentComponent: ComponentInternalInstance
  309. ) {
  310. const target = vnode.props && vnode.props.to
  311. const disabled = vnode.props && vnode.props.disabled
  312. if (!target) {
  313. warn(`[@vue/server-renderer] Teleport is missing target prop.`)
  314. return []
  315. }
  316. if (!isString(target)) {
  317. warn(
  318. `[@vue/server-renderer] Teleport target must be a query selector string.`
  319. )
  320. return []
  321. }
  322. ssrRenderTeleport(
  323. push,
  324. push => {
  325. renderVNodeChildren(
  326. push,
  327. vnode.children as VNodeArrayChildren,
  328. parentComponent
  329. )
  330. },
  331. target,
  332. disabled || disabled === '',
  333. parentComponent
  334. )
  335. }