render.ts 9.2 KB

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