render.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. NOOP
  27. } from '@vue/shared'
  28. import { ssrRenderAttrs } from './helpers/ssrRenderAttrs'
  29. import { ssrCompile } from './helpers/ssrCompile'
  30. import { ssrRenderTeleport } from './helpers/ssrRenderTeleport'
  31. const {
  32. createComponentInstance,
  33. setCurrentRenderingInstance,
  34. setupComponent,
  35. renderComponentRoot,
  36. normalizeVNode
  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. slotScopeId?: string
  81. ): SSRBuffer | Promise<SSRBuffer> {
  82. const instance = createComponentInstance(vnode, parentComponent, null)
  83. const res = setupComponent(instance, true /* isSSR */)
  84. const hasAsyncSetup = isPromise(res)
  85. const prefetch = (vnode.type as ComponentOptions).serverPrefetch
  86. if (hasAsyncSetup || prefetch) {
  87. let p = hasAsyncSetup ? (res as Promise<void>) : Promise.resolve()
  88. if (prefetch) {
  89. p = p.then(() => prefetch.call(instance.proxy)).catch(err => {
  90. warn(`[@vue/server-renderer]: Uncaught error in serverPrefetch:\n`, err)
  91. })
  92. }
  93. return p.then(() => renderComponentSubTree(instance, slotScopeId))
  94. } else {
  95. return renderComponentSubTree(instance, slotScopeId)
  96. }
  97. }
  98. function renderComponentSubTree(
  99. instance: ComponentInternalInstance,
  100. slotScopeId?: string
  101. ): SSRBuffer | Promise<SSRBuffer> {
  102. const comp = instance.type as Component
  103. const { getBuffer, push } = createBuffer()
  104. if (isFunction(comp)) {
  105. renderVNode(
  106. push,
  107. (instance.subTree = renderComponentRoot(instance)),
  108. instance,
  109. slotScopeId
  110. )
  111. } else {
  112. if (
  113. (!instance.render || instance.render === NOOP) &&
  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. let hasCloned = false
  127. let cur = instance
  128. while (true) {
  129. const scopeId = cur.vnode.scopeId
  130. if (scopeId) {
  131. if (!hasCloned) {
  132. attrs = { ...attrs }
  133. hasCloned = true
  134. }
  135. attrs![scopeId] = ''
  136. }
  137. const parent = cur.parent
  138. if (parent && parent.subTree && parent.subTree === cur.vnode) {
  139. // parent is a non-SSR compiled component and is rendering this
  140. // component as root. inherit its scopeId if present.
  141. cur = parent
  142. } else {
  143. break
  144. }
  145. }
  146. if (slotScopeId) {
  147. if (!hasCloned) attrs = { ...attrs }
  148. attrs![slotScopeId.trim()] = ''
  149. }
  150. // set current rendering instance for asset resolution
  151. const prev = setCurrentRenderingInstance(instance)
  152. ssrRender(
  153. instance.proxy,
  154. push,
  155. instance,
  156. attrs,
  157. // compiler-optimized bindings
  158. instance.props,
  159. instance.setupState,
  160. instance.data,
  161. instance.ctx
  162. )
  163. setCurrentRenderingInstance(prev)
  164. } else if (instance.render && instance.render !== NOOP) {
  165. renderVNode(
  166. push,
  167. (instance.subTree = renderComponentRoot(instance)),
  168. instance,
  169. slotScopeId
  170. )
  171. } else {
  172. warn(
  173. `Component ${
  174. comp.name ? `${comp.name} ` : ``
  175. } is missing template or render function.`
  176. )
  177. push(`<!---->`)
  178. }
  179. }
  180. return getBuffer()
  181. }
  182. export function renderVNode(
  183. push: PushFn,
  184. vnode: VNode,
  185. parentComponent: ComponentInternalInstance,
  186. slotScopeId?: string
  187. ) {
  188. const { type, shapeFlag, children } = vnode
  189. switch (type) {
  190. case Text:
  191. push(escapeHtml(children as string))
  192. break
  193. case Comment:
  194. push(
  195. children ? `<!--${escapeHtmlComment(children as string)}-->` : `<!---->`
  196. )
  197. break
  198. case Static:
  199. push(children as string)
  200. break
  201. case Fragment:
  202. if (vnode.slotScopeIds) {
  203. slotScopeId =
  204. (slotScopeId ? slotScopeId + ' ' : '') + vnode.slotScopeIds.join(' ')
  205. }
  206. push(`<!--[-->`) // open
  207. renderVNodeChildren(
  208. push,
  209. children as VNodeArrayChildren,
  210. parentComponent,
  211. slotScopeId
  212. )
  213. push(`<!--]-->`) // close
  214. break
  215. default:
  216. if (shapeFlag & ShapeFlags.ELEMENT) {
  217. renderElementVNode(push, vnode, parentComponent, slotScopeId)
  218. } else if (shapeFlag & ShapeFlags.COMPONENT) {
  219. push(renderComponentVNode(vnode, parentComponent, slotScopeId))
  220. } else if (shapeFlag & ShapeFlags.TELEPORT) {
  221. renderTeleportVNode(push, vnode, parentComponent, slotScopeId)
  222. } else if (shapeFlag & ShapeFlags.SUSPENSE) {
  223. renderVNode(push, vnode.ssContent!, parentComponent, slotScopeId)
  224. } else {
  225. warn(
  226. '[@vue/server-renderer] Invalid VNode type:',
  227. type,
  228. `(${typeof type})`
  229. )
  230. }
  231. }
  232. }
  233. export function renderVNodeChildren(
  234. push: PushFn,
  235. children: VNodeArrayChildren,
  236. parentComponent: ComponentInternalInstance,
  237. slotScopeId: string | undefined
  238. ) {
  239. for (let i = 0; i < children.length; i++) {
  240. renderVNode(push, normalizeVNode(children[i]), parentComponent, slotScopeId)
  241. }
  242. }
  243. function renderElementVNode(
  244. push: PushFn,
  245. vnode: VNode,
  246. parentComponent: ComponentInternalInstance,
  247. slotScopeId: string | undefined
  248. ) {
  249. const tag = vnode.type as string
  250. let { props, children, shapeFlag, scopeId, dirs } = vnode
  251. let openTag = `<${tag}`
  252. if (dirs) {
  253. props = applySSRDirectives(vnode, props, dirs)
  254. }
  255. if (props) {
  256. openTag += ssrRenderAttrs(props, tag)
  257. }
  258. if (scopeId) {
  259. openTag += ` ${scopeId}`
  260. }
  261. // inherit parent chain scope id if this is the root node
  262. let curParent: ComponentInternalInstance | null = parentComponent
  263. let curVnode = vnode
  264. while (curParent && curVnode === curParent.subTree) {
  265. curVnode = curParent.vnode
  266. if (curVnode.scopeId) {
  267. openTag += ` ${curVnode.scopeId}`
  268. }
  269. curParent = curParent.parent
  270. }
  271. if (slotScopeId) {
  272. openTag += ` ${slotScopeId}`
  273. }
  274. push(openTag + `>`)
  275. if (!isVoidTag(tag)) {
  276. let hasChildrenOverride = false
  277. if (props) {
  278. if (props.innerHTML) {
  279. hasChildrenOverride = true
  280. push(props.innerHTML)
  281. } else if (props.textContent) {
  282. hasChildrenOverride = true
  283. push(escapeHtml(props.textContent))
  284. } else if (tag === 'textarea' && props.value) {
  285. hasChildrenOverride = true
  286. push(escapeHtml(props.value))
  287. }
  288. }
  289. if (!hasChildrenOverride) {
  290. if (shapeFlag & ShapeFlags.TEXT_CHILDREN) {
  291. push(escapeHtml(children as string))
  292. } else if (shapeFlag & ShapeFlags.ARRAY_CHILDREN) {
  293. renderVNodeChildren(
  294. push,
  295. children as VNodeArrayChildren,
  296. parentComponent,
  297. slotScopeId
  298. )
  299. }
  300. }
  301. push(`</${tag}>`)
  302. }
  303. }
  304. function applySSRDirectives(
  305. vnode: VNode,
  306. rawProps: VNodeProps | null,
  307. dirs: DirectiveBinding[]
  308. ): VNodeProps {
  309. const toMerge: VNodeProps[] = []
  310. for (let i = 0; i < dirs.length; i++) {
  311. const binding = dirs[i]
  312. const {
  313. dir: { getSSRProps }
  314. } = binding
  315. if (getSSRProps) {
  316. const props = getSSRProps(binding, vnode)
  317. if (props) toMerge.push(props)
  318. }
  319. }
  320. return mergeProps(rawProps || {}, ...toMerge)
  321. }
  322. function renderTeleportVNode(
  323. push: PushFn,
  324. vnode: VNode,
  325. parentComponent: ComponentInternalInstance,
  326. slotScopeId: string | undefined
  327. ) {
  328. const target = vnode.props && vnode.props.to
  329. const disabled = vnode.props && vnode.props.disabled
  330. if (!target) {
  331. warn(`[@vue/server-renderer] Teleport is missing target prop.`)
  332. return []
  333. }
  334. if (!isString(target)) {
  335. warn(
  336. `[@vue/server-renderer] Teleport target must be a query selector string.`
  337. )
  338. return []
  339. }
  340. ssrRenderTeleport(
  341. push,
  342. push => {
  343. renderVNodeChildren(
  344. push,
  345. vnode.children as VNodeArrayChildren,
  346. parentComponent,
  347. slotScopeId
  348. )
  349. },
  350. target,
  351. disabled || disabled === '',
  352. parentComponent
  353. )
  354. }