repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
sun-panel
github_2023
hslr-s
typescript
generateMD5AndUpdate
function generateMD5AndUpdate() { jsonData.md5 = generateMD5(JSON.stringify(jsonData)) }
// MD5 生成函数
https://github.com/hslr-s/sun-panel/blob/25f46209d97ae7bd6de29c39f93fd4d83932eb06/src/utils/jsonImportExport/index.ts#L67-L69
25f46209d97ae7bd6de29c39f93fd4d83932eb06
openbao
github_2023
openbao
typescript
SidebarHeaderHomeLinkComponent.ariaLabel
get ariaLabel() { const { ariaLabel } = this.args; assert( '@ariaLabel for "Sidebar::Header::HomeLink" ("Logo") must have a valid value', ariaLabel !== undefined ); return ariaLabel; }
/** * @param ariaLabel * @type {string} * @description The value of `aria-label` */
https://github.com/openbao/openbao/blob/b77625e9e5441469f949cc548aeed31f523628ec/ui/app/components/sidebar/header/home-link.ts#L21-L30
b77625e9e5441469f949cc548aeed31f523628ec
openbao
github_2023
openbao
typescript
DownloadService.csv
csv(filename: string, content: string) { this.download(filename, content, 'csv'); }
// namespacelonglonglong4/,auth/method/uMGBU,35,20,15\n'
https://github.com/openbao/openbao/blob/b77625e9e5441469f949cc548aeed31f523628ec/ui/app/services/download.ts#L54-L56
b77625e9e5441469f949cc548aeed31f523628ec
openbao
github_2023
openbao
typescript
PagePkiIssuerRotateRootComponent.displayFields
get displayFields() { const addKeyFields = ['privateKey', 'privateKeyType']; const defaultFields = [ 'certificate', 'caChain', 'issuerId', 'issuerName', 'issuingCa', 'keyName', 'keyId', 'serialNumber', ]; return this.args.newRootModel.id ? [...defaultFields, ...addKeyFields] : defaultFields; }
// for displaying old root details, and generated root details
https://github.com/openbao/openbao/blob/b77625e9e5441469f949cc548aeed31f523628ec/ui/lib/pki/addon/components/page/pki-issuer-rotate-root.ts#L61-L74
b77625e9e5441469f949cc548aeed31f523628ec
openbao
github_2023
openbao
typescript
fetchOptions
const fetchOptions = async () => { try { const url = new URL(location); var version = url.searchParams.get("version"); // Check if options are cached in localStorage and not expired const cachedOptions = localStorage.getItem("gh-releases"); if (cachedOptions) { const { data, timestamp } = JSON.parse(cachedOptions); if (new Date().getTime() - timestamp < 600000) { setOptions(data); const versions = Object.keys(data); // Prefer version from the query string, if present. if (version !== "" && versions.includes(version)) { setSelectedItem(version); return; } // Auto-select the first option otherwise. if (versions.length > 0) { setSelectedItem(versions[0]); return; } } } const response = await fetch( "https://api.github.com/repos/openbao/openbao/releases", ); if (!response.ok) { throw new Error("Failed to fetch gh-releases"); } const ghReleases = await response.json(); const releases = GetReleases(ghReleases); const versions = Object.keys(releases); setOptions(releases); localStorage.setItem( "gh-releases", JSON.stringify({ data: releases, timestamp: new Date().getTime(), }), ); // Prefer version from the query string, if present. if (version !== "" && versions.includes(version)) { setSelectedItem(version); return; } // Auto-select the first option. if (versions.length > 0) { setSelectedItem(versions[0]); } } catch (error) { console.error(error); } };
// Function to fetch options from API
https://github.com/openbao/openbao/blob/b77625e9e5441469f949cc548aeed31f523628ec/website/src/pages/downloads.tsx#L25-L83
b77625e9e5441469f949cc548aeed31f523628ec
backrest
github_2023
garethgeorge
typescript
handleScroll
const handleScroll = () => { if (!ref.current) { return; } const refRect = ref.current!.getBoundingClientRect(); let wiggle = Math.max(refRect.height - window.innerHeight, 0); let topY = Math.max(ref.current!.getBoundingClientRect().top, 0); let bottomY = topY; if (topY == 0) { // wiggle only if the top is actually the top edge of the screen. topY -= wiggle; bottomY += wiggle; } setTopY(topY); setBottomY(bottomY); refresh(Math.random()); };
// handle scroll events to keep the fixed container in view.
https://github.com/garethgeorge/backrest/blob/403458f70705258906258fa77d4668d70ac176e3/webui/src/components/OperationTreeView.tsx#L472-L490
403458f70705258906258fa77d4668d70ac176e3
backrest
github_2023
garethgeorge
typescript
getStatus
const getStatus = async (req: GetOperationsRequest) => { let ops = await getOperations(req); ops.sort((a, b) => { return Number(b.unixTimeStartMs - a.unixTimeStartMs); }); let flowID: BigInt | undefined = undefined; for (const op of ops) { if (op.status === OperationStatus.STATUS_PENDING || op.status === OperationStatus.STATUS_SYSTEM_CANCELLED) { continue; } if (op.status !== OperationStatus.STATUS_SUCCESS) { return op.status; } if (!flowID) { flowID = op.flowId; } else if (flowID !== op.flowId) { break; } if (op.status !== OperationStatus.STATUS_SUCCESS) { return op.status; } } return OperationStatus.STATUS_SUCCESS; };
// getStatus returns the status of the last N operations that belong to a single snapshot.
https://github.com/garethgeorge/backrest/blob/403458f70705258906258fa77d4668d70ac176e3/webui/src/state/logstate.ts#L58-L82
403458f70705258906258fa77d4668d70ac176e3
backrest
github_2023
garethgeorge
typescript
fetchData
const fetchData = async () => { // check if the tab is in the foreground if (document.hidden) { return; } try { const data = await backrestService.getSummaryDashboard({}); setSummaryData(data); } catch (e) { alertApi.error("Failed to fetch summary data: " + e); } };
// Fetch summary data
https://github.com/garethgeorge/backrest/blob/403458f70705258906258fa77d4668d70ac176e3/webui/src/views/SummaryDashboard.tsx#L54-L66
403458f70705258906258fa77d4668d70ac176e3
vue-vapor
github_2023
vuejs
typescript
PluginTyped
const PluginTyped: Plugin<PluginOptions> = (app, options) => {}
// still valid but it's better to use the regular function because this one can accept an optional param
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages-private/dts-test/appUse.test-d.ts#L91-L91
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
testUnrefGenerics
function testUnrefGenerics<T>(p: T | Ref<T>) { expectType<T>(unref(p)) }
// #3954
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages-private/dts-test/ref.test-d.ts#L408-L410
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
customNodeTransform
const customNodeTransform: NodeTransform = (node, context) => { if ( node.type === NodeTypes.ELEMENT && node.tag === 'div' && node.props.some( prop => prop.type === NodeTypes.ATTRIBUTE && prop.name === 'id' && prop.value && prop.value.content === 'foo', ) ) { context.replaceNode({ ...node, tag: 'span', }) } }
// a NodeTransform that swaps out <div id="foo" /> with <span id="foo" />
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-core/__tests__/transforms/transformElement.spec.ts#L1318-L1335
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
isReferenced
function isReferenced(node: Node, parent: Node, grandparent?: Node): boolean { switch (parent.type) { // yes: PARENT[NODE] // yes: NODE.child // no: parent.NODE case 'MemberExpression': case 'OptionalMemberExpression': if (parent.property === node) { return !!parent.computed } return parent.object === node case 'JSXMemberExpression': return parent.object === node // no: let NODE = init; // yes: let id = NODE; case 'VariableDeclarator': return parent.init === node // yes: () => NODE // no: (NODE) => {} case 'ArrowFunctionExpression': return parent.body === node // no: class { #NODE; } // no: class { get #NODE() {} } // no: class { #NODE() {} } // no: class { fn() { return this.#NODE; } } case 'PrivateName': return false // no: class { NODE() {} } // yes: class { [NODE]() {} } // no: class { foo(NODE) {} } case 'ClassMethod': case 'ClassPrivateMethod': case 'ObjectMethod': if (parent.key === node) { return !!parent.computed } return false // yes: { [NODE]: "" } // no: { NODE: "" } // depends: { NODE } // depends: { key: NODE } case 'ObjectProperty': if (parent.key === node) { return !!parent.computed } // parent.value === node return !grandparent || grandparent.type !== 'ObjectPattern' // no: class { NODE = value; } // yes: class { [NODE] = value; } // yes: class { key = NODE; } case 'ClassProperty': if (parent.key === node) { return !!parent.computed } return true case 'ClassPrivateProperty': return parent.key !== node // no: class NODE {} // yes: class Foo extends NODE {} case 'ClassDeclaration': case 'ClassExpression': return parent.superClass === node // yes: left = NODE; // no: NODE = right; case 'AssignmentExpression': return parent.right === node // no: [NODE = foo] = []; // yes: [foo = NODE] = []; case 'AssignmentPattern': return parent.right === node // no: NODE: for (;;) {} case 'LabeledStatement': return false // no: try {} catch (NODE) {} case 'CatchClause': return false // no: function foo(...NODE) {} case 'RestElement': return false case 'BreakStatement': case 'ContinueStatement': return false // no: function NODE() {} // no: function foo(NODE) {} case 'FunctionDeclaration': case 'FunctionExpression': return false // no: export NODE from "foo"; // no: export * as NODE from "foo"; case 'ExportNamespaceSpecifier': case 'ExportDefaultSpecifier': return false // no: export { foo as NODE }; // yes: export { NODE as foo }; // no: export { NODE as foo } from "foo"; case 'ExportSpecifier': // @ts-expect-error // eslint-disable-next-line no-restricted-syntax if (grandparent?.source) { return false } return parent.local === node // no: import NODE from "foo"; // no: import * as NODE from "foo"; // no: import { NODE as foo } from "foo"; // no: import { foo as NODE } from "foo"; // no: import NODE from "bar"; case 'ImportDefaultSpecifier': case 'ImportNamespaceSpecifier': case 'ImportSpecifier': return false // no: import "foo" assert { NODE: "json" } case 'ImportAttribute': return false // no: <div NODE="foo" /> case 'JSXAttribute': return false // no: [NODE] = []; // no: ({ NODE }) = []; case 'ObjectPattern': case 'ArrayPattern': return false // no: new.NODE // no: NODE.target case 'MetaProperty': return false // yes: type X = { someProperty: NODE } // no: type X = { NODE: OtherType } case 'ObjectTypeProperty': return parent.key !== node // yes: enum X { Foo = NODE } // no: enum X { NODE } case 'TSEnumMember': return parent.id !== node // yes: { [NODE]: value } // no: { NODE: value } case 'TSPropertySignature': if (parent.key === node) { return !!parent.computed } return true } return true }
/** * Copied from https://github.com/babel/babel/blob/main/packages/babel-types/src/validators/isReferenced.ts * To avoid runtime dependency on @babel/types (which includes process references) * This file should not change very often in babel but we may need to keep it * up-to-date from time to time. * * https://github.com/babel/babel/blob/main/LICENSE * */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-core/src/babelUtils.ts#L328-L496
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
genCallExpression
function genCallExpression(node: CallExpression, context: CodegenContext) { const { push, helper, pure } = context const callee = isString(node.callee) ? node.callee : helper(node.callee) if (pure) { push(PURE_ANNOTATION) } push(callee + `(`, NewlineType.None, node) genNodeList(node.arguments, context) push(`)`) }
// JavaScript
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-core/src/codegen.ts#L902-L911
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
isTagStartChar
function isTagStartChar(c: number): boolean { return ( (c >= CharCodes.LowerA && c <= CharCodes.LowerZ) || (c >= CharCodes.UpperA && c <= CharCodes.UpperZ) ) }
/** * HTML only allows ASCII alpha characters (a-z and A-Z) at the beginning of a * tag name. */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-core/src/tokenizer.ts#L144-L149
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
Tokenizer.getPos
public getPos(index: number): Position { let line = 1 let column = index + 1 for (let i = this.newlines.length - 1; i >= 0; i--) { const newlineIndex = this.newlines[i] if (index > newlineIndex) { line = i + 2 column = index - newlineIndex break } } return { column, line, offset: index, } }
/** * Generate Position object with line / column information using recorded * newline positions. We know the index is always going to be an already * processed index, so all the newlines up to this index should have been * recorded. */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-core/src/tokenizer.ts#L296-L312
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
Tokenizer.stateInRCDATA
private stateInRCDATA(c: number): void { if (this.sequenceIndex === this.currentSequence.length) { if (c === CharCodes.Gt || isWhitespace(c)) { const endOfText = this.index - this.currentSequence.length if (this.sectionStart < endOfText) { // Spoof the index so that reported locations match up. const actualIndex = this.index this.index = endOfText this.cbs.ontext(this.sectionStart, endOfText) this.index = actualIndex } this.sectionStart = endOfText + 2 // Skip over the `</` this.stateInClosingTagName(c) this.inRCDATA = false return // We are done; skip the rest of the function. } this.sequenceIndex = 0 } if ((c | 0x20) === this.currentSequence[this.sequenceIndex]) { this.sequenceIndex += 1 } else if (this.sequenceIndex === 0) { if ( this.currentSequence === Sequences.TitleEnd || (this.currentSequence === Sequences.TextareaEnd && !this.inSFCRoot) ) { // We have to parse entities in <title> and <textarea> tags. if (!__BROWSER__ && c === CharCodes.Amp) { this.startEntity() } else if (!this.inVPre && c === this.delimiterOpen[0]) { // We also need to handle interpolation this.state = State.InterpolationOpen this.delimiterIndex = 0 this.stateInterpolationOpen(c) } } else if (this.fastForwardTo(CharCodes.Lt)) { // Outside of <title> and <textarea> tags, we can fast-forward. this.sequenceIndex = 1 } } else { // If we see a `<`, set the sequence index to 1; useful for eg. `<</script>`. this.sequenceIndex = Number(c === CharCodes.Lt) } }
/** Look for an end tag. For <title> and <textarea>, also decode entities. */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-core/src/tokenizer.ts#L409-L455
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
Tokenizer.fastForwardTo
private fastForwardTo(c: number): boolean { while (++this.index < this.buffer.length) { const cc = this.buffer.charCodeAt(this.index) if (cc === CharCodes.NewLine) { this.newlines.push(this.index) } if (cc === c) { return true } } /* * We increment the index at the end of the `parse` loop, * so set it to `buffer.length - 1` here. * * TODO: Refactor `parse` to increment index before calling states. */ this.index = this.buffer.length - 1 return false }
/** * When we wait for one specific character, we can speed things up * by skipping through the buffer until we find it. * * @returns Whether the character was found. */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-core/src/tokenizer.ts#L478-L498
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
Tokenizer.stateInCommentLike
private stateInCommentLike(c: number): void { if (c === this.currentSequence[this.sequenceIndex]) { if (++this.sequenceIndex === this.currentSequence.length) { if (this.currentSequence === Sequences.CdataEnd) { this.cbs.oncdata(this.sectionStart, this.index - 2) } else { this.cbs.oncomment(this.sectionStart, this.index - 2) } this.sequenceIndex = 0 this.sectionStart = this.index + 1 this.state = State.Text } } else if (this.sequenceIndex === 0) { // Fast-forward to the first character of the sequence if (this.fastForwardTo(this.currentSequence[0])) { this.sequenceIndex = 1 } } else if (c !== this.currentSequence[this.sequenceIndex - 1]) { // Allow long sequences, eg. --->, ]]]> this.sequenceIndex = 0 } }
/** * Comments and CDATA end with `-->` and `]]>`. * * Their common qualities are: * - Their end sequences have a distinct character they start with. * - That character is then repeated, so we have to check multiple repeats. * - All characters but the start character of the sequence can be skipped. */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-core/src/tokenizer.ts#L508-L530
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
Tokenizer.parse
public parse(input: string): void { this.buffer = input while (this.index < this.buffer.length) { const c = this.buffer.charCodeAt(this.index) if (c === CharCodes.NewLine) { this.newlines.push(this.index) } switch (this.state) { case State.Text: { this.stateText(c) break } case State.InterpolationOpen: { this.stateInterpolationOpen(c) break } case State.Interpolation: { this.stateInterpolation(c) break } case State.InterpolationClose: { this.stateInterpolationClose(c) break } case State.SpecialStartSequence: { this.stateSpecialStartSequence(c) break } case State.InRCDATA: { this.stateInRCDATA(c) break } case State.CDATASequence: { this.stateCDATASequence(c) break } case State.InAttrValueDq: { this.stateInAttrValueDoubleQuotes(c) break } case State.InAttrName: { this.stateInAttrName(c) break } case State.InDirName: { this.stateInDirName(c) break } case State.InDirArg: { this.stateInDirArg(c) break } case State.InDirDynamicArg: { this.stateInDynamicDirArg(c) break } case State.InDirModifier: { this.stateInDirModifier(c) break } case State.InCommentLike: { this.stateInCommentLike(c) break } case State.InSpecialComment: { this.stateInSpecialComment(c) break } case State.BeforeAttrName: { this.stateBeforeAttrName(c) break } case State.InTagName: { this.stateInTagName(c) break } case State.InSFCRootTagName: { this.stateInSFCRootTagName(c) break } case State.InClosingTagName: { this.stateInClosingTagName(c) break } case State.BeforeTagName: { this.stateBeforeTagName(c) break } case State.AfterAttrName: { this.stateAfterAttrName(c) break } case State.InAttrValueSq: { this.stateInAttrValueSingleQuotes(c) break } case State.BeforeAttrValue: { this.stateBeforeAttrValue(c) break } case State.BeforeClosingTagName: { this.stateBeforeClosingTagName(c) break } case State.AfterClosingTagName: { this.stateAfterClosingTagName(c) break } case State.BeforeSpecialS: { this.stateBeforeSpecialS(c) break } case State.BeforeSpecialT: { this.stateBeforeSpecialT(c) break } case State.InAttrValueNq: { this.stateInAttrValueNoQuotes(c) break } case State.InSelfClosingTag: { this.stateInSelfClosingTag(c) break } case State.InDeclaration: { this.stateInDeclaration(c) break } case State.BeforeDeclaration: { this.stateBeforeDeclaration(c) break } case State.BeforeComment: { this.stateBeforeComment(c) break } case State.InProcessingInstruction: { this.stateInProcessingInstruction(c) break } case State.InEntity: { this.stateInEntity() break } } this.index++ } this.cleanup() this.finish() }
/** * Iterates through the buffer, calling the function corresponding to the current state. * * States that are more likely to be hit are higher up, as a performance improvement. */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-core/src/tokenizer.ts#L928-L1077
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
Tokenizer.cleanup
private cleanup() { // If we are inside of text or attributes, emit what we already have. if (this.sectionStart !== this.index) { if ( this.state === State.Text || (this.state === State.InRCDATA && this.sequenceIndex === 0) ) { this.cbs.ontext(this.sectionStart, this.index) this.sectionStart = this.index } else if ( this.state === State.InAttrValueDq || this.state === State.InAttrValueSq || this.state === State.InAttrValueNq ) { this.cbs.onattribdata(this.sectionStart, this.index) this.sectionStart = this.index } } }
/** * Remove data that has already been consumed from the buffer. */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-core/src/tokenizer.ts#L1082-L1100
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
Tokenizer.handleTrailingData
private handleTrailingData() { const endIndex = this.buffer.length // If there is no remaining data, we are done. if (this.sectionStart >= endIndex) { return } if (this.state === State.InCommentLike) { if (this.currentSequence === Sequences.CdataEnd) { this.cbs.oncdata(this.sectionStart, endIndex) } else { this.cbs.oncomment(this.sectionStart, endIndex) } } else if ( this.state === State.InTagName || this.state === State.BeforeAttrName || this.state === State.BeforeAttrValue || this.state === State.AfterAttrName || this.state === State.InAttrName || this.state === State.InDirName || this.state === State.InDirArg || this.state === State.InDirDynamicArg || this.state === State.InDirModifier || this.state === State.InAttrValueSq || this.state === State.InAttrValueDq || this.state === State.InAttrValueNq || this.state === State.InClosingTagName ) { /* * If we are currently in an opening or closing tag, us not calling the * respective callback signals that the tag should be ignored. */ } else { this.cbs.ontext(this.sectionStart, endIndex) } }
/** Handle any trailing data. */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-core/src/tokenizer.ts#L1114-L1150
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
hasProp
function hasProp(prop: Property, props: ObjectExpression) { let result = false if (prop.key.type === NodeTypes.SIMPLE_EXPRESSION) { const propKeyName = prop.key.content result = props.properties.some( p => p.key.type === NodeTypes.SIMPLE_EXPRESSION && p.key.content === propKeyName, ) } return result }
// check existing key to avoid overriding user provided keys
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-core/src/utils.ts#L473-L484
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
pushRefVForMarker
const pushRefVForMarker = () => { if (context.scopes.vFor > 0) { properties.push( createObjectProperty( createSimpleExpression('ref_for', true), createSimpleExpression('true'), ), ) } }
// mark template ref on v-for
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-core/src/transforms/transformElement.ts#L416-L425
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
dedupeProperties
function dedupeProperties(properties: Property[]): Property[] { const knownProps: Map<string, Property> = new Map() const deduped: Property[] = [] for (let i = 0; i < properties.length; i++) { const prop = properties[i] // dynamic keys are always allowed if (prop.key.type === NodeTypes.COMPOUND_EXPRESSION || !prop.key.isStatic) { deduped.push(prop) continue } const name = prop.key.content const existing = knownProps.get(name) if (existing) { if (name === 'style' || name === 'class' || isOn(name)) { mergeAsArray(existing, prop) } // unexpected duplicate, should have emitted error during parse } else { knownProps.set(name, prop) deduped.push(prop) } } return deduped }
// Dedupe props in an object literal.
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-core/src/transforms/transformElement.ts#L838-L861
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
cachedArrayBailedMatcher
function cachedArrayBailedMatcher(n = 1) { return { type: NodeTypes.JS_CACHE_EXPRESSION, value: { type: NodeTypes.JS_ARRAY_EXPRESSION, elements: new Array(n).fill(0).map(() => ({ // should remain VNODE_CALL instead of JS_CALL_EXPRESSION codegenNode: { type: NodeTypes.VNODE_CALL }, })), }, } }
/** * Assert cached node NOT stringified */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-dom/__tests__/transforms/stringifyStatic.spec.ts#L29-L40
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
cachedArraySuccessMatcher
function cachedArraySuccessMatcher(n = 1) { return { type: NodeTypes.JS_CACHE_EXPRESSION, value: { type: NodeTypes.JS_ARRAY_EXPRESSION, elements: new Array(n).fill(0).map(() => ({ type: NodeTypes.JS_CALL_EXPRESSION, callee: CREATE_STATIC, })), }, } }
/** * Assert cached node is stringified (no content check) */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-dom/__tests__/transforms/stringifyStatic.spec.ts#L45-L56
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
cachedArrayStaticNodeMatcher
function cachedArrayStaticNodeMatcher(content: string, count: number) { return { type: NodeTypes.JS_CACHE_EXPRESSION, value: { type: NodeTypes.JS_ARRAY_EXPRESSION, elements: [ { type: NodeTypes.JS_CALL_EXPRESSION, callee: CREATE_STATIC, arguments: [JSON.stringify(content), String(count)], }, ], }, } }
/** * Assert cached node stringified with desired content and node count */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-dom/__tests__/transforms/stringifyStatic.spec.ts#L61-L75
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
analyzeNode
function analyzeNode(node: StringifiableNode): [number, number] | false { if (node.type === NodeTypes.ELEMENT && isNonStringifiable(node.tag)) { return false } if (node.type === NodeTypes.TEXT_CALL) { return [1, 0] } let nc = 1 // node count let ec = node.props.length > 0 ? 1 : 0 // element w/ binding count let bailed = false const bail = (): false => { bailed = true return false } // TODO: check for cases where using innerHTML will result in different // output compared to imperative node insertions. // probably only need to check for most common case // i.e. non-phrasing-content tags inside `<p>` function walk(node: ElementNode): boolean { const isOptionTag = node.tag === 'option' && node.ns === Namespaces.HTML for (let i = 0; i < node.props.length; i++) { const p = node.props[i] // bail on non-attr bindings if ( p.type === NodeTypes.ATTRIBUTE && !isStringifiableAttr(p.name, node.ns) ) { return bail() } if (p.type === NodeTypes.DIRECTIVE && p.name === 'bind') { // bail on non-attr bindings if ( p.arg && (p.arg.type === NodeTypes.COMPOUND_EXPRESSION || (p.arg.isStatic && !isStringifiableAttr(p.arg.content, node.ns))) ) { return bail() } if ( p.exp && (p.exp.type === NodeTypes.COMPOUND_EXPRESSION || p.exp.constType < ConstantTypes.CAN_STRINGIFY) ) { return bail() } // <option :value="1"> cannot be safely stringified if ( isOptionTag && isStaticArgOf(p.arg, 'value') && p.exp && !p.exp.isStatic ) { return bail() } } } for (let i = 0; i < node.children.length; i++) { nc++ const child = node.children[i] if (child.type === NodeTypes.ELEMENT) { if (child.props.length > 0) { ec++ } walk(child) if (bailed) { return false } } } return true } return walk(node) ? [nc, ec] : false }
/** * for a cached node, analyze it and return: * - false: bailed (contains non-stringifiable props or runtime constant) * - [nc, ec] where * - nc is the number of nodes inside * - ec is the number of element with bindings inside */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-dom/src/transforms/stringifyStatic.ts#L211-L287
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
walk
function walk(node: ElementNode): boolean { const isOptionTag = node.tag === 'option' && node.ns === Namespaces.HTML for (let i = 0; i < node.props.length; i++) { const p = node.props[i] // bail on non-attr bindings if ( p.type === NodeTypes.ATTRIBUTE && !isStringifiableAttr(p.name, node.ns) ) { return bail() } if (p.type === NodeTypes.DIRECTIVE && p.name === 'bind') { // bail on non-attr bindings if ( p.arg && (p.arg.type === NodeTypes.COMPOUND_EXPRESSION || (p.arg.isStatic && !isStringifiableAttr(p.arg.content, node.ns))) ) { return bail() } if ( p.exp && (p.exp.type === NodeTypes.COMPOUND_EXPRESSION || p.exp.constType < ConstantTypes.CAN_STRINGIFY) ) { return bail() } // <option :value="1"> cannot be safely stringified if ( isOptionTag && isStaticArgOf(p.arg, 'value') && p.exp && !p.exp.isStatic ) { return bail() } } } for (let i = 0; i < node.children.length; i++) { nc++ const child = node.children[i] if (child.type === NodeTypes.ELEMENT) { if (child.props.length > 0) { ec++ } walk(child) if (bailed) { return false } } } return true }
// TODO: check for cases where using innerHTML will result in different
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-dom/src/transforms/stringifyStatic.ts#L232-L284
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
evaluateConstant
function evaluateConstant(exp: ExpressionNode): string { if (exp.type === NodeTypes.SIMPLE_EXPRESSION) { return new Function(`return (${exp.content})`)() } else { // compound let res = `` exp.children.forEach(c => { if (isString(c) || isSymbol(c)) { return } if (c.type === NodeTypes.TEXT) { res += c.content } else if (c.type === NodeTypes.INTERPOLATION) { res += toDisplayString(evaluateConstant(c.content)) } else { res += evaluateConstant(c as ExpressionNode) } }) return res } }
// __UNSAFE__
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-dom/src/transforms/stringifyStatic.ts#L397-L417
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
isEmpty
function isEmpty(node: ElementNode) { for (let i = 0; i < node.children.length; i++) { const child = node.children[i] if (child.type !== NodeTypes.TEXT || child.content.trim() !== '') { return false } } return true }
/** * Returns true if the node has no children * once the empty text nodes (trimmed content) have been filtered out. */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-sfc/src/parse.ts#L425-L433
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
dedent
function dedent(s: string): [string, number] { const lines = s.split('\n') const minIndent = lines.reduce(function (minIndent, line) { if (line.trim() === '') { return minIndent } const indent = line.match(/^\s*/)?.[0]?.length || 0 return Math.min(indent, minIndent) }, Infinity) if (minIndent === 0) { return [s, minIndent] } return [ lines .map(function (line) { return line.slice(minIndent) }) .join('\n'), minIndent, ] }
/** * Dedent a string. * * This removes any whitespace that is common to all lines in the string from * each line in the string. */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-sfc/src/parse.ts#L470-L490
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
hasStaticWithDefaults
function hasStaticWithDefaults(ctx: TypeResolveContext) { return !!( ctx.propsRuntimeDefaults && ctx.propsRuntimeDefaults.type === 'ObjectExpression' && ctx.propsRuntimeDefaults.properties.every( node => node.type !== 'SpreadElement' && (!node.computed || node.key.type.endsWith('Literal')), ) ) }
/** * check defaults. If the default object is an object literal with only * static properties, we can directly generate more optimized default * declarations. Otherwise we will have to fallback to runtime merging. */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-sfc/src/script/defineProps.ts#L314-L324
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
inferValueType
function inferValueType(node: Node): string | undefined { switch (node.type) { case 'StringLiteral': return 'String' case 'NumericLiteral': return 'Number' case 'BooleanLiteral': return 'Boolean' case 'ObjectExpression': return 'Object' case 'ArrayExpression': return 'Array' case 'FunctionExpression': case 'ArrowFunctionExpression': return 'Function' } }
// non-comprehensive, best-effort type infernece for a runtime value
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-sfc/src/script/defineProps.ts#L375-L391
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
resolveExtractPropTypes
function resolveExtractPropTypes( { props }: ResolvedElements, scope: TypeScope, ): ResolvedElements { const res: ResolvedElements = { props: {} } for (const key in props) { const raw = props[key] res.props[key] = reverseInferType( raw.key, raw.typeAnnotation!.typeAnnotation, scope, ) } return res }
/** * support for the `ExtractPropTypes` helper - it's non-exhaustive, mostly * tailored towards popular component libs like element-plus and antd-vue. */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-sfc/src/script/resolveType.ts#L1802-L1816
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
scss
const scss: StylePreprocessor = (source, map, options, load = require) => { const nodeSass: typeof import('sass') = load('sass') const { compileString, renderSync } = nodeSass const data = getSource(source, options.filename, options.additionalData) let css: string let dependencies: string[] let sourceMap: any try { if (compileString) { const { pathToFileURL, fileURLToPath }: typeof import('url') = load('url') const result = compileString(data, { ...options, url: pathToFileURL(options.filename), sourceMap: !!map, }) css = result.css dependencies = result.loadedUrls.map(url => fileURLToPath(url)) sourceMap = map ? result.sourceMap! : undefined } else { const result = renderSync({ ...options, data, file: options.filename, outFile: options.filename, sourceMap: !!map, }) css = result.css.toString() dependencies = result.stats.includedFiles sourceMap = map ? JSON.parse(result.map!.toString()) : undefined } if (map) { return { code: css, errors: [], dependencies, map: merge(map, sourceMap!), } } return { code: css, errors: [], dependencies } } catch (e: any) { return { code: '', errors: [e], dependencies: [] } } }
// .scss/.sass processor
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-sfc/src/style/preprocessors.ts#L25-L71
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
less
const less: StylePreprocessor = (source, map, options, load = require) => { const nodeLess = load('less') let result: any let error: Error | null = null nodeLess.render( getSource(source, options.filename, options.additionalData), { ...options, syncImport: true }, (err: Error | null, output: any) => { error = err result = output }, ) if (error) return { code: '', errors: [error], dependencies: [] } const dependencies = result.imports if (map) { return { code: result.css.toString(), map: merge(map, result.map), errors: [], dependencies: dependencies, } } return { code: result.css.toString(), errors: [], dependencies: dependencies, } }
// .less
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-sfc/src/style/preprocessors.ts#L85-L115
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
styl
const styl: StylePreprocessor = (source, map, options, load = require) => { const nodeStylus = load('stylus') try { const ref = nodeStylus(source, options) if (map) ref.set('sourcemap', { inline: false, comment: false }) const result = ref.render() const dependencies = ref.deps() if (map) { return { code: result, map: merge(map, ref.sourcemap), errors: [], dependencies, } } return { code: result, errors: [], dependencies } } catch (e: any) { return { code: '', errors: [e], dependencies: [] } } }
// .styl
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-sfc/src/style/preprocessors.ts#L118-L139
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
parseUriParts
function parseUriParts(urlString: string): UrlWithStringQuery { // A TypeError is thrown if urlString is not a string // @see https://nodejs.org/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost return uriParse(isString(urlString) ? urlString : '', false, true) }
/** * vuejs/component-compiler-utils#22 Support uri fragment in transformed require * @param urlString - an url as a string */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-sfc/src/template/templateUtils.ts#L35-L39
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
compile
function compile(template: string | RootNode, options: CompilerOptions = {}) { let { code } = _compile(template, { ...options, mode: 'module', prefixIdentifiers: true, }) return code }
// TODO This is a temporary test case for initial implementation.
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-vapor/__tests__/compile.spec.ts#L8-L15
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
dedupeProperties
function dedupeProperties(results: DirectiveTransformResult[]): IRProp[] { const knownProps: Map<string, IRProp> = new Map() const deduped: IRProp[] = [] for (const result of results) { const prop = resolveDirectiveResult(result) // dynamic keys are always allowed if (!prop.key.isStatic) { deduped.push(prop) continue } const name = prop.key.content const existing = knownProps.get(name) if (existing) { if (name === 'style' || name === 'class') { mergePropValues(existing, prop) } // unexpected duplicate, should have emitted error during parse } else { knownProps.set(name, prop) deduped.push(prop) } } return deduped }
// Dedupe props in an object literal.
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-vapor/src/transforms/transformElement.ts#L403-L427
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
transformComponentSlot
function transformComponentSlot( node: ElementNode, dir: VaporDirectiveNode | undefined, context: TransformContext<ElementNode>, ) { const { children } = node const arg = dir && dir.arg const nonSlotTemplateChildren = children.filter( n => isNonWhitespaceContent(node) && !(n.type === NodeTypes.ELEMENT && n.props.some(isVSlot)), ) const [block, onExit] = createSlotBlock(node, dir, context) const { slots } = context return () => { onExit() const hasOtherSlots = !!slots.length if (dir && hasOtherSlots) { // already has on-component slot - this is incorrect usage. context.options.onError( createCompilerError(ErrorCodes.X_V_SLOT_MIXED_SLOT_USAGE, dir.loc), ) return } if (nonSlotTemplateChildren.length) { if (hasStaticSlot(slots, 'default')) { context.options.onError( createCompilerError( ErrorCodes.X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN, nonSlotTemplateChildren[0].loc, ), ) } else { registerSlot(slots, arg, block) context.slots = slots } } else if (hasOtherSlots) { context.slots = slots } } }
// <Foo v-slot:default>
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-vapor/src/transforms/vSlot.ts#L62-L107
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
transformTemplateSlot
function transformTemplateSlot( node: ElementNode, dir: VaporDirectiveNode, context: TransformContext<ElementNode>, ) { context.dynamic.flags |= DynamicFlag.NON_TEMPLATE const arg = dir.arg && resolveExpression(dir.arg) const vFor = findDir(node, 'for') const vIf = findDir(node, 'if') const vElse = findDir(node, /^else(-if)?$/, true /* allowEmpty */) const { slots } = context const [block, onExit] = createSlotBlock(node, dir, context) if (!vFor && !vIf && !vElse) { const slotName = arg ? arg.isStatic && arg.content : 'default' if (slotName && hasStaticSlot(slots, slotName)) { context.options.onError( createCompilerError(ErrorCodes.X_V_SLOT_DUPLICATE_SLOT_NAMES, dir.loc), ) } else { registerSlot(slots, arg, block) } } else if (vIf) { registerDynamicSlot(slots, { slotType: IRSlotType.CONDITIONAL, condition: vIf.exp!, positive: { slotType: IRSlotType.DYNAMIC, name: arg!, fn: block, }, }) } else if (vElse) { const vIfSlot = slots[slots.length - 1] as IRSlotDynamic if (vIfSlot.slotType === IRSlotType.CONDITIONAL) { let ifNode = vIfSlot while ( ifNode.negative && ifNode.negative.slotType === IRSlotType.CONDITIONAL ) ifNode = ifNode.negative const negative: IRSlotDynamicBasic | IRSlotDynamicConditional = vElse.exp ? { slotType: IRSlotType.CONDITIONAL, condition: vElse.exp, positive: { slotType: IRSlotType.DYNAMIC, name: arg!, fn: block, }, } : { slotType: IRSlotType.DYNAMIC, name: arg!, fn: block, } ifNode.negative = negative } else { context.options.onError( createCompilerError(ErrorCodes.X_V_ELSE_NO_ADJACENT_IF, vElse.loc), ) } } else if (vFor) { if (vFor.forParseResult) { registerDynamicSlot(slots, { slotType: IRSlotType.LOOP, name: arg!, fn: block, loop: vFor.forParseResult as IRFor, }) } else { context.options.onError( createCompilerError(ErrorCodes.X_V_FOR_MALFORMED_EXPRESSION, vFor.loc), ) } } return onExit }
// <template #foo>
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/compiler-vapor/src/transforms/vSlot.ts#L110-L189
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
Collection.every
every(foo: any, bar: any, baz: any) { expect(foo).toBe('foo') expect(bar).toBe('bar') expect(baz).toBe('baz') return super.every(obj => obj.id === foo) }
// @ts-expect-error
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/reactivity/__tests__/reactiveArray.spec.ts#L724-L729
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
Collection.filter
filter(foo: any, bar: any, baz: any) { expect(foo).toBe('foo') expect(bar).toBe('bar') expect(baz).toBe('baz') return super.filter(obj => obj.id === foo) }
// @ts-expect-error
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/reactivity/__tests__/reactiveArray.spec.ts#L732-L737
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
Collection.find
find(foo: any, bar: any, baz: any) { expect(foo).toBe('foo') expect(bar).toBe('bar') expect(baz).toBe('baz') return super.find(obj => obj.id === foo) }
// @ts-expect-error
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/reactivity/__tests__/reactiveArray.spec.ts#L740-L745
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
Collection.findIndex
findIndex(foo: any, bar: any, baz: any) { expect(foo).toBe('foo') expect(bar).toBe('bar') expect(baz).toBe('baz') return super.findIndex(obj => obj.id === bar) }
// @ts-expect-error
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/reactivity/__tests__/reactiveArray.spec.ts#L748-L753
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
Collection.forEach
forEach(foo: any, bar: any, baz: any) { expect(foo).toBe('foo') expect(bar).toBe('bar') expect(baz).toBe('baz') }
// @ts-expect-error
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/reactivity/__tests__/reactiveArray.spec.ts#L771-L775
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
Collection.map
map(foo: any, bar: any, baz: any) { expect(foo).toBe('foo') expect(bar).toBe('bar') expect(baz).toBe('baz') return super.map(obj => obj.value) }
// @ts-expect-error
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/reactivity/__tests__/reactiveArray.spec.ts#L778-L783
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
Collection.some
some(foo: any, bar: any, baz: any) { expect(foo).toBe('foo') expect(bar).toBe('bar') expect(baz).toBe('baz') return super.some(obj => obj.id === baz) }
// @ts-expect-error
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/reactivity/__tests__/reactiveArray.spec.ts#L786-L791
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
clamp
const clamp = (n: number, min: number, max: number) => Math.min(max, Math.max(min, n))
// useClamp from VueUse
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/reactivity/__tests__/watch.spec.ts#L238-L239
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
iterator
function iterator( self: unknown[], method: keyof Array<unknown>, wrapValue: (value: any) => unknown, ) { // note that taking ARRAY_ITERATE dependency here is not strictly equivalent // to calling iterate on the proxified array. // creating the iterator does not access any array property: // it is only when .next() is called that length and indexes are accessed. // pushed to the extreme, an iterator could be created in one effect scope, // partially iterated in another, then iterated more in yet another. // given that JS iterator can only be read once, this doesn't seem like // a plausible use-case, so this tracking simplification seems ok. const arr = shallowReadArray(self) const iter = (arr[method] as any)() as IterableIterator<unknown> & { _next: IterableIterator<unknown>['next'] } if (arr !== self && !isShallow(self)) { iter._next = iter.next iter.next = () => { const result = iter._next() if (result.value) { result.value = wrapValue(result.value) } return result } } return iter }
// instrument iterators to take ARRAY_ITERATE dependency
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/reactivity/src/arrayInstrumentations.ts#L197-L225
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
apply
function apply( self: unknown[], method: ArrayMethods, fn: (item: unknown, index: number, array: unknown[]) => unknown, thisArg?: unknown, wrappedRetFn?: (result: any) => unknown, args?: IArguments, ) { const arr = shallowReadArray(self) const needsWrap = arr !== self && !isShallow(self) // @ts-expect-error our code is limited to es2016 but user code is not const methodFn = arr[method] // #11759 // If the method being called is from a user-extended Array, the arguments will be unknown // (unknown order and unknown parameter types). In this case, we skip the shallowReadArray // handling and directly call apply with self. if (methodFn !== arrayProto[method as any]) { const result = methodFn.apply(self, args) return needsWrap ? toReactive(result) : result } let wrappedFn = fn if (arr !== self) { if (needsWrap) { wrappedFn = function (this: unknown, item, index) { return fn.call(this, toReactive(item), index, self) } } else if (fn.length > 2) { wrappedFn = function (this: unknown, item, index) { return fn.call(this, item, index, self) } } } const result = methodFn.call(arr, wrappedFn, thisArg) return needsWrap && wrappedRetFn ? wrappedRetFn(result) : result }
// instrument functions that read (potentially) all items
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/reactivity/src/arrayInstrumentations.ts#L234-L270
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
reduce
function reduce( self: unknown[], method: keyof Array<any>, fn: (acc: unknown, item: unknown, index: number, array: unknown[]) => unknown, args: unknown[], ) { const arr = shallowReadArray(self) let wrappedFn = fn if (arr !== self) { if (!isShallow(self)) { wrappedFn = function (this: unknown, acc, item, index) { return fn.call(this, acc, toReactive(item), index, self) } } else if (fn.length > 3) { wrappedFn = function (this: unknown, acc, item, index) { return fn.call(this, acc, item, index, self) } } } return (arr[method] as any)(wrappedFn, ...args) }
// instrument reduce and reduceRight to take ARRAY_ITERATE dependency
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/reactivity/src/arrayInstrumentations.ts#L273-L293
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
searchProxy
function searchProxy( self: unknown[], method: keyof Array<any>, args: unknown[], ) { const arr = toRaw(self) as any track(arr, TrackOpTypes.ITERATE, ARRAY_ITERATE_KEY) // we run the method using the original args first (which may be reactive) const res = arr[method](...args) // if that didn't work, run it again using raw values. if ((res === -1 || res === false) && isProxy(args[0])) { args[0] = toRaw(args[0]) return arr[method](...args) } return res }
// instrument identity-sensitive methods to account for reactive proxies
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/reactivity/src/arrayInstrumentations.ts#L296-L313
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
noTracking
function noTracking( self: unknown[], method: keyof Array<any>, args: unknown[] = [], ) { pauseTracking() startBatch() const res = (toRaw(self) as any)[method].apply(self, args) endBatch() resetTracking() return res }
// instrument length-altering mutation methods to avoid length being tracked
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/reactivity/src/arrayInstrumentations.ts#L317-L328
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
ComputedRefImpl.notify
notify(): true | void { this.flags |= EffectFlags.DIRTY if ( !(this.flags & EffectFlags.NOTIFIED) && // avoid infinite self recursion activeSub !== this ) { batch(this, true) return true } else if (__DEV__) { // TODO warn } }
/** * @internal */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/reactivity/src/computed.ts#L117-L129
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
ReactiveEffect.notify
notify(): void { if ( this.flags & EffectFlags.RUNNING && !(this.flags & EffectFlags.ALLOW_RECURSE) ) { return } if (!(this.flags & EffectFlags.NOTIFIED)) { batch(this) } }
/** * @internal */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/reactivity/src/effect.ts#L138-L148
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
ReactiveEffect.runIfDirty
runIfDirty(): void { if (isDirty(this)) { this.run() } }
/** * @internal */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/reactivity/src/effect.ts#L207-L211
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
EffectScope.resume
resume(): void { if (this._active) { if (this._isPaused) { this._isPaused = false let i, l if (this.scopes) { for (i = 0, l = this.scopes.length; i < l; i++) { this.scopes[i].resume() } } for (i = 0, l = this.effects.length; i < l; i++) { this.effects[i].resume() } } } }
/** * Resumes the effect scope, including all child scopes and effects. */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/reactivity/src/effectScope.ts#L71-L86
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
EffectScope.on
on(): void { this.prevScope = activeEffectScope activeEffectScope = this }
/** * This should only be called on non-detached scopes * @internal */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/reactivity/src/effectScope.ts#L107-L110
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
EffectScope.off
off(): void { activeEffectScope = this.prevScope }
/** * This should only be called on non-detached scopes * @internal */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/reactivity/src/effectScope.ts#L116-L118
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
slot
const slot = () => {}
// default slot
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/__tests__/h.spec.ts#L23-L23
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
job2
const job2 = () => calls.push('job2')
// job1 has no id
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/__tests__/scheduler.spec.ts#L473-L473
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
cb2
const cb2 = () => calls.push('cb2')
// cb1 has no id
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/__tests__/scheduler.spec.ts#L497-L497
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
cb
const cb: SchedulerJob = () => { if (count < 5) { count++ queuePostFlushCb(cb) } }
// post cb
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/__tests__/scheduler.spec.ts#L611-L616
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
job1
const job1 = () => { // @ts-expect-error job2.flags! |= SchedulerJobFlags.DISPOSED }
// simulate parent component that toggles child
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/__tests__/scheduler.spec.ts#L755-L758
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
job2
const job2 = () => spy()
// simulate child that's triggered by the same reactive change that
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/__tests__/scheduler.spec.ts#L761-L761
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
CompB
const CompB = ({ msg }: { msg: string }) => h(CompC, { msg })
// test HOC
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/__tests__/components/BaseTransition.spec.ts#L113-L113
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
mockPersistedHooks
function mockPersistedHooks() { const state = { show: true } const toggle = ref(true) const hooks: VNodeProps = { onVnodeBeforeMount(vnode) { vnode.transition!.beforeEnter(vnode.el!) }, onVnodeMounted(vnode) { vnode.transition!.enter(vnode.el!) }, onVnodeUpdated(vnode, oldVnode) { if (oldVnode.props!.id !== vnode.props!.id) { if (vnode.props!.id) { vnode.transition!.beforeEnter(vnode.el!) state.show = true vnode.transition!.enter(vnode.el!) } else { vnode.transition!.leave(vnode.el!, () => { state.show = false }) } } }, } return { state, toggle, hooks } }
// this is pretty much how v-show is implemented
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/__tests__/components/BaseTransition.spec.ts#L186-L211
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
defineAsyncComponent
function defineAsyncComponent<T extends ComponentOptions>( comp: T, delay: number = 0, ) { return { setup(props: any, { slots }: any) { const p = new Promise(resolve => { setTimeout(() => { resolve(() => h(comp, props, slots)) }, delay) }) // in Node 12, due to timer/nextTick mechanism change, we have to wait // an extra tick to avoid race conditions deps.push(p.then(() => Promise.resolve())) return p }, } }
// a simple async factory for testing purposes only.
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/__tests__/components/Suspense.spec.ts#L39-L56
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
baseCheckWarn
function baseCheckWarn( shouldWarn: boolean, children: RawSlots, props: SuspenseProps | null = null, ) { const Comp = { setup() { return () => h(Suspense, props, children) }, } const root = nodeOps.createElement('div') render(h(Comp), root) if (shouldWarn) { expect(`<Suspense> slots expect a single root node.`).toHaveBeenWarned() } else { expect( `<Suspense> slots expect a single root node.`, ).not.toHaveBeenWarned() } }
// base function to check if a combination of slots warns or not
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/__tests__/components/Suspense.spec.ts#L2166-L2187
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
warnRuntimeUsage
const warnRuntimeUsage = (method: string) => warn( `${method}() is a compiler-hint helper that is only usable inside ` + `<script setup> of a single file component. Its arguments should be ` + `compiled away and passing it at runtime has no effect.`, )
// dev only
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/src/apiSetupHelpers.ts#L36-L41
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
getSlotsProxy
function getSlotsProxy(instance: ComponentInternalInstance): Slots { return new Proxy(instance.slots, { get(target, key: string) { track(instance, TrackOpTypes.GET, '$slots') return target[key] }, }) }
/** * Dev-only */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/src/component.ts#L1110-L1117
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
inferFromRegistry
const inferFromRegistry = (registry: Record<string, any> | undefined) => { for (const key in registry) { if (registry[key] === Component) { return key } } }
// try to infer the name based on reverse resolution
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/src/component.ts#L1228-L1234
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
getType
function getType(ctor: Prop<any> | null): string { // Early return for null to avoid unnecessary computations if (ctor === null) { return 'null' } // Avoid using regex for common cases by checking the type directly if (typeof ctor === 'function') { // Using name property to avoid converting function to string return ctor.name || '' } else if (typeof ctor === 'object') { // Attempting to directly access constructor name if possible const name = ctor.constructor && ctor.constructor.name return name || '' } // Fallback for other types (though they're less likely to have meaningful names here) return '' }
// dev only
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/src/componentProps.ts#L627-L645
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
validateProps
function validateProps( rawProps: Data, props: Data, instance: ComponentInternalInstance, ) { const resolvedValues = toRaw(props) const options = instance.propsOptions[0] const camelizePropsKey = Object.keys(rawProps).map(key => camelize(key)) for (const key in options) { let opt = options[key] if (opt == null) continue validateProp( key, resolvedValues[key], opt, __DEV__ ? shallowReadonly(resolvedValues) : resolvedValues, !camelizePropsKey.includes(key), ) } }
/** * dev only */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/src/componentProps.ts#L650-L669
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
validateProp
function validateProp( name: string, value: unknown, prop: PropOptions, props: Data, isAbsent: boolean, ) { const { type, required, validator, skipCheck } = prop // required! if (required && isAbsent) { warn('Missing required prop: "' + name + '"') return } // missing but optional if (value == null && !required) { return } // type check if (type != null && type !== true && !skipCheck) { let isValid = false const types = isArray(type) ? type : [type] const expectedTypes = [] // value is valid as long as one of the specified types match for (let i = 0; i < types.length && !isValid; i++) { const { valid, expectedType } = assertType(value, types[i]) expectedTypes.push(expectedType || '') isValid = valid } if (!isValid) { warn(getInvalidTypeMessage(name, value, expectedTypes)) return } } // custom validator if (validator && !validator(value, props)) { warn('Invalid prop: custom validator check failed for prop "' + name + '".') } }
/** * dev only */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/src/componentProps.ts#L674-L711
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
assertType
function assertType( value: unknown, type: PropConstructor | null, ): AssertionResult { let valid const expectedType = getType(type) if (expectedType === 'null') { valid = value === null } else if (isSimpleType(expectedType)) { const t = typeof value valid = t === expectedType.toLowerCase() // for primitive wrapper objects if (!valid && t === 'object') { valid = value instanceof (type as PropConstructor) } } else if (expectedType === 'Object') { valid = isObject(value) } else if (expectedType === 'Array') { valid = isArray(value) } else { valid = value instanceof (type as PropConstructor) } return { valid, expectedType, } }
/** * dev only */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/src/componentProps.ts#L725-L751
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
getInvalidTypeMessage
function getInvalidTypeMessage( name: string, value: unknown, expectedTypes: string[], ): string { if (expectedTypes.length === 0) { return ( `Prop type [] for prop "${name}" won't match anything.` + ` Did you mean to use type Array instead?` ) } let message = `Invalid prop: type check failed for prop "${name}".` + ` Expected ${expectedTypes.map(capitalize).join(' | ')}` const expectedType = expectedTypes[0] const receivedType = toRawType(value) const expectedValue = styleValue(value, expectedType) const receivedValue = styleValue(value, receivedType) // check if we need to specify expected value if ( expectedTypes.length === 1 && isExplicable(expectedType) && !isBoolean(expectedType, receivedType) ) { message += ` with value ${expectedValue}` } message += `, got ${receivedType} ` // check if we need to specify received value if (isExplicable(receivedType)) { message += `with value ${receivedValue}.` } return message }
/** * dev only */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/src/componentProps.ts#L756-L788
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
styleValue
function styleValue(value: unknown, type: string): string { if (type === 'String') { return `"${value}"` } else if (type === 'Number') { return `${Number(value)}` } else { return `${value}` } }
/** * dev only */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/src/componentProps.ts#L793-L801
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
isExplicable
function isExplicable(type: string): boolean { const explicitTypes = ['string', 'number', 'boolean'] return explicitTypes.some(elem => type.toLowerCase() === elem) }
/** * dev only */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/src/componentProps.ts#L806-L809
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
isBoolean
function isBoolean(...args: string[]): boolean { return args.some(elem => elem.toLowerCase() === 'boolean') }
/** * dev only */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/src/componentProps.ts#L814-L816
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
getPublicInstance
const getPublicInstance = ( i: ComponentInternalInstance | null, ): ComponentPublicInstance | ComponentInternalInstance['exposed'] | null => { if (!i) return null if (isStatefulComponent(i)) return getComponentPublicInstance(i) return getPublicInstance(i.parent) }
/** * #2437 In Vue 3, functional components do not have a public instance proxy but * they exist in the internal parent chain. For code that relies on traversing * public $parent chains, skip functional ones and go to the parent instead. */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/src/componentPublicInstance.ts#L357-L363
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
getChildRoot
const getChildRoot = (vnode: VNode): [VNode, SetRootFn] => { const rawChildren = vnode.children as VNodeArrayChildren const dynamicChildren = vnode.dynamicChildren const childRoot = filterSingleRoot(rawChildren, false) if (!childRoot) { return [vnode, undefined] } else if ( __DEV__ && childRoot.patchFlag > 0 && childRoot.patchFlag & PatchFlags.DEV_ROOT_FRAGMENT ) { return getChildRoot(childRoot) } const index = rawChildren.indexOf(childRoot) const dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1 const setRoot: SetRootFn = (updatedRoot: VNode) => { rawChildren[index] = updatedRoot if (dynamicChildren) { if (dynamicIndex > -1) { dynamicChildren[dynamicIndex] = updatedRoot } else if (updatedRoot.patchFlag > 0) { vnode.dynamicChildren = [...dynamicChildren, updatedRoot] } } } return [normalizeVNode(childRoot), setRoot] }
/** * dev only * In dev mode, template root level comments are rendered, which turns the * template into a fragment root, but we need to locate the single element * root for attrs and scope id processing. */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/src/componentRenderUtils.ts#L276-L303
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
createDevtoolsComponentHook
function createDevtoolsComponentHook( hook: DevtoolsHooks, ): DevtoolsComponentHook { return (component: ComponentInternalInstance) => { emit( hook, component.appContext.app, component.uid, component.parent ? component.parent.uid : undefined, component, ) } }
/*! #__NO_SIDE_EFFECTS__ */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/src/devtools.ts#L129-L141
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
locateClosingAnchor
const locateClosingAnchor = ( node: Node | null, open = '[', close = ']', ): Node | null => { let match = 0 while (node) { node = nextSibling(node) if (node && isComment(node)) { if (node.data === open) match++ if (node.data === close) { if (match === 0) { return nextSibling(node) } else { match-- } } } } return node }
// looks ahead for a start and closing comment node
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/src/hydration.ts#L732-L752
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
propHasMismatch
function propHasMismatch( el: Element, key: string, clientValue: any, vnode: VNode, instance: ComponentInternalInstance | null, ): boolean { let mismatchType: MismatchTypes | undefined let mismatchKey: string | undefined let actual: string | boolean | null | undefined let expected: string | boolean | null | undefined if (key === 'class') { // classes might be in different order, but that doesn't affect cascade // so we just need to check if the class lists contain the same classes. actual = el.getAttribute('class') expected = normalizeClass(clientValue) if (!isSetEqual(toClassSet(actual || ''), toClassSet(expected))) { mismatchType = MismatchTypes.CLASS mismatchKey = `class` } } else if (key === 'style') { // style might be in different order, but that doesn't affect cascade actual = el.getAttribute('style') || '' expected = isString(clientValue) ? clientValue : stringifyStyle(normalizeStyle(clientValue)) const actualMap = toStyleMap(actual) const expectedMap = toStyleMap(expected) // If `v-show=false`, `display: 'none'` should be added to expected if (vnode.dirs) { for (const { dir, value } of vnode.dirs) { // @ts-expect-error only vShow has this internal name if (dir.name === 'show' && !value) { expectedMap.set('display', 'none') } } } if (instance) { resolveCssVars(instance, vnode, expectedMap) } if (!isMapEqual(actualMap, expectedMap)) { mismatchType = MismatchTypes.STYLE mismatchKey = 'style' } } else if ( (el instanceof SVGElement && isKnownSvgAttr(key)) || (el instanceof HTMLElement && (isBooleanAttr(key) || isKnownHtmlAttr(key))) ) { if (isBooleanAttr(key)) { actual = el.hasAttribute(key) expected = includeBooleanAttr(clientValue) } else if (clientValue == null) { actual = el.hasAttribute(key) expected = false } else { if (el.hasAttribute(key)) { actual = el.getAttribute(key) } else if (key === 'value' && el.tagName === 'TEXTAREA') { // #10000 textarea.value can't be retrieved by `hasAttribute` actual = (el as HTMLTextAreaElement).value } else { actual = false } expected = isRenderableAttrValue(clientValue) ? String(clientValue) : false } if (actual !== expected) { mismatchType = MismatchTypes.ATTRIBUTE mismatchKey = key } } if (mismatchType != null && !isMismatchAllowed(el, mismatchType)) { const format = (v: any) => v === false ? `(not rendered)` : `${mismatchKey}="${v}"` const preSegment = `Hydration ${MismatchTypeString[mismatchType]} mismatch on` const postSegment = `\n - rendered on server: ${format(actual)}` + `\n - expected on client: ${format(expected)}` + `\n Note: this mismatch is check-only. The DOM will not be rectified ` + `in production due to performance overhead.` + `\n You should fix the source of the mismatch.` if (__TEST__) { // during tests, log the full message in one single string for easier // debugging. warn(`${preSegment} ${el.tagName}${postSegment}`) } else { warn(preSegment, el, postSegment) } return true } return false }
/** * Dev only */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/src/hydration.ts#L788-L883
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
baseCreateRenderer
function baseCreateRenderer( options: RendererOptions, createHydrationFns?: typeof createHydrationFunctions, ): any { // compile-time feature flags check if (__ESM_BUNDLER__ && !__TEST__) { initFeatureFlags() } const target = getGlobalThis() target.__VUE__ = true if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) { setDevtoolsHook(target.__VUE_DEVTOOLS_GLOBAL_HOOK__, target) } const { insert: hostInsert, remove: hostRemove, patchProp: hostPatchProp, createElement: hostCreateElement, createText: hostCreateText, createComment: hostCreateComment, setText: hostSetText, setElementText: hostSetElementText, parentNode: hostParentNode, nextSibling: hostNextSibling, setScopeId: hostSetScopeId = NOOP, insertStaticContent: hostInsertStaticContent, } = options // Note: functions inside this closure should use `const xxx = () => {}` // style in order to prevent being inlined by minifiers. const patch: PatchFn = ( n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, namespace = undefined, slotScopeIds = null, optimized = __DEV__ && isHmrUpdating ? false : !!n2.dynamicChildren, ) => { if (n1 === n2) { return } // patching & not same type, unmount old tree if (n1 && !isSameVNodeType(n1, n2)) { anchor = getNextHostNode(n1) unmount(n1, parentComponent, parentSuspense, true) n1 = null } if (n2.patchFlag === PatchFlags.BAIL) { optimized = false n2.dynamicChildren = null } const { type, ref, shapeFlag } = n2 switch (type) { case Text: processText(n1, n2, container, anchor) break case Comment: processCommentNode(n1, n2, container, anchor) break case Static: if (n1 == null) { mountStaticNode(n2, container, anchor, namespace) } else if (__DEV__) { patchStaticNode(n1, n2, container, namespace) } break case Fragment: processFragment( n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, ) break default: if (shapeFlag & ShapeFlags.ELEMENT) { processElement( n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, ) } else if (shapeFlag & ShapeFlags.COMPONENT) { processComponent( n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, ) } else if (shapeFlag & ShapeFlags.TELEPORT) { ;(type as typeof TeleportImpl).process( n1 as TeleportVNode, n2 as TeleportVNode, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, internals, ) } else if (__FEATURE_SUSPENSE__ && shapeFlag & ShapeFlags.SUSPENSE) { ;(type as typeof SuspenseImpl).process( n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, internals, ) } else if (__DEV__) { warn('Invalid VNode type:', type, `(${typeof type})`) } } // set ref if (ref != null && parentComponent) { setRef(ref, n1 && n1.ref, parentSuspense, n2 || n1, !n2) } } const processText: ProcessTextOrCommentFn = (n1, n2, container, anchor) => { if (n1 == null) { hostInsert( (n2.el = hostCreateText(n2.children as string)), container, anchor, ) } else { const el = (n2.el = n1.el!) if (n2.children !== n1.children) { hostSetText(el, n2.children as string) } } } const processCommentNode: ProcessTextOrCommentFn = ( n1, n2, container, anchor, ) => { if (n1 == null) { hostInsert( (n2.el = hostCreateComment((n2.children as string) || '')), container, anchor, ) } else { // there's no support for dynamic comments n2.el = n1.el } } const mountStaticNode = ( n2: VNode, container: RendererElement, anchor: RendererNode | null, namespace: ElementNamespace, ) => { // static nodes are only present when used with compiler-dom/runtime-dom // which guarantees presence of hostInsertStaticContent. ;[n2.el, n2.anchor] = hostInsertStaticContent!( n2.children as string, container, anchor, namespace, n2.el, n2.anchor, ) } /** * Dev / HMR only */ const patchStaticNode = ( n1: VNode, n2: VNode, container: RendererElement, namespace: ElementNamespace, ) => { // static nodes are only patched during dev for HMR if (n2.children !== n1.children) { const anchor = hostNextSibling(n1.anchor!) // remove existing removeStaticNode(n1) // insert new ;[n2.el, n2.anchor] = hostInsertStaticContent!( n2.children as string, container, anchor, namespace, ) } else { n2.el = n1.el n2.anchor = n1.anchor } } const moveStaticNode = ( { el, anchor }: VNode, container: RendererElement, nextSibling: RendererNode | null, ) => { let next while (el && el !== anchor) { next = hostNextSibling(el) hostInsert(el, container, nextSibling) el = next } hostInsert(anchor!, container, nextSibling) } const removeStaticNode = ({ el, anchor }: VNode) => { let next while (el && el !== anchor) { next = hostNextSibling(el) hostRemove(el) el = next } hostRemove(anchor!) } const processElement = ( n1: VNode | null, n2: VNode, container: RendererElement, anchor: RendererNode | null, parentComponent: ComponentInternalInstance | null, parentSuspense: SuspenseBoundary | null, namespace: ElementNamespace, slotScopeIds: string[] | null, optimized: boolean, ) => { if (n2.type === 'svg') { namespace = 'svg' } else if (n2.type === 'math') { namespace = 'mathml' } if (n1 == null) { mountElement( n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, ) } else { patchElement( n1, n2, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, ) } } const mountElement = ( vnode: VNode, container: RendererElement, anchor: RendererNode | null, parentComponent: ComponentInternalInstance | null, parentSuspense: SuspenseBoundary | null, namespace: ElementNamespace, slotScopeIds: string[] | null, optimized: boolean, ) => { let el: RendererElement let vnodeHook: VNodeHook | undefined | null const { props, shapeFlag, transition, dirs } = vnode el = vnode.el = hostCreateElement( vnode.type as string, namespace, props && props.is, props, ) // mount children first, since some props may rely on child content // being already rendered, e.g. `<select value>` if (shapeFlag & ShapeFlags.TEXT_CHILDREN) { hostSetElementText(el, vnode.children as string) } else if (shapeFlag & ShapeFlags.ARRAY_CHILDREN) { mountChildren( vnode.children as VNodeArrayChildren, el, null, parentComponent, parentSuspense, resolveChildrenNamespace(vnode, namespace), slotScopeIds, optimized, ) } if (dirs) { invokeDirectiveHook(vnode, null, parentComponent, 'created') } // scopeId setScopeId(el, vnode, vnode.scopeId, slotScopeIds, parentComponent) // props if (props) { for (const key in props) { if (key !== 'value' && !isReservedProp(key)) { hostPatchProp(el, key, null, props[key], namespace, parentComponent) } } /** * Special case for setting value on DOM elements: * - it can be order-sensitive (e.g. should be set *after* min/max, #2325, #4024) * - it needs to be forced (#1471) * #2353 proposes adding another renderer option to configure this, but * the properties affects are so finite it is worth special casing it * here to reduce the complexity. (Special casing it also should not * affect non-DOM renderers) */ if ('value' in props) { hostPatchProp(el, 'value', null, props.value, namespace) } if ((vnodeHook = props.onVnodeBeforeMount)) { invokeVNodeHook(vnodeHook, parentComponent, vnode) } } if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) { def(el, '__vnode', vnode, true) def(el, '__vueParentComponent', parentComponent, true) } if (dirs) { invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount') } // #1583 For inside suspense + suspense not resolved case, enter hook should call when suspense resolved // #1689 For inside suspense + suspense resolved case, just call it const needCallTransitionHooks = needTransition(parentSuspense, transition) if (needCallTransitionHooks) { transition!.beforeEnter(el) } hostInsert(el, container, anchor) if ( (vnodeHook = props && props.onVnodeMounted) || needCallTransitionHooks || dirs ) { queuePostRenderEffect(() => { vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode) needCallTransitionHooks && transition!.enter(el) dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted') }, parentSuspense) } } const setScopeId = ( el: RendererElement, vnode: VNode, scopeId: string | null, slotScopeIds: string[] | null, parentComponent: ComponentInternalInstance | null, ) => { if (scopeId) { hostSetScopeId(el, scopeId) } if (slotScopeIds) { for (let i = 0; i < slotScopeIds.length; i++) { hostSetScopeId(el, slotScopeIds[i]) } } if (parentComponent) { let subTree = parentComponent.subTree if ( __DEV__ && subTree.patchFlag > 0 && subTree.patchFlag & PatchFlags.DEV_ROOT_FRAGMENT ) { subTree = filterSingleRoot(subTree.children as VNodeArrayChildren) || subTree } if ( vnode === subTree || (isSuspense(subTree.type) && (subTree.ssContent === vnode || subTree.ssFallback === vnode)) ) { const parentVNode = parentComponent.vnode setScopeId( el, parentVNode, parentVNode.scopeId, parentVNode.slotScopeIds, parentComponent.parent, ) } } } const mountChildren: MountChildrenFn = ( children, container, anchor, parentComponent, parentSuspense, namespace: ElementNamespace, slotScopeIds, optimized, start = 0, ) => { for (let i = start; i < children.length; i++) { const child = (children[i] = optimized ? cloneIfMounted(children[i] as VNode) : normalizeVNode(children[i])) patch( null, child, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, ) } } const patchElement = ( n1: VNode, n2: VNode, parentComponent: ComponentInternalInstance | null, parentSuspense: SuspenseBoundary | null, namespace: ElementNamespace, slotScopeIds: string[] | null, optimized: boolean, ) => { const el = (n2.el = n1.el!) if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) { el.__vnode = n2 } let { patchFlag, dynamicChildren, dirs } = n2 // #1426 take the old vnode's patch flag into account since user may clone a // compiler-generated vnode, which de-opts to FULL_PROPS patchFlag |= n1.patchFlag & PatchFlags.FULL_PROPS const oldProps = n1.props || EMPTY_OBJ const newProps = n2.props || EMPTY_OBJ let vnodeHook: VNodeHook | undefined | null // disable recurse in beforeUpdate hooks parentComponent && toggleRecurse(parentComponent, false) if ((vnodeHook = newProps.onVnodeBeforeUpdate)) { invokeVNodeHook(vnodeHook, parentComponent, n2, n1) } if (dirs) { invokeDirectiveHook(n2, n1, parentComponent, 'beforeUpdate') } parentComponent && toggleRecurse(parentComponent, true) if (__DEV__ && isHmrUpdating) { // HMR updated, force full diff patchFlag = 0 optimized = false dynamicChildren = null } // #9135 innerHTML / textContent unset needs to happen before possible // new children mount if ( (oldProps.innerHTML && newProps.innerHTML == null) || (oldProps.textContent && newProps.textContent == null) ) { hostSetElementText(el, '') } if (dynamicChildren) { patchBlockChildren( n1.dynamicChildren!, dynamicChildren, el, parentComponent, parentSuspense, resolveChildrenNamespace(n2, namespace), slotScopeIds, ) if (__DEV__) { // necessary for HMR traverseStaticChildren(n1, n2) } } else if (!optimized) { // full diff patchChildren( n1, n2, el, null, parentComponent, parentSuspense, resolveChildrenNamespace(n2, namespace), slotScopeIds, false, ) } if (patchFlag > 0) { // the presence of a patchFlag means this element's render code was // generated by the compiler and can take the fast path. // in this path old node and new node are guaranteed to have the same shape // (i.e. at the exact same position in the source template) if (patchFlag & PatchFlags.FULL_PROPS) { // element props contain dynamic keys, full diff needed patchProps(el, oldProps, newProps, parentComponent, namespace) } else { // class // this flag is matched when the element has dynamic class bindings. if (patchFlag & PatchFlags.CLASS) { if (oldProps.class !== newProps.class) { hostPatchProp(el, 'class', null, newProps.class, namespace) } } // style // this flag is matched when the element has dynamic style bindings if (patchFlag & PatchFlags.STYLE) { hostPatchProp(el, 'style', oldProps.style, newProps.style, namespace) } // props // This flag is matched when the element has dynamic prop/attr bindings // other than class and style. The keys of dynamic prop/attrs are saved for // faster iteration. // Note dynamic keys like :[foo]="bar" will cause this optimization to // bail out and go through a full diff because we need to unset the old key if (patchFlag & PatchFlags.PROPS) { // if the flag is present then dynamicProps must be non-null const propsToUpdate = n2.dynamicProps! for (let i = 0; i < propsToUpdate.length; i++) { const key = propsToUpdate[i] const prev = oldProps[key] const next = newProps[key] // #1471 force patch value if (next !== prev || key === 'value') { hostPatchProp(el, key, prev, next, namespace, parentComponent) } } } } // text // This flag is matched when the element has only dynamic text children. if (patchFlag & PatchFlags.TEXT) { if (n1.children !== n2.children) { hostSetElementText(el, n2.children as string) } } } else if (!optimized && dynamicChildren == null) { // unoptimized, full diff patchProps(el, oldProps, newProps, parentComponent, namespace) } if ((vnodeHook = newProps.onVnodeUpdated) || dirs) { queuePostRenderEffect(() => { vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1) dirs && invokeDirectiveHook(n2, n1, parentComponent, 'updated') }, parentSuspense) } } // The fast path for blocks. const patchBlockChildren: PatchBlockChildrenFn = ( oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, namespace: ElementNamespace, slotScopeIds, ) => { for (let i = 0; i < newChildren.length; i++) { const oldVNode = oldChildren[i] const newVNode = newChildren[i] // Determine the container (parent element) for the patch. const container = // oldVNode may be an errored async setup() component inside Suspense // which will not have a mounted element oldVNode.el && // - In the case of a Fragment, we need to provide the actual parent // of the Fragment itself so it can move its children. (oldVNode.type === Fragment || // - In the case of different nodes, there is going to be a replacement // which also requires the correct parent container !isSameVNodeType(oldVNode, newVNode) || // - In the case of a component, it could contain anything. oldVNode.shapeFlag & (ShapeFlags.COMPONENT | ShapeFlags.TELEPORT)) ? hostParentNode(oldVNode.el)! : // In other cases, the parent container is not actually used so we // just pass the block element here to avoid a DOM parentNode call. fallbackContainer patch( oldVNode, newVNode, container, null, parentComponent, parentSuspense, namespace, slotScopeIds, true, ) } } const patchProps = ( el: RendererElement, oldProps: Data, newProps: Data, parentComponent: ComponentInternalInstance | null, namespace: ElementNamespace, ) => { if (oldProps !== newProps) { if (oldProps !== EMPTY_OBJ) { for (const key in oldProps) { if (!isReservedProp(key) && !(key in newProps)) { hostPatchProp( el, key, oldProps[key], null, namespace, parentComponent, ) } } } for (const key in newProps) { // empty string is not valid prop if (isReservedProp(key)) continue const next = newProps[key] const prev = oldProps[key] // defer patching value if (next !== prev && key !== 'value') { hostPatchProp(el, key, prev, next, namespace, parentComponent) } } if ('value' in newProps) { hostPatchProp(el, 'value', oldProps.value, newProps.value, namespace) } } } const processFragment = ( n1: VNode | null, n2: VNode, container: RendererElement, anchor: RendererNode | null, parentComponent: ComponentInternalInstance | null, parentSuspense: SuspenseBoundary | null, namespace: ElementNamespace, slotScopeIds: string[] | null, optimized: boolean, ) => { const fragmentStartAnchor = (n2.el = n1 ? n1.el : hostCreateText(''))! const fragmentEndAnchor = (n2.anchor = n1 ? n1.anchor : hostCreateText(''))! let { patchFlag, dynamicChildren, slotScopeIds: fragmentSlotScopeIds } = n2 if ( __DEV__ && // #5523 dev root fragment may inherit directives (isHmrUpdating || patchFlag & PatchFlags.DEV_ROOT_FRAGMENT) ) { // HMR updated / Dev root fragment (w/ comments), force full diff patchFlag = 0 optimized = false dynamicChildren = null } // check if this is a slot fragment with :slotted scope ids if (fragmentSlotScopeIds) { slotScopeIds = slotScopeIds ? slotScopeIds.concat(fragmentSlotScopeIds) : fragmentSlotScopeIds } if (n1 == null) { hostInsert(fragmentStartAnchor, container, anchor) hostInsert(fragmentEndAnchor, container, anchor) // a fragment can only have array children // since they are either generated by the compiler, or implicitly created // from arrays. mountChildren( // #10007 // such fragment like `<></>` will be compiled into // a fragment which doesn't have a children. // In this case fallback to an empty array (n2.children || []) as VNodeArrayChildren, container, fragmentEndAnchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, ) } else { if ( patchFlag > 0 && patchFlag & PatchFlags.STABLE_FRAGMENT && dynamicChildren && // #2715 the previous fragment could've been a BAILed one as a result // of renderSlot() with no valid children n1.dynamicChildren ) { // a stable fragment (template root or <template v-for>) doesn't need to // patch children order, but it may contain dynamicChildren. patchBlockChildren( n1.dynamicChildren, dynamicChildren, container, parentComponent, parentSuspense, namespace, slotScopeIds, ) if (__DEV__) { // necessary for HMR traverseStaticChildren(n1, n2) } else if ( // #2080 if the stable fragment has a key, it's a <template v-for> that may // get moved around. Make sure all root level vnodes inherit el. // #2134 or if it's a component root, it may also get moved around // as the component is being moved. n2.key != null || (parentComponent && n2 === parentComponent.subTree) ) { traverseStaticChildren(n1, n2, true /* shallow */) } } else { // keyed / unkeyed, or manual fragments. // for keyed & unkeyed, since they are compiler generated from v-for, // each child is guaranteed to be a block so the fragment will never // have dynamicChildren. patchChildren( n1, n2, container, fragmentEndAnchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, ) } } } const processComponent = ( n1: VNode | null, n2: VNode, container: RendererElement, anchor: RendererNode | null, parentComponent: ComponentInternalInstance | null, parentSuspense: SuspenseBoundary | null, namespace: ElementNamespace, slotScopeIds: string[] | null, optimized: boolean, ) => { n2.slotScopeIds = slotScopeIds if (n1 == null) { if (n2.shapeFlag & ShapeFlags.COMPONENT_KEPT_ALIVE) { ;(parentComponent!.ctx as KeepAliveContext).activate( n2, container, anchor, namespace, optimized, ) } else { mountComponent( n2, container, anchor, parentComponent, parentSuspense, namespace, optimized, ) } } else { updateComponent(n1, n2, optimized) } } const mountComponent: MountComponentFn = ( initialVNode, container, anchor, parentComponent, parentSuspense, namespace: ElementNamespace, optimized, ) => { // 2.x compat may pre-create the component instance before actually // mounting const compatMountInstance = __COMPAT__ && initialVNode.isCompatRoot && initialVNode.component const instance: ComponentInternalInstance = compatMountInstance || (initialVNode.component = createComponentInstance( initialVNode, parentComponent, parentSuspense, )) if (__DEV__ && instance.type.__hmrId) { registerHMR(instance) } if (__DEV__) { pushWarningContext(initialVNode) startMeasure(instance, `mount`) } // inject renderer internals for keepAlive if (isKeepAlive(initialVNode)) { ;(instance.ctx as KeepAliveContext).renderer = internals } // resolve props and slots for setup context if (!(__COMPAT__ && compatMountInstance)) { if (__DEV__) { startMeasure(instance, `init`) } setupComponent(instance, false, optimized) if (__DEV__) { endMeasure(instance, `init`) } } // setup() is async. This component relies on async logic to be resolved // before proceeding if (__FEATURE_SUSPENSE__ && instance.asyncDep) { // avoid hydration for hmr updating if (__DEV__ && isHmrUpdating) initialVNode.el = null parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect, optimized) // Give it a placeholder if this is not hydration // TODO handle self-defined fallback if (!initialVNode.el) { const placeholder = (instance.subTree = createVNode(Comment)) processCommentNode(null, placeholder, container!, anchor) } } else { setupRenderEffect( instance, initialVNode, container, anchor, parentSuspense, namespace, optimized, ) } if (__DEV__) { popWarningContext() endMeasure(instance, `mount`) } } const updateComponent = (n1: VNode, n2: VNode, optimized: boolean) => { const instance = (n2.component = n1.component)! if (shouldUpdateComponent(n1, n2, optimized)) { if ( __FEATURE_SUSPENSE__ && instance.asyncDep && !instance.asyncResolved ) { // async & still pending - just update props and slots // since the component's reactive effect for render isn't set-up yet if (__DEV__) { pushWarningContext(n2) } updateComponentPreRender(instance, n2, optimized) if (__DEV__) { popWarningContext() } return } else { // normal update instance.next = n2 // instance.update is the reactive effect. instance.update() } } else { // no update needed. just copy over properties n2.el = n1.el instance.vnode = n2 } } const setupRenderEffect: SetupRenderEffectFn = ( instance, initialVNode, container, anchor, parentSuspense, namespace: ElementNamespace, optimized, ) => { const componentUpdateFn = () => { if (!instance.isMounted) { let vnodeHook: VNodeHook | null | undefined const { el, props } = initialVNode const { bm, m, parent, root, type } = instance const isAsyncWrapperVNode = isAsyncWrapper(initialVNode) toggleRecurse(instance, false) // beforeMount hook if (bm) { invokeArrayFns(bm) } // onVnodeBeforeMount if ( !isAsyncWrapperVNode && (vnodeHook = props && props.onVnodeBeforeMount) ) { invokeVNodeHook(vnodeHook, parent, initialVNode) } if ( __COMPAT__ && isCompatEnabled(DeprecationTypes.INSTANCE_EVENT_HOOKS, instance) ) { instance.emit('hook:beforeMount') } toggleRecurse(instance, true) if (el && hydrateNode) { // vnode has adopted host node - perform hydration instead of mount. const hydrateSubTree = () => { if (__DEV__) { startMeasure(instance, `render`) } instance.subTree = renderComponentRoot(instance) if (__DEV__) { endMeasure(instance, `render`) } if (__DEV__) { startMeasure(instance, `hydrate`) } hydrateNode!( el as Node, instance.subTree, instance, parentSuspense, null, ) if (__DEV__) { endMeasure(instance, `hydrate`) } } if ( isAsyncWrapperVNode && (type as ComponentOptions).__asyncHydrate ) { ;(type as ComponentOptions).__asyncHydrate!( el as Element, instance, hydrateSubTree, ) } else { hydrateSubTree() } } else { // custom element style injection if (root.ce) { root.ce._injectChildStyle(type) } if (__DEV__) { startMeasure(instance, `render`) } const subTree = (instance.subTree = renderComponentRoot(instance)) if (__DEV__) { endMeasure(instance, `render`) } if (__DEV__) { startMeasure(instance, `patch`) } patch( null, subTree, container, anchor, instance, parentSuspense, namespace, ) if (__DEV__) { endMeasure(instance, `patch`) } initialVNode.el = subTree.el } // mounted hook if (m) { queuePostRenderEffect(m, parentSuspense) } // onVnodeMounted if ( !isAsyncWrapperVNode && (vnodeHook = props && props.onVnodeMounted) ) { const scopedInitialVNode = initialVNode queuePostRenderEffect( () => invokeVNodeHook(vnodeHook!, parent, scopedInitialVNode), parentSuspense, ) } if ( __COMPAT__ && isCompatEnabled(DeprecationTypes.INSTANCE_EVENT_HOOKS, instance) ) { queuePostRenderEffect( () => instance.emit('hook:mounted'), parentSuspense, ) } // activated hook for keep-alive roots. // #1742 activated hook must be accessed after first render // since the hook may be injected by a child keep-alive if ( initialVNode.shapeFlag & ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE || (parent && isAsyncWrapper(parent.vnode) && parent.vnode.shapeFlag & ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE) ) { instance.a && queuePostRenderEffect(instance.a, parentSuspense) if ( __COMPAT__ && isCompatEnabled(DeprecationTypes.INSTANCE_EVENT_HOOKS, instance) ) { queuePostRenderEffect( () => instance.emit('hook:activated'), parentSuspense, ) } } instance.isMounted = true if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) { devtoolsComponentAdded(instance) } // #2458: deference mount-only object parameters to prevent memleaks initialVNode = container = anchor = null as any } else { let { next, bu, u, parent, vnode } = instance if (__FEATURE_SUSPENSE__) { const nonHydratedAsyncRoot = locateNonHydratedAsyncRoot(instance) // we are trying to update some async comp before hydration // this will cause crash because we don't know the root node yet if (nonHydratedAsyncRoot) { // only sync the properties and abort the rest of operations if (next) { next.el = vnode.el updateComponentPreRender(instance, next, optimized) } // and continue the rest of operations once the deps are resolved nonHydratedAsyncRoot.asyncDep!.then(() => { // the instance may be destroyed during the time period if (!instance.isUnmounted) { componentUpdateFn() } }) return } } // updateComponent // This is triggered by mutation of component's own state (next: null) // OR parent calling processComponent (next: VNode) let originNext = next let vnodeHook: VNodeHook | null | undefined if (__DEV__) { pushWarningContext(next || instance.vnode) } // Disallow component effect recursion during pre-lifecycle hooks. toggleRecurse(instance, false) if (next) { next.el = vnode.el updateComponentPreRender(instance, next, optimized) } else { next = vnode } // beforeUpdate hook if (bu) { invokeArrayFns(bu) } // onVnodeBeforeUpdate if ((vnodeHook = next.props && next.props.onVnodeBeforeUpdate)) { invokeVNodeHook(vnodeHook, parent, next, vnode) } if ( __COMPAT__ && isCompatEnabled(DeprecationTypes.INSTANCE_EVENT_HOOKS, instance) ) { instance.emit('hook:beforeUpdate') } toggleRecurse(instance, true) // render if (__DEV__) { startMeasure(instance, `render`) } const nextTree = renderComponentRoot(instance) if (__DEV__) { endMeasure(instance, `render`) } const prevTree = instance.subTree instance.subTree = nextTree if (__DEV__) { startMeasure(instance, `patch`) } patch( prevTree, nextTree, // parent may have changed if it's in a teleport hostParentNode(prevTree.el!)!, // anchor may have changed if it's in a fragment getNextHostNode(prevTree), instance, parentSuspense, namespace, ) if (__DEV__) { endMeasure(instance, `patch`) } next.el = nextTree.el if (originNext === null) { // self-triggered update. In case of HOC, update parent component // vnode el. HOC is indicated by parent instance's subTree pointing // to child component's vnode updateHOCHostEl(instance, nextTree.el) } // updated hook if (u) { queuePostRenderEffect(u, parentSuspense) } // onVnodeUpdated if ((vnodeHook = next.props && next.props.onVnodeUpdated)) { queuePostRenderEffect( () => invokeVNodeHook(vnodeHook!, parent, next!, vnode), parentSuspense, ) } if ( __COMPAT__ && isCompatEnabled(DeprecationTypes.INSTANCE_EVENT_HOOKS, instance) ) { queuePostRenderEffect( () => instance.emit('hook:updated'), parentSuspense, ) } if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) { devtoolsComponentUpdated(instance) } if (__DEV__) { popWarningContext() } } } // create reactive effect for rendering instance.scope.on() const effect = (instance.effect = new ReactiveEffect(componentUpdateFn)) instance.scope.off() const update = (instance.update = effect.run.bind(effect)) const job: SchedulerJob = (instance.job = effect.runIfDirty.bind(effect)) job.i = instance job.id = instance.uid effect.scheduler = () => queueJob(job) // allowRecurse // #1801, #2043 component render effects should allow recursive updates toggleRecurse(instance, true) if (__DEV__) { effect.onTrack = instance.rtc ? e => invokeArrayFns(instance.rtc!, e) : void 0 effect.onTrigger = instance.rtg ? e => invokeArrayFns(instance.rtg!, e) : void 0 } update() } const updateComponentPreRender = ( instance: ComponentInternalInstance, nextVNode: VNode, optimized: boolean, ) => { nextVNode.component = instance const prevProps = instance.vnode.props instance.vnode = nextVNode instance.next = null updateProps(instance, nextVNode.props, prevProps, optimized) updateSlots(instance, nextVNode.children, optimized) pauseTracking() // props update may have triggered pre-flush watchers. // flush them before the render update. flushPreFlushCbs(instance) resetTracking() } const patchChildren: PatchChildrenFn = ( n1, n2, container, anchor, parentComponent, parentSuspense, namespace: ElementNamespace, slotScopeIds, optimized = false, ) => { const c1 = n1 && n1.children const prevShapeFlag = n1 ? n1.shapeFlag : 0 const c2 = n2.children const { patchFlag, shapeFlag } = n2 // fast path if (patchFlag > 0) { if (patchFlag & PatchFlags.KEYED_FRAGMENT) { // this could be either fully-keyed or mixed (some keyed some not) // presence of patchFlag means children are guaranteed to be arrays patchKeyedChildren( c1 as VNode[], c2 as VNodeArrayChildren, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, ) return } else if (patchFlag & PatchFlags.UNKEYED_FRAGMENT) { // unkeyed patchUnkeyedChildren( c1 as VNode[], c2 as VNodeArrayChildren, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, ) return } } // children has 3 possibilities: text, array or no children. if (shapeFlag & ShapeFlags.TEXT_CHILDREN) { // text children fast path if (prevShapeFlag & ShapeFlags.ARRAY_CHILDREN) { unmountChildren(c1 as VNode[], parentComponent, parentSuspense) } if (c2 !== c1) { hostSetElementText(container, c2 as string) } } else { if (prevShapeFlag & ShapeFlags.ARRAY_CHILDREN) { // prev children was array if (shapeFlag & ShapeFlags.ARRAY_CHILDREN) { // two arrays, cannot assume anything, do full diff patchKeyedChildren( c1 as VNode[], c2 as VNodeArrayChildren, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, ) } else { // no new children, just unmount old unmountChildren(c1 as VNode[], parentComponent, parentSuspense, true) } } else { // prev children was text OR null // new children is array OR null if (prevShapeFlag & ShapeFlags.TEXT_CHILDREN) { hostSetElementText(container, '') } // mount new if array if (shapeFlag & ShapeFlags.ARRAY_CHILDREN) { mountChildren( c2 as VNodeArrayChildren, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, ) } } } } const patchUnkeyedChildren = ( c1: VNode[], c2: VNodeArrayChildren, container: RendererElement, anchor: RendererNode | null, parentComponent: ComponentInternalInstance | null, parentSuspense: SuspenseBoundary | null, namespace: ElementNamespace, slotScopeIds: string[] | null, optimized: boolean, ) => { c1 = c1 || EMPTY_ARR c2 = c2 || EMPTY_ARR const oldLength = c1.length const newLength = c2.length const commonLength = Math.min(oldLength, newLength) let i for (i = 0; i < commonLength; i++) { const nextChild = (c2[i] = optimized ? cloneIfMounted(c2[i] as VNode) : normalizeVNode(c2[i])) patch( c1[i], nextChild, container, null, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, ) } if (oldLength > newLength) { // remove old unmountChildren( c1, parentComponent, parentSuspense, true, false, commonLength, ) } else { // mount new mountChildren( c2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, commonLength, ) } } // can be all-keyed or mixed const patchKeyedChildren = ( c1: VNode[], c2: VNodeArrayChildren, container: RendererElement, parentAnchor: RendererNode | null, parentComponent: ComponentInternalInstance | null, parentSuspense: SuspenseBoundary | null, namespace: ElementNamespace, slotScopeIds: string[] | null, optimized: boolean, ) => { let i = 0 const l2 = c2.length let e1 = c1.length - 1 // prev ending index let e2 = l2 - 1 // next ending index // 1. sync from start // (a b) c // (a b) d e while (i <= e1 && i <= e2) { const n1 = c1[i] const n2 = (c2[i] = optimized ? cloneIfMounted(c2[i] as VNode) : normalizeVNode(c2[i])) if (isSameVNodeType(n1, n2)) { patch( n1, n2, container, null, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, ) } else { break } i++ } // 2. sync from end // a (b c) // d e (b c) while (i <= e1 && i <= e2) { const n1 = c1[e1] const n2 = (c2[e2] = optimized ? cloneIfMounted(c2[e2] as VNode) : normalizeVNode(c2[e2])) if (isSameVNodeType(n1, n2)) { patch( n1, n2, container, null, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, ) } else { break } e1-- e2-- } // 3. common sequence + mount // (a b) // (a b) c // i = 2, e1 = 1, e2 = 2 // (a b) // c (a b) // i = 0, e1 = -1, e2 = 0 if (i > e1) { if (i <= e2) { const nextPos = e2 + 1 const anchor = nextPos < l2 ? (c2[nextPos] as VNode).el : parentAnchor while (i <= e2) { patch( null, (c2[i] = optimized ? cloneIfMounted(c2[i] as VNode) : normalizeVNode(c2[i])), container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, ) i++ } } } // 4. common sequence + unmount // (a b) c // (a b) // i = 2, e1 = 2, e2 = 1 // a (b c) // (b c) // i = 0, e1 = 0, e2 = -1 else if (i > e2) { while (i <= e1) { unmount(c1[i], parentComponent, parentSuspense, true) i++ } } // 5. unknown sequence // [i ... e1 + 1]: a b [c d e] f g // [i ... e2 + 1]: a b [e d c h] f g // i = 2, e1 = 4, e2 = 5 else { const s1 = i // prev starting index const s2 = i // next starting index // 5.1 build key:index map for newChildren const keyToNewIndexMap: Map<PropertyKey, number> = new Map() for (i = s2; i <= e2; i++) { const nextChild = (c2[i] = optimized ? cloneIfMounted(c2[i] as VNode) : normalizeVNode(c2[i])) if (nextChild.key != null) { if (__DEV__ && keyToNewIndexMap.has(nextChild.key)) { warn( `Duplicate keys found during update:`, JSON.stringify(nextChild.key), `Make sure keys are unique.`, ) } keyToNewIndexMap.set(nextChild.key, i) } } // 5.2 loop through old children left to be patched and try to patch // matching nodes & remove nodes that are no longer present let j let patched = 0 const toBePatched = e2 - s2 + 1 let moved = false // used to track whether any node has moved let maxNewIndexSoFar = 0 // works as Map<newIndex, oldIndex> // Note that oldIndex is offset by +1 // and oldIndex = 0 is a special value indicating the new node has // no corresponding old node. // used for determining longest stable subsequence const newIndexToOldIndexMap = new Array(toBePatched) for (i = 0; i < toBePatched; i++) newIndexToOldIndexMap[i] = 0 for (i = s1; i <= e1; i++) { const prevChild = c1[i] if (patched >= toBePatched) { // all new children have been patched so this can only be a removal unmount(prevChild, parentComponent, parentSuspense, true) continue } let newIndex if (prevChild.key != null) { newIndex = keyToNewIndexMap.get(prevChild.key) } else { // key-less node, try to locate a key-less node of the same type for (j = s2; j <= e2; j++) { if ( newIndexToOldIndexMap[j - s2] === 0 && isSameVNodeType(prevChild, c2[j] as VNode) ) { newIndex = j break } } } if (newIndex === undefined) { unmount(prevChild, parentComponent, parentSuspense, true) } else { newIndexToOldIndexMap[newIndex - s2] = i + 1 if (newIndex >= maxNewIndexSoFar) { maxNewIndexSoFar = newIndex } else { moved = true } patch( prevChild, c2[newIndex] as VNode, container, null, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, ) patched++ } } // 5.3 move and mount // generate longest stable subsequence only when nodes have moved const increasingNewIndexSequence = moved ? getSequence(newIndexToOldIndexMap) : EMPTY_ARR j = increasingNewIndexSequence.length - 1 // looping backwards so that we can use last patched node as anchor for (i = toBePatched - 1; i >= 0; i--) { const nextIndex = s2 + i const nextChild = c2[nextIndex] as VNode const anchor = nextIndex + 1 < l2 ? (c2[nextIndex + 1] as VNode).el : parentAnchor if (newIndexToOldIndexMap[i] === 0) { // mount new patch( null, nextChild, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, ) } else if (moved) { // move if: // There is no stable subsequence (e.g. a reverse) // OR current node is not among the stable sequence if (j < 0 || i !== increasingNewIndexSequence[j]) { move(nextChild, container, anchor, MoveType.REORDER) } else { j-- } } } } } const move: MoveFn = ( vnode, container, anchor, moveType, parentSuspense = null, ) => { const { el, type, transition, children, shapeFlag } = vnode if (shapeFlag & ShapeFlags.COMPONENT) { move(vnode.component!.subTree, container, anchor, moveType) return } if (__FEATURE_SUSPENSE__ && shapeFlag & ShapeFlags.SUSPENSE) { vnode.suspense!.move(container, anchor, moveType) return } if (shapeFlag & ShapeFlags.TELEPORT) { ;(type as typeof TeleportImpl).move(vnode, container, anchor, internals) return } if (type === Fragment) { hostInsert(el!, container, anchor) for (let i = 0; i < (children as VNode[]).length; i++) { move((children as VNode[])[i], container, anchor, moveType) } hostInsert(vnode.anchor!, container, anchor) return } if (type === Static) { moveStaticNode(vnode, container, anchor) return } // single nodes const needTransition = moveType !== MoveType.REORDER && shapeFlag & ShapeFlags.ELEMENT && transition if (needTransition) { if (moveType === MoveType.ENTER) { transition!.beforeEnter(el!) hostInsert(el!, container, anchor) queuePostRenderEffect(() => transition!.enter(el!), parentSuspense) } else { const { leave, delayLeave, afterLeave } = transition! const remove = () => hostInsert(el!, container, anchor) const performLeave = () => { leave(el!, () => { remove() afterLeave && afterLeave() }) } if (delayLeave) { delayLeave(el!, remove, performLeave) } else { performLeave() } } } else { hostInsert(el!, container, anchor) } } const unmount: UnmountFn = ( vnode, parentComponent, parentSuspense, doRemove = false, optimized = false, ) => { const { type, props, ref, children, dynamicChildren, shapeFlag, patchFlag, dirs, cacheIndex, } = vnode if (patchFlag === PatchFlags.BAIL) { optimized = false } // unset ref if (ref != null) { setRef(ref, null, parentSuspense, vnode, true) } // #6593 should clean memo cache when unmount if (cacheIndex != null) { parentComponent!.renderCache[cacheIndex] = undefined } if (shapeFlag & ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE) { ;(parentComponent!.ctx as KeepAliveContext).deactivate(vnode) return } const shouldInvokeDirs = shapeFlag & ShapeFlags.ELEMENT && dirs const shouldInvokeVnodeHook = !isAsyncWrapper(vnode) let vnodeHook: VNodeHook | undefined | null if ( shouldInvokeVnodeHook && (vnodeHook = props && props.onVnodeBeforeUnmount) ) { invokeVNodeHook(vnodeHook, parentComponent, vnode) } if (shapeFlag & ShapeFlags.COMPONENT) { unmountComponent(vnode.component!, parentSuspense, doRemove) } else { if (__FEATURE_SUSPENSE__ && shapeFlag & ShapeFlags.SUSPENSE) { vnode.suspense!.unmount(parentSuspense, doRemove) return } if (shouldInvokeDirs) { invokeDirectiveHook(vnode, null, parentComponent, 'beforeUnmount') } if (shapeFlag & ShapeFlags.TELEPORT) { ;(vnode.type as typeof TeleportImpl).remove( vnode, parentComponent, parentSuspense, internals, doRemove, ) } else if ( dynamicChildren && // #5154 // when v-once is used inside a block, setBlockTracking(-1) marks the // parent block with hasOnce: true // so that it doesn't take the fast path during unmount - otherwise // components nested in v-once are never unmounted. !dynamicChildren.hasOnce && // #1153: fast path should not be taken for non-stable (v-for) fragments (type !== Fragment || (patchFlag > 0 && patchFlag & PatchFlags.STABLE_FRAGMENT)) ) { // fast path for block nodes: only need to unmount dynamic children. unmountChildren( dynamicChildren, parentComponent, parentSuspense, false, true, ) } else if ( (type === Fragment && patchFlag & (PatchFlags.KEYED_FRAGMENT | PatchFlags.UNKEYED_FRAGMENT)) || (!optimized && shapeFlag & ShapeFlags.ARRAY_CHILDREN) ) { unmountChildren(children as VNode[], parentComponent, parentSuspense) } if (doRemove) { remove(vnode) } } if ( (shouldInvokeVnodeHook && (vnodeHook = props && props.onVnodeUnmounted)) || shouldInvokeDirs ) { queuePostRenderEffect(() => { vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode) shouldInvokeDirs && invokeDirectiveHook(vnode, null, parentComponent, 'unmounted') }, parentSuspense) } } const remove: RemoveFn = vnode => { const { type, el, anchor, transition } = vnode if (type === Fragment) { if ( __DEV__ && vnode.patchFlag > 0 && vnode.patchFlag & PatchFlags.DEV_ROOT_FRAGMENT && transition && !transition.persisted ) { ;(vnode.children as VNode[]).forEach(child => { if (child.type === Comment) { hostRemove(child.el!) } else { remove(child) } }) } else { removeFragment(el!, anchor!) } return } if (type === Static) { removeStaticNode(vnode) return } const performRemove = () => { hostRemove(el!) if (transition && !transition.persisted && transition.afterLeave) { transition.afterLeave() } } if ( vnode.shapeFlag & ShapeFlags.ELEMENT && transition && !transition.persisted ) { const { leave, delayLeave } = transition const performLeave = () => leave(el!, performRemove) if (delayLeave) { delayLeave(vnode.el!, performRemove, performLeave) } else { performLeave() } } else { performRemove() } } const removeFragment = (cur: RendererNode, end: RendererNode) => { // For fragments, directly remove all contained DOM nodes. // (fragment child nodes cannot have transition) let next while (cur !== end) { next = hostNextSibling(cur)! hostRemove(cur) cur = next } hostRemove(end) } const unmountComponent = ( instance: ComponentInternalInstance, parentSuspense: SuspenseBoundary | null, doRemove?: boolean, ) => { if (__DEV__ && instance.type.__hmrId) { unregisterHMR(instance) } const { bum, scope, job, subTree, um, m, a } = instance invalidateMount(m) invalidateMount(a) // beforeUnmount hook if (bum) { invokeArrayFns(bum) } if ( __COMPAT__ && isCompatEnabled(DeprecationTypes.INSTANCE_EVENT_HOOKS, instance) ) { instance.emit('hook:beforeDestroy') } // stop effects in component scope scope.stop() // job may be null if a component is unmounted before its async // setup has resolved. if (job) { // so that scheduler will no longer invoke it job.flags! |= SchedulerJobFlags.DISPOSED unmount(subTree, instance, parentSuspense, doRemove) } // unmounted hook if (um) { queuePostRenderEffect(um, parentSuspense) } if ( __COMPAT__ && isCompatEnabled(DeprecationTypes.INSTANCE_EVENT_HOOKS, instance) ) { queuePostRenderEffect( () => instance.emit('hook:destroyed'), parentSuspense, ) } queuePostRenderEffect(() => { instance.isUnmounted = true }, parentSuspense) // A component with async dep inside a pending suspense is unmounted before // its async dep resolves. This should remove the dep from the suspense, and // cause the suspense to resolve immediately if that was the last dep. if ( __FEATURE_SUSPENSE__ && parentSuspense && parentSuspense.pendingBranch && !parentSuspense.isUnmounted && instance.asyncDep && !instance.asyncResolved && instance.suspenseId === parentSuspense.pendingId ) { parentSuspense.deps-- if (parentSuspense.deps === 0) { parentSuspense.resolve() } } if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) { devtoolsComponentRemoved(instance) } } const unmountChildren: UnmountChildrenFn = ( children, parentComponent, parentSuspense, doRemove = false, optimized = false, start = 0, ) => { for (let i = start; i < children.length; i++) { unmount(children[i], parentComponent, parentSuspense, doRemove, optimized) } } const getNextHostNode: NextFn = vnode => { if (vnode.shapeFlag & ShapeFlags.COMPONENT) { return getNextHostNode(vnode.component!.subTree) } if (__FEATURE_SUSPENSE__ && vnode.shapeFlag & ShapeFlags.SUSPENSE) { return vnode.suspense!.next() } const el = hostNextSibling((vnode.anchor || vnode.el)!) // #9071, #9313 // teleported content can mess up nextSibling searches during patch so // we need to skip them during nextSibling search const teleportEnd = el && el[TeleportEndKey] return teleportEnd ? hostNextSibling(teleportEnd) : el } let isFlushing = false const render: RootRenderFunction = (vnode, container, namespace) => { if (vnode == null) { if (container._vnode) { unmount(container._vnode, null, null, true) } } else { patch( container._vnode || null, vnode, container, null, null, null, namespace, ) } container._vnode = vnode if (!isFlushing) { isFlushing = true flushPreFlushCbs() flushPostFlushCbs() isFlushing = false } } const internals: RendererInternals = { p: patch, um: unmount, m: move, r: remove, mt: mountComponent, mc: mountChildren, pc: patchChildren, pbc: patchBlockChildren, n: getNextHostNode, o: options, } let hydrate: ReturnType<typeof createHydrationFunctions>[0] | undefined let hydrateNode: ReturnType<typeof createHydrationFunctions>[1] | undefined if (createHydrationFns) { ;[hydrate, hydrateNode] = createHydrationFns( internals as RendererInternals<Node, Element>, ) } return { render, hydrate, createApp: createAppAPI(render, hydrate), } }
// implementation
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/src/renderer.ts#L341-L2405
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
patch
const patch: PatchFn = ( n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, namespace = undefined, slotScopeIds = null, optimized = __DEV__ && isHmrUpdating ? false : !!n2.dynamicChildren, ) => { if (n1 === n2) { return } // patching & not same type, unmount old tree if (n1 && !isSameVNodeType(n1, n2)) { anchor = getNextHostNode(n1) unmount(n1, parentComponent, parentSuspense, true) n1 = null } if (n2.patchFlag === PatchFlags.BAIL) { optimized = false n2.dynamicChildren = null } const { type, ref, shapeFlag } = n2 switch (type) { case Text: processText(n1, n2, container, anchor) break case Comment: processCommentNode(n1, n2, container, anchor) break case Static: if (n1 == null) { mountStaticNode(n2, container, anchor, namespace) } else if (__DEV__) { patchStaticNode(n1, n2, container, namespace) } break case Fragment: processFragment( n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, ) break default: if (shapeFlag & ShapeFlags.ELEMENT) { processElement( n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, ) } else if (shapeFlag & ShapeFlags.COMPONENT) { processComponent( n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, ) } else if (shapeFlag & ShapeFlags.TELEPORT) { ;(type as typeof TeleportImpl).process( n1 as TeleportVNode, n2 as TeleportVNode, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, internals, ) } else if (__FEATURE_SUSPENSE__ && shapeFlag & ShapeFlags.SUSPENSE) { ;(type as typeof SuspenseImpl).process( n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, internals, ) } else if (__DEV__) { warn('Invalid VNode type:', type, `(${typeof type})`) } } // set ref if (ref != null && parentComponent) { setRef(ref, n1 && n1.ref, parentSuspense, n2 || n1, !n2) } }
// Note: functions inside this closure should use `const xxx = () => {}`
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/src/renderer.ts#L373-L488
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
patchStaticNode
const patchStaticNode = ( n1: VNode, n2: VNode, container: RendererElement, namespace: ElementNamespace, ) => { // static nodes are only patched during dev for HMR if (n2.children !== n1.children) { const anchor = hostNextSibling(n1.anchor!) // remove existing removeStaticNode(n1) // insert new ;[n2.el, n2.anchor] = hostInsertStaticContent!( n2.children as string, container, anchor, namespace, ) } else { n2.el = n1.el n2.anchor = n1.anchor } }
/** * Dev / HMR only */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/src/renderer.ts#L544-L566
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
patchBlockChildren
const patchBlockChildren: PatchBlockChildrenFn = ( oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, namespace: ElementNamespace, slotScopeIds, ) => { for (let i = 0; i < newChildren.length; i++) { const oldVNode = oldChildren[i] const newVNode = newChildren[i] // Determine the container (parent element) for the patch. const container = // oldVNode may be an errored async setup() component inside Suspense // which will not have a mounted element oldVNode.el && // - In the case of a Fragment, we need to provide the actual parent // of the Fragment itself so it can move its children. (oldVNode.type === Fragment || // - In the case of different nodes, there is going to be a replacement // which also requires the correct parent container !isSameVNodeType(oldVNode, newVNode) || // - In the case of a component, it could contain anything. oldVNode.shapeFlag & (ShapeFlags.COMPONENT | ShapeFlags.TELEPORT)) ? hostParentNode(oldVNode.el)! : // In other cases, the parent container is not actually used so we // just pass the block element here to avoid a DOM parentNode call. fallbackContainer patch( oldVNode, newVNode, container, null, parentComponent, parentSuspense, namespace, slotScopeIds, true, ) } }
// The fast path for blocks.
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/src/renderer.ts#L940-L981
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
hydrateSubTree
const hydrateSubTree = () => { if (__DEV__) { startMeasure(instance, `render`) } instance.subTree = renderComponentRoot(instance) if (__DEV__) { endMeasure(instance, `render`) } if (__DEV__) { startMeasure(instance, `hydrate`) } hydrateNode!( el as Node, instance.subTree, instance, parentSuspense, null, ) if (__DEV__) { endMeasure(instance, `hydrate`) } }
// vnode has adopted host node - perform hydration instead of mount.
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/src/renderer.ts#L1313-L1334
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
patchKeyedChildren
const patchKeyedChildren = ( c1: VNode[], c2: VNodeArrayChildren, container: RendererElement, parentAnchor: RendererNode | null, parentComponent: ComponentInternalInstance | null, parentSuspense: SuspenseBoundary | null, namespace: ElementNamespace, slotScopeIds: string[] | null, optimized: boolean, ) => { let i = 0 const l2 = c2.length let e1 = c1.length - 1 // prev ending index let e2 = l2 - 1 // next ending index // 1. sync from start // (a b) c // (a b) d e while (i <= e1 && i <= e2) { const n1 = c1[i] const n2 = (c2[i] = optimized ? cloneIfMounted(c2[i] as VNode) : normalizeVNode(c2[i])) if (isSameVNodeType(n1, n2)) { patch( n1, n2, container, null, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, ) } else { break } i++ } // 2. sync from end // a (b c) // d e (b c) while (i <= e1 && i <= e2) { const n1 = c1[e1] const n2 = (c2[e2] = optimized ? cloneIfMounted(c2[e2] as VNode) : normalizeVNode(c2[e2])) if (isSameVNodeType(n1, n2)) { patch( n1, n2, container, null, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, ) } else { break } e1-- e2-- } // 3. common sequence + mount // (a b) // (a b) c // i = 2, e1 = 1, e2 = 2 // (a b) // c (a b) // i = 0, e1 = -1, e2 = 0 if (i > e1) { if (i <= e2) { const nextPos = e2 + 1 const anchor = nextPos < l2 ? (c2[nextPos] as VNode).el : parentAnchor while (i <= e2) { patch( null, (c2[i] = optimized ? cloneIfMounted(c2[i] as VNode) : normalizeVNode(c2[i])), container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, ) i++ } } } // 4. common sequence + unmount // (a b) c // (a b) // i = 2, e1 = 2, e2 = 1 // a (b c) // (b c) // i = 0, e1 = 0, e2 = -1 else if (i > e2) { while (i <= e1) { unmount(c1[i], parentComponent, parentSuspense, true) i++ } } // 5. unknown sequence // [i ... e1 + 1]: a b [c d e] f g // [i ... e2 + 1]: a b [e d c h] f g // i = 2, e1 = 4, e2 = 5 else { const s1 = i // prev starting index const s2 = i // next starting index // 5.1 build key:index map for newChildren const keyToNewIndexMap: Map<PropertyKey, number> = new Map() for (i = s2; i <= e2; i++) { const nextChild = (c2[i] = optimized ? cloneIfMounted(c2[i] as VNode) : normalizeVNode(c2[i])) if (nextChild.key != null) { if (__DEV__ && keyToNewIndexMap.has(nextChild.key)) { warn( `Duplicate keys found during update:`, JSON.stringify(nextChild.key), `Make sure keys are unique.`, ) } keyToNewIndexMap.set(nextChild.key, i) } } // 5.2 loop through old children left to be patched and try to patch // matching nodes & remove nodes that are no longer present let j let patched = 0 const toBePatched = e2 - s2 + 1 let moved = false // used to track whether any node has moved let maxNewIndexSoFar = 0 // works as Map<newIndex, oldIndex> // Note that oldIndex is offset by +1 // and oldIndex = 0 is a special value indicating the new node has // no corresponding old node. // used for determining longest stable subsequence const newIndexToOldIndexMap = new Array(toBePatched) for (i = 0; i < toBePatched; i++) newIndexToOldIndexMap[i] = 0 for (i = s1; i <= e1; i++) { const prevChild = c1[i] if (patched >= toBePatched) { // all new children have been patched so this can only be a removal unmount(prevChild, parentComponent, parentSuspense, true) continue } let newIndex if (prevChild.key != null) { newIndex = keyToNewIndexMap.get(prevChild.key) } else { // key-less node, try to locate a key-less node of the same type for (j = s2; j <= e2; j++) { if ( newIndexToOldIndexMap[j - s2] === 0 && isSameVNodeType(prevChild, c2[j] as VNode) ) { newIndex = j break } } } if (newIndex === undefined) { unmount(prevChild, parentComponent, parentSuspense, true) } else { newIndexToOldIndexMap[newIndex - s2] = i + 1 if (newIndex >= maxNewIndexSoFar) { maxNewIndexSoFar = newIndex } else { moved = true } patch( prevChild, c2[newIndex] as VNode, container, null, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, ) patched++ } } // 5.3 move and mount // generate longest stable subsequence only when nodes have moved const increasingNewIndexSequence = moved ? getSequence(newIndexToOldIndexMap) : EMPTY_ARR j = increasingNewIndexSequence.length - 1 // looping backwards so that we can use last patched node as anchor for (i = toBePatched - 1; i >= 0; i--) { const nextIndex = s2 + i const nextChild = c2[nextIndex] as VNode const anchor = nextIndex + 1 < l2 ? (c2[nextIndex + 1] as VNode).el : parentAnchor if (newIndexToOldIndexMap[i] === 0) { // mount new patch( null, nextChild, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, ) } else if (moved) { // move if: // There is no stable subsequence (e.g. a reverse) // OR current node is not among the stable sequence if (j < 0 || i !== increasingNewIndexSequence[j]) { move(nextChild, container, anchor, MoveType.REORDER) } else { j-- } } } } }
// can be all-keyed or mixed
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/src/renderer.ts#L1763-L2001
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
getSequence
function getSequence(arr: number[]): number[] { const p = arr.slice() const result = [0] let i, j, u, v, c const len = arr.length for (i = 0; i < len; i++) { const arrI = arr[i] if (arrI !== 0) { j = result[result.length - 1] if (arr[j] < arrI) { p[i] = j result.push(i) continue } u = 0 v = result.length - 1 while (u < v) { c = (u + v) >> 1 if (arr[result[c]] < arrI) { u = c + 1 } else { v = c } } if (arrI < arr[result[u]]) { if (u > 0) { p[i] = result[u - 1] } result[u] = i } } } u = result.length v = result[u - 1] while (u-- > 0) { result[u] = v v = p[v] } return result }
// https://en.wikipedia.org/wiki/Longest_increasing_subsequence
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/src/renderer.ts#L2491-L2530
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
findInsertionIndex
function findInsertionIndex(id: number) { let start = flushIndex + 1 let end = queue.length while (start < end) { const middle = (start + end) >>> 1 const middleJob = queue[middle] const middleJobId = getId(middleJob) if ( middleJobId < id || (middleJobId === id && middleJob.flags! & SchedulerJobFlags.PRE) ) { start = middle + 1 } else { end = middle } } return start }
// Use binary-search to find a suitable position in the queue. The queue needs
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/src/scheduler.ts#L73-L92
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
deepCloneVNode
function deepCloneVNode(vnode: VNode): VNode { const cloned = cloneVNode(vnode) if (isArray(vnode.children)) { cloned.children = (vnode.children as VNode[]).map(deepCloneVNode) } return cloned }
/** * Dev only, for HMR of hoisted vnodes reused in v-for * https://github.com/vitejs/vite/issues/2022 */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/src/vnode.ts#L741-L747
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
formatTrace
function formatTrace(trace: ComponentTraceStack): any[] { const logs: any[] = [] trace.forEach((entry, i) => { logs.push(...(i === 0 ? [] : [`\n`]), ...formatTraceEntry(entry)) }) return logs }
/* v8 ignore start */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/src/warning.ts#L111-L117
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
emptyPlaceholder
function emptyPlaceholder(vnode: VNode): VNode | undefined { if (isKeepAlive(vnode)) { vnode = cloneVNode(vnode) vnode.children = null return vnode } }
// the placeholder really only handles one special case: KeepAlive
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/src/components/BaseTransition.ts#L488-L494
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
resolveAsset
function resolveAsset( type: AssetTypes, name: string, warnMissing = true, maybeSelfReference = false, ) { const instance = currentRenderingInstance || currentInstance if (instance) { const Component = instance.type // explicit self name has highest priority if (type === COMPONENTS) { const selfName = getComponentName( Component, false /* do not include inferred name to avoid breaking existing code */, ) if ( selfName && (selfName === name || selfName === camelize(name) || selfName === capitalize(camelize(name))) ) { return Component } } const res = // local registration // check instance[type] first which is resolved for options API resolve(instance[type] || (Component as ComponentOptions)[type], name) || // global registration resolve(instance.appContext[type], name) if (!res && maybeSelfReference) { // fallback to implicit self-reference return Component } if (__DEV__ && warnMissing && !res) { const extra = type === COMPONENTS ? `\nIf this is a native custom element, make sure to exclude it from ` + `component resolution via compilerOptions.isCustomElement.` : `` warn(`Failed to resolve ${type.slice(0, -1)}: ${name}${extra}`) } return res } else if (__DEV__) { warn( `resolve${capitalize(type.slice(0, -1))} ` + `can only be used in render() or setup().`, ) } }
// implementation
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-core/src/helpers/resolveAssets.ts#L77-L131
da75dd9131958ff4fb0f9b592c99cd76c761e272