})
const { code } = generate(root, { mode: 'module' })
expect(code).toMatch(
- `import { ${helperNameMap[CREATE_VNODE]} as _${
- helperNameMap[CREATE_VNODE]
- }, ${helperNameMap[RESOLVE_DIRECTIVE]} as _${
- helperNameMap[RESOLVE_DIRECTIVE]
- } } from "vue"`
+ `import { ${helperNameMap[CREATE_VNODE]} as _${helperNameMap[CREATE_VNODE]}, ${helperNameMap[RESOLVE_DIRECTIVE]} as _${helperNameMap[RESOLVE_DIRECTIVE]} } from "vue"`
)
expect(code).toMatchSnapshot()
})
})
const { code } = generate(root, { mode: 'module', optimizeImports: true })
expect(code).toMatch(
- `import { ${helperNameMap[CREATE_VNODE]}, ${
- helperNameMap[RESOLVE_DIRECTIVE]
- } } from "vue"`
+ `import { ${helperNameMap[CREATE_VNODE]}, ${helperNameMap[RESOLVE_DIRECTIVE]} } from "vue"`
)
expect(code).toMatch(
- `const _${helperNameMap[CREATE_VNODE]} = ${
- helperNameMap[CREATE_VNODE]
- }, _${helperNameMap[RESOLVE_DIRECTIVE]} = ${
- helperNameMap[RESOLVE_DIRECTIVE]
- }`
+ `const _${helperNameMap[CREATE_VNODE]} = ${helperNameMap[CREATE_VNODE]}, _${helperNameMap[RESOLVE_DIRECTIVE]} = ${helperNameMap[RESOLVE_DIRECTIVE]}`
)
expect(code).toMatchSnapshot()
})
const { code } = generate(root, { mode: 'function' })
expect(code).toMatch(`const _Vue = Vue`)
expect(code).toMatch(
- `const { ${helperNameMap[CREATE_VNODE]}: _${
- helperNameMap[CREATE_VNODE]
- }, ${helperNameMap[RESOLVE_DIRECTIVE]}: _${
- helperNameMap[RESOLVE_DIRECTIVE]
- } } = _Vue`
+ `const { ${helperNameMap[CREATE_VNODE]}: _${helperNameMap[CREATE_VNODE]}, ${helperNameMap[RESOLVE_DIRECTIVE]}: _${helperNameMap[RESOLVE_DIRECTIVE]} } = _Vue`
)
expect(code).toMatchSnapshot()
})
})
expect(code).not.toMatch(`const _Vue = Vue`)
expect(code).toMatch(
- `const { ${helperNameMap[CREATE_VNODE]}: _${
- helperNameMap[CREATE_VNODE]
- }, ${helperNameMap[RESOLVE_DIRECTIVE]}: _${
- helperNameMap[RESOLVE_DIRECTIVE]
- } } = Vue`
+ `const { ${helperNameMap[CREATE_VNODE]}: _${helperNameMap[CREATE_VNODE]}, ${helperNameMap[RESOLVE_DIRECTIVE]}: _${helperNameMap[RESOLVE_DIRECTIVE]} } = Vue`
)
expect(code).toMatchSnapshot()
})
`const _component_Foo = _${helperNameMap[RESOLVE_COMPONENT]}("Foo")\n`
)
expect(code).toMatch(
- `const _component_bar_baz = _${
- helperNameMap[RESOLVE_COMPONENT]
- }("bar-baz")\n`
+ `const _component_bar_baz = _${helperNameMap[RESOLVE_COMPONENT]}("bar-baz")\n`
)
expect(code).toMatch(
- `const _component_barbaz = _${
- helperNameMap[RESOLVE_COMPONENT]
- }("barbaz")\n`
+ `const _component_barbaz = _${helperNameMap[RESOLVE_COMPONENT]}("barbaz")\n`
)
// implicit self reference from SFC filename
expect(code).toMatch(
- `const _component_Qux = _${
- helperNameMap[RESOLVE_COMPONENT]
- }("Qux", true)\n`
+ `const _component_Qux = _${helperNameMap[RESOLVE_COMPONENT]}("Qux", true)\n`
)
expect(code).toMatch(
- `const _directive_my_dir_0 = _${
- helperNameMap[RESOLVE_DIRECTIVE]
- }("my_dir_0")\n`
+ `const _directive_my_dir_0 = _${helperNameMap[RESOLVE_DIRECTIVE]}("my_dir_0")\n`
)
expect(code).toMatch(
- `const _directive_my_dir_1 = _${
- helperNameMap[RESOLVE_DIRECTIVE]
- }("my_dir_1")\n`
+ `const _directive_my_dir_1 = _${helperNameMap[RESOLVE_DIRECTIVE]}("my_dir_1")\n`
)
expect(code).toMatch(`let _temp0, _temp1, _temp2`)
expect(code).toMatchSnapshot()
]
}
- for (const key of Object.keys(patterns) as (keyof (typeof patterns))[]) {
+ for (const key of Object.keys(patterns) as (keyof typeof patterns)[]) {
describe(key, () => {
for (const { code, errors, options } of patterns[key]) {
test(
},
hoistedChildrenArrayMatcher(2)
])
- const forBlockCodegen = ((root.children[0] as ElementNode)
- .children[0] as ForNode).codegenNode
+ const forBlockCodegen = (
+ (root.children[0] as ElementNode).children[0] as ForNode
+ ).codegenNode
expect(forBlockCodegen).toMatchObject({
type: NodeTypes.VNODE_CALL,
tag: FRAGMENT,
patchFlag: !disableTracking
? genFlagText(PatchFlags.STABLE_FRAGMENT)
: keyed
- ? genFlagText(PatchFlags.KEYED_FRAGMENT)
- : genFlagText(PatchFlags.UNKEYED_FRAGMENT),
+ ? genFlagText(PatchFlags.KEYED_FRAGMENT)
+ : genFlagText(PatchFlags.UNKEYED_FRAGMENT),
children: {
type: NodeTypes.JS_CALL_EXPRESSION,
callee: RENDER_LIST,
test('with dynamic argument', () => {
const root = parseWithVModel('<input v-model:[value]="model" />')
const node = root.children[0] as ElementNode
- const props = ((node.codegenNode as VNodeCall)
- .props as unknown) as CallExpression
+ const props = (node.codegenNode as VNodeCall)
+ .props as unknown as CallExpression
expect(props).toMatchObject({
type: NodeTypes.JS_CALL_EXPRESSION,
prefixIdentifiers: true
})
const node = root.children[0] as ElementNode
- const props = ((node.codegenNode as VNodeCall)
- .props as unknown) as CallExpression
+ const props = (node.codegenNode as VNodeCall)
+ .props as unknown as CallExpression
expect(props).toMatchObject({
type: NodeTypes.JS_CALL_EXPRESSION,
}
)
expect(root.cached).toBe(0)
- const codegen = ((root.children[0] as ForNode)
- .children[0] as PlainElementNode).codegenNode as VNodeCall
+ const codegen = (
+ (root.children[0] as ForNode).children[0] as PlainElementNode
+ ).codegenNode as VNodeCall
expect(codegen.dynamicProps).toBe(`["modelValue", "onUpdate:modelValue"]`)
expect(
(codegen.props as ObjectExpression).properties[1].value.type
})
test('should not cache update handler if it inside v-once', () => {
- const root = parseWithVModel(
- '<div v-once><input v-model="foo" /></div>',
- {
- prefixIdentifiers: true,
- cacheHandlers: true
- }
- )
+ const root = parseWithVModel('<div v-once><input v-model="foo" /></div>', {
+ prefixIdentifiers: true,
+ cacheHandlers: true
+ })
expect(root.cached).not.toBe(2)
expect(root.cached).toBe(1)
})
prefixIdentifiers: true
}
)
- const codegen = ((root.children[0] as ComponentNode)
- .children[0] as PlainElementNode).codegenNode as VNodeCall
+ const codegen = (
+ (root.children[0] as ComponentNode).children[0] as PlainElementNode
+ ).codegenNode as VNodeCall
expect(codegen.dynamicProps).toBe(`["modelValue", "onUpdate:modelValue"]`)
})
})
test('should not be cached inside v-once', () => {
- const { root } = parseWithVOn(`<div v-once><div v-on:click="foo"/></div>`, {
- prefixIdentifiers: true,
- cacheHandlers: true
- })
+ const { root } = parseWithVOn(
+ `<div v-once><div v-on:click="foo"/></div>`,
+ {
+ prefixIdentifiers: true,
+ cacheHandlers: true
+ }
+ )
expect(root.cached).not.toBe(2)
expect(root.cached).toBe(1)
})
| InterpolationNode
| TextNode
| string
- | symbol)[]
+ | symbol
+ )[]
/**
* an expression parsed as the params of a function will track
| JSChildNode
| SSRCodegenNode
| TemplateChildNode
- | TemplateChildNode[])[]
+ | TemplateChildNode[]
+ )[]
}
export interface ObjectExpression extends Node {
}
export interface DirectiveArgumentNode extends ArrayExpression {
- elements: // dir, exp, arg, modifiers
- | [string]
+ elements: // dir, exp, arg, modifiers
+ | [string]
| [string, ExpressionNode]
| [string, ExpressionNode, ExpressionNode]
| [string, ExpressionNode, ExpressionNode, ObjectExpression]
// renderSlot(...)
export interface RenderSlotCall extends CallExpression {
callee: typeof RENDER_SLOT
- arguments: // $slots, name, props, fallback
- | [string, string | ExpressionNode]
+ arguments: // $slots, name, props, fallback
+ | [string, string | ExpressionNode]
| [string, string | ExpressionNode, PropsExpression]
| [
string,
__COMPAT__ && type === 'filter'
? RESOLVE_FILTER
: type === 'component'
- ? RESOLVE_COMPONENT
- : RESOLVE_DIRECTIVE
+ ? RESOLVE_COMPONENT
+ : RESOLVE_DIRECTIVE
)
for (let i = 0; i < assets.length; i++) {
let id = assets[i]
transformExpression
]
: __BROWSER__ && __DEV__
- ? [transformExpression]
- : []),
+ ? [transformExpression]
+ : []),
transformSlotOutlet,
transformElement,
trackSlotScopes,
}
const ast = isString(template) ? baseParse(template, options) : template
- const [nodeTransforms, directiveTransforms] = getBaseTransformPreset(
- prefixIdentifiers
- )
+ const [nodeTransforms, directiveTransforms] =
+ getBaseTransformPreset(prefixIdentifiers)
transform(
ast,
extend({}, options, {
const loc = getSelection(context, start)
if (!context.inVPre && /^(v-|:|\.|@|#)/.test(name)) {
- const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^\.|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(
- name
- )!
+ const match =
+ /(?:^v-([a-z0-9-]+))?(?:(?::|^\.|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(
+ name
+ )!
let isPropShorthand = startsWith(name, '.')
let dirName =
(isPropShorthand || startsWith(name, ':')
? 'bind'
: startsWith(name, '@')
- ? 'on'
- : 'slot')
+ ? 'on'
+ : 'slot')
let arg: ExpressionNode | undefined
if (match[2]) {
const removalIndex = node
? list.indexOf(node)
: context.currentNode
- ? context.childIndex
- : -1
+ ? context.childIndex
+ : -1
/* istanbul ignore if */
if (__DEV__ && removalIndex < 0) {
throw new Error(`node being removed is not a child of current parent`)
const fragmentFlag = isStableFragment
? PatchFlags.STABLE_FRAGMENT
: keyProp
- ? PatchFlags.KEYED_FRAGMENT
- : PatchFlags.UNKEYED_FRAGMENT
+ ? PatchFlags.KEYED_FRAGMENT
+ : PatchFlags.UNKEYED_FRAGMENT
forNode.codegenNode = createVNodeCall(
context,
: isTemplate &&
node.children.length === 1 &&
isSlotOutlet(node.children[0])
- ? (node.children[0] as SlotOutletNode) // api-extractor somehow fails to infer this
- : null
+ ? (node.children[0] as SlotOutletNode) // api-extractor somehow fails to infer this
+ : null
if (slotOutlet) {
// <slot v-for="..."> or <template v-for="..."><slot/></template>
createSimpleExpression(String(context.cached++))
)
} else {
- renderExp.arguments.push(createFunctionExpression(
- createForLoopParams(forNode.parseResult),
- childBlock,
- true /* force newline */
- ) as ForIteratorExpression)
+ renderExp.arguments.push(
+ createFunctionExpression(
+ createForLoopParams(forNode.parseResult),
+ childBlock,
+ true /* force newline */
+ ) as ForIteratorExpression
+ )
}
}
})
validateBrowserExpression(result.source as SimpleExpressionNode, context)
}
- let valueContent = LHS.trim()
- .replace(stripParensRE, '')
- .trim()
+ let valueContent = LHS.trim().replace(stripParensRE, '').trim()
const trimmedOffset = LHS.indexOf(valueContent)
const iteratorMatch = valueContent.match(forIteratorRE)
}
if (
exp.type !== NodeTypes.SIMPLE_EXPRESSION ||
- (exp.isStatic !== (branchExp as SimpleExpressionNode).isStatic ||
- exp.content !== (branchExp as SimpleExpressionNode).content)
+ exp.isStatic !== (branchExp as SimpleExpressionNode).isStatic ||
+ exp.content !== (branchExp as SimpleExpressionNode).content
) {
return false
}
const slotFlag = hasDynamicSlots
? SlotFlags.DYNAMIC
: hasForwardedSlots(node.children)
- ? SlotFlags.FORWARDED
- : SlotFlags.STABLE
+ ? SlotFlags.FORWARDED
+ : SlotFlags.STABLE
let slots = createObjectExpression(
slotsProperties.concat(
p.type === NodeTypes.DIRECTIVE &&
p.name === 'bind' &&
(!p.arg || // v-bind="obj"
- p.arg.type !== NodeTypes.SIMPLE_EXPRESSION || // v-bind:[_ctx.foo]
+ p.arg.type !== NodeTypes.SIMPLE_EXPRESSION || // v-bind:[_ctx.foo]
!p.arg.isStatic) // v-bind:[foo]
)
}
)
// strip strings in expressions
-const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g
+const stripStringRE =
+ /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g
/**
* Validate a non-prefixed expression.
.replace(stripStringRE, '')
.match(prohibitedKeywordRE)
if (keywordMatch) {
- message = `avoid using JavaScript keyword as property name: "${
- keywordMatch[0]
- }"`
+ message = `avoid using JavaScript keyword as property name: "${keywordMatch[0]}"`
}
context.onError(
createCompilerError(
})
return {
root: ast,
- props: (((ast.children[0] as ElementNode).codegenNode as VNodeCall)
- .props as ObjectExpression).properties
+ props: (
+ ((ast.children[0] as ElementNode).codegenNode as VNodeCall)
+ .props as ObjectExpression
+ ).properties
}
}
return isStaticClick
? createSimpleExpression(event, true)
: key.type !== NodeTypes.SIMPLE_EXPRESSION
- ? createCompoundExpression([
- `(`,
- key,
- `) === "onClick" ? "${event}" : (`,
- key,
- `)`
- ])
- : key
+ ? createCompoundExpression([
+ `(`,
+ key,
+ `) === "onClick" ? "${event}" : (`,
+ key,
+ `)`
+ ])
+ : key
}
export const transformOn: DirectiveTransform = (dir, node, context) => {
if (!modifiers.length) return baseResult
let { key, value: handlerExp } = baseResult.props[0]
- const {
- keyModifiers,
- nonKeyModifiers,
- eventOptionModifiers
- } = resolveModifiers(key, modifiers, context, dir.loc)
+ const { keyModifiers, nonKeyModifiers, eventOptionModifiers } =
+ resolveModifiers(key, modifiers, context, dir.loc)
// normalize click.right and click.middle since they don't actually fire
if (nonKeyModifiers.includes('right')) {
test('with explicit base', () => {
const { code } = compileWithAssetUrls(
`<img src="./bar.png"></img>` + // -> /foo/bar.png
- `<img src="bar.png"></img>` + // -> bar.png (untouched)
- `<img src="~bar.png"></img>` + // -> still converts to import
+ `<img src="bar.png"></img>` + // -> bar.png (untouched)
+ `<img src="~bar.png"></img>` + // -> still converts to import
`<img src="@theme/bar.png"></img>`, // -> still converts to import
{
base: '/foo'
.map(key => {
let defaultString: string | undefined
if (hasStaticDefaults) {
- const prop = (propsRuntimeDefaults as ObjectExpression).properties.find(
+ const prop = (
+ propsRuntimeDefaults as ObjectExpression
+ ).properties.find(
(node: any) => node.key.name === key
) as ObjectProperty
if (prop) {
// rewrite to `import { x as __default__ } from './x'` and
// add to top
s.prepend(
- `import { ${
- defaultSpecifier.local.name
- } as ${defaultTempVar} } from '${node.source.value}'\n`
+ `import { ${defaultSpecifier.local.name} as ${defaultTempVar} } from '${node.source.value}'\n`
)
} else {
// export { x as default }
...scriptSetup,
bindings: bindingMetadata,
content: s.toString(),
- map: (s.generateMap({
+ map: s.generateMap({
source: filename,
hires: true,
includeContent: true
- }) as unknown) as RawSourceMap,
+ }) as unknown as RawSourceMap,
scriptAst,
scriptSetupAst
}
const type = isDefineCall
? BindingTypes.SETUP_CONST
: isConst
- ? BindingTypes.SETUP_MAYBE_REF
- : BindingTypes.SETUP_LET
+ ? BindingTypes.SETUP_MAYBE_REF
+ : BindingTypes.SETUP_LET
registerBinding(bindings, p.key, type)
} else {
walkPattern(p.value, bindings, isConst, isDefineCall)
const type = isDefineCall
? BindingTypes.SETUP_CONST
: isConst
- ? BindingTypes.SETUP_MAYBE_REF
- : BindingTypes.SETUP_LET
+ ? BindingTypes.SETUP_MAYBE_REF
+ : BindingTypes.SETUP_LET
registerBinding(bindings, node, type)
} else if (node.type === 'RestElement') {
// argument can only be identifer when destructuring
const type = isDefineCall
? BindingTypes.SETUP_CONST
: isConst
- ? BindingTypes.SETUP_MAYBE_REF
- : BindingTypes.SETUP_LET
+ ? BindingTypes.SETUP_MAYBE_REF
+ : BindingTypes.SETUP_LET
registerBinding(bindings, node.left, type)
} else {
walkPattern(node.left, bindings, isConst)
case 'TSUnionType':
return [
...new Set(
- [].concat(node.types.map(t =>
- inferRuntimeType(t, declaredTypes)
- ) as any)
+ [].concat(
+ node.types.map(t => inferRuntimeType(t, declaredTypes)) as any
+ )
)
]
case 'TSIntersectionType':
return types.some(t => t === 'null')
? `null`
: types.length > 1
- ? `[${types.join(', ')}]`
- : types[0]
+ ? `[${types.join(', ')}]`
+ : types[0]
}
function extractRuntimeEmits(
export function compileStyleAsync(
options: SFCAsyncStyleCompileOptions
): Promise<SFCStyleCompileResults> {
- return doCompileStyle({ ...options, isAsync: true }) as Promise<
- SFCStyleCompileResults
- >
+ return doCompileStyle({
+ ...options,
+ isAsync: true
+ }) as Promise<SFCStyleCompileResults>
}
export function doCompileStyle(
code: `export default function render() {}`,
source: options.source,
tips: [
- `Component ${
- options.filename
- } uses lang ${preprocessLang} for template. Please install the language preprocessor.`
+ `Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
],
errors: [
- `Component ${
- options.filename
- } uses lang ${preprocessLang} for template, however it is not installed.`
+ `Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
]
}
} else {
import hash from 'hash-sum'
export const CSS_VARS_HELPER = `useCssVars`
-export const cssVarRE = /\bv-bind\(\s*(?:'([^']+)'|"([^"]+)"|([^'"][^)]*))\s*\)/g
+export const cssVarRE =
+ /\bv-bind\(\s*(?:'([^']+)'|"([^"]+)"|([^'"][^)]*))\s*\)/g
export function genCssVarsFromList(
vars: string[],
const defaultExportRE = /((?:^|\n|;)\s*)export(\s*)default/
const namedDefaultExportRE = /((?:^|\n|;)\s*)export(.+)as(\s*)default/s
-const exportDefaultClassRE = /((?:^|\n|;)\s*)export\s+default\s+class\s+([\w$]+)/
+const exportDefaultClassRE =
+ /((?:^|\n|;)\s*)export\s+default\s+class\s+([\w$]+)/
/**
* Utility for rewriting `export default` in a script block into a variable
`)
})
- test("multiple _ssrInterpolate at parent and child import dependency once", () => {
- expect( compile(`<div>{{ hello }}<textarea v-bind="a"></textarea></div>`).code)
- .toMatchInlineSnapshot(`
+ test('multiple _ssrInterpolate at parent and child import dependency once', () => {
+ expect(
+ compile(`<div>{{ hello }}<textarea v-bind="a"></textarea></div>`).code
+ ).toMatchInlineSnapshot(`
"const { ssrRenderAttrs: _ssrRenderAttrs, ssrInterpolate: _ssrInterpolate } = require(\\"@vue/server-renderer\\")
return function ssrRender(_ctx, _push, _parent, _attrs) {
_ssrInterpolate((\\"value\\" in _temp0) ? _temp0.value : \\"\\")
}</textarea></div>\`)
}"
- `);
- });
+ `)
+ })
test('should pass tag to custom elements w/ dynamic v-bind', () => {
expect(
// Finalize helpers.
// We need to separate helpers imported from 'vue' vs. '@vue/server-renderer'
- ast.ssrHelpers = Array.from(new Set([
- ...ast.helpers.filter(h => h in ssrHelpers),
- ...context.helpers
- ]))
-
+ ast.ssrHelpers = Array.from(
+ new Set([...ast.helpers.filter(h => h in ssrHelpers), ...context.helpers])
+ )
+
ast.helpers = ast.helpers.filter(h => !(h in ssrHelpers))
}
export const rawOptionsMap = new WeakMap<RootNode, CompilerOptions>()
-const [baseNodeTransforms, baseDirectiveTransforms] = getBaseTransformPreset(
- true
-)
+const [baseNodeTransforms, baseDirectiveTransforms] =
+ getBaseTransformPreset(true)
const vnodeNodeTransforms = [...baseNodeTransforms, ...DOMNodeTransforms]
const vnodeDirectiveTransforms = {
...baseDirectiveTransforms,
}
}
-declare module '*.vue' {
-
-}
+declare module '*.vue' {}
declare module '*?raw' {
const content: string
export default content
const proxy = reactive(raw)
const thisArg = {}
let count = 0
- proxy.forEach(function(this: {}, value, _, set) {
+ proxy.forEach(function (this: {}, value, _, set) {
++count
expect(this).toBe(thisArg)
expect(value).toBe('value')
test('should make nested values readonly', () => {
const key1 = {}
const key2 = {}
- const original = new Collection([[key1, {}], [key2, {}]])
+ const original = new Collection([
+ [key1, {}],
+ [key2, {}]
+ ])
const wrapped = readonly(original)
expect(wrapped).not.toBe(original)
expect(isProxy(wrapped)).toBe(true)
test('should retrieve readonly values on iteration', () => {
const key1 = {}
const key2 = {}
- const original = new Map([[key1, {}], [key2, {}]])
+ const original = new Map([
+ [key1, {}],
+ [key2, {}]
+ ])
const wrapped: any = readonly(original)
expect(wrapped.size).toBe(2)
for (const [key, value] of wrapped) {
test('should retrieve reactive + readonly values on iteration', () => {
const key1 = {}
const key2 = {}
- const original = reactive(new Map([[key1, {}], [key2, {}]]))
+ const original = reactive(
+ new Map([
+ [key1, {}],
+ [key2, {}]
+ ])
+ )
const wrapped: any = readonly(original)
expect(wrapped.size).toBe(2)
for (const [key, value] of wrapped) {
// instrument identity-sensitive Array methods to account for possible reactive
// values
;(['includes', 'indexOf', 'lastIndexOf'] as const).forEach(key => {
- instrumentations[key] = function(this: unknown[], ...args: unknown[]) {
+ instrumentations[key] = function (this: unknown[], ...args: unknown[]) {
const arr = toRaw(this) as any
for (let i = 0, l = this.length; i < l; i++) {
track(arr, TrackOpTypes.GET, i + '')
// instrument length-altering mutation methods to avoid length being tracked
// which leads to infinite loops in some cases (#2137)
;(['push', 'pop', 'shift', 'unshift', 'splice'] as const).forEach(key => {
- instrumentations[key] = function(this: unknown[], ...args: unknown[]) {
+ instrumentations[key] = function (this: unknown[], ...args: unknown[]) {
pauseTracking()
const res = (toRaw(this) as any)[key].apply(this, args)
resetTracking()
? shallowReadonlyMap
: readonlyMap
: shallow
- ? shallowReactiveMap
- : reactiveMap
+ ? shallowReactiveMap
+ : reactiveMap
).get(target)
) {
return target
isReadonly: boolean,
isShallow: boolean
) {
- return function(
+ return function (
this: IterableCollections,
...args: unknown[]
): Iterable & Iterator {
}
function createReadonlyMethod(type: TriggerOpTypes): Function {
- return function(this: CollectionTypes, ...args: unknown[]) {
+ return function (this: CollectionTypes, ...args: unknown[]) {
if (__DEV__) {
const key = args[0] ? `on key "${args[0]}" ` : ``
console.warn(
return get(this, key)
},
get size() {
- return size((this as unknown) as IterableCollections)
+ return size(this as unknown as IterableCollections)
},
has,
add,
return get(this, key, false, true)
},
get size() {
- return size((this as unknown) as IterableCollections)
+ return size(this as unknown as IterableCollections)
},
has,
add,
return get(this, key, true)
},
get size() {
- return size((this as unknown) as IterableCollections, true)
+ return size(this as unknown as IterableCollections, true)
},
has(this: MapTypes, key: unknown) {
return has.call(this, key, true)
return get(this, key, true, true)
},
get size() {
- return size((this as unknown) as IterableCollections, true)
+ return size(this as unknown as IterableCollections, true)
},
has(this: MapTypes, key: unknown) {
return has.call(this, key, true)
? shallowReadonlyInstrumentations
: shallowInstrumentations
: isReadonly
- ? readonlyInstrumentations
- : mutableInstrumentations
+ ? readonlyInstrumentations
+ : mutableInstrumentations
return (
target: CollectionTypes,
get: /*#__PURE__*/ createInstrumentationGetter(true, false)
}
-export const shallowReadonlyCollectionHandlers: ProxyHandler<
- CollectionTypes
-> = {
- get: /*#__PURE__*/ createInstrumentationGetter(true, true)
-}
+export const shallowReadonlyCollectionHandlers: ProxyHandler<CollectionTypes> =
+ {
+ get: /*#__PURE__*/ createInstrumentationGetter(true, true)
+ }
function checkIdentityKeys(
target: CollectionTypes,
private _dirty = true
public readonly effect: ReactiveEffect<T>
- public readonly __v_isRef = true;
+ public readonly __v_isRef = true
public readonly [ReactiveFlags.IS_READONLY]: boolean
constructor(
export type DeepReadonly<T> = T extends Builtin
? T
: T extends Map<infer K, infer V>
- ? ReadonlyMap<DeepReadonly<K>, DeepReadonly<V>>
- : T extends ReadonlyMap<infer K, infer V>
- ? ReadonlyMap<DeepReadonly<K>, DeepReadonly<V>>
- : T extends WeakMap<infer K, infer V>
- ? WeakMap<DeepReadonly<K>, DeepReadonly<V>>
- : T extends Set<infer U>
- ? ReadonlySet<DeepReadonly<U>>
- : T extends ReadonlySet<infer U>
- ? ReadonlySet<DeepReadonly<U>>
- : T extends WeakSet<infer U>
- ? WeakSet<DeepReadonly<U>>
- : T extends Promise<infer U>
- ? Promise<DeepReadonly<U>>
- : T extends {}
- ? { readonly [K in keyof T]: DeepReadonly<T[K]> }
- : Readonly<T>
+ ? ReadonlyMap<DeepReadonly<K>, DeepReadonly<V>>
+ : T extends ReadonlyMap<infer K, infer V>
+ ? ReadonlyMap<DeepReadonly<K>, DeepReadonly<V>>
+ : T extends WeakMap<infer K, infer V>
+ ? WeakMap<DeepReadonly<K>, DeepReadonly<V>>
+ : T extends Set<infer U>
+ ? ReadonlySet<DeepReadonly<U>>
+ : T extends ReadonlySet<infer U>
+ ? ReadonlySet<DeepReadonly<U>>
+ : T extends WeakSet<infer U>
+ ? WeakSet<DeepReadonly<U>>
+ : T extends Promise<infer U>
+ ? Promise<DeepReadonly<U>>
+ : T extends {}
+ ? { readonly [K in keyof T]: DeepReadonly<T[K]> }
+ : Readonly<T>
/**
* Creates a readonly copy of the original object. Note the returned copy is not
[K in keyof T]: T[K] extends Ref<infer V>
? V
: T[K] extends Ref<infer V> | undefined // if `V` is `unknown` that means it does not extend `Ref` and is undefined
- ? unknown extends V ? undefined : V | undefined
- : T[K]
+ ? unknown extends V
+ ? undefined
+ : V | undefined
+ : T[K]
}
export type UnwrapRef<T> = T extends Ref<infer V>
| RefUnwrapBailTypes[keyof RefUnwrapBailTypes]
? T
: T extends Array<any>
- ? { [K in keyof T]: UnwrapRefSimple<T[K]> }
- : T extends object ? UnwrappedObject<T> : T
+ ? { [K in keyof T]: UnwrapRefSimple<T[K]> }
+ : T extends object
+ ? UnwrappedObject<T>
+ : T
// Extract all known symbols from an object
// when unwrapping Object the symbols are not `in keyof`, this should cover all the
beforeInstance = getCurrentInstance()
- const msg = (([__temp, __restore] = withAsyncContext(
- () =>
- new Promise(r => {
- resolve = r
- })
- )),
- (__temp = await __temp),
- __restore(),
- __temp)
+ const msg =
+ (([__temp, __restore] = withAsyncContext(
+ () =>
+ new Promise(r => {
+ resolve = r
+ })
+ )),
+ (__temp = await __temp),
+ __restore(),
+ __temp)
// register the lifecycle after an await statement
onMounted(spy)
})
const root = nodeOps.createElement('div')
- render(h(() => h(Suspense, () => h(Comp))), root)
+ render(
+ h(() => h(Suspense, () => h(Comp))),
+ root
+ )
expect(spy).not.toHaveBeenCalled()
resolve!('hello')
})
const root = nodeOps.createElement('div')
- render(h(() => h(Suspense, () => h(Comp))), root)
+ render(
+ h(() => h(Suspense, () => h(Comp))),
+ root
+ )
expect(spy).not.toHaveBeenCalled()
reject!()
})
const root = nodeOps.createElement('div')
- render(h(() => h(Suspense, () => h(Comp))), root)
+ render(
+ h(() => h(Suspense, () => h(Comp))),
+ root
+ )
await ready
expect(inBandInstance).toBe(beforeInstance)
const fn = jest.fn()
const toggle = ref(true)
- const Comp = defineComponent(() => () =>
- toggle.value ? h('div', { ref: fn }) : null
+ const Comp = defineComponent(
+ () => () => toggle.value ? h('div', { ref: fn }) : null
)
render(h(Comp), root)
expect(fn.mock.calls[0][0]).toBe(root.children[0])
state.count++
count.value++
await nextTick()
- expect(dummy).toMatchObject([[2, 2, 3], [1, 1, 2]])
+ expect(dummy).toMatchObject([
+ [2, 2, 3],
+ [1, 1, 2]
+ ])
})
it('watching multiple sources: readonly array', async () => {
state.count++
status.value = true
await nextTick()
- expect(dummy).toMatchObject([[2, true], [1, false]])
+ expect(dummy).toMatchObject([
+ [2, true],
+ [1, false]
+ ])
})
it('watching multiple sources: reactive object (with automatic deep: true)', async () => {
count: ref(0)
},
array: [1, 2, 3],
- map: new Map([['a', 1], ['b', 2]]),
+ map: new Map([
+ ['a', 1],
+ ['b', 2]
+ ]),
set: new Set([1, 2, 3])
})
mounted() {
// this call runs while Comp is currentInstance, but
// the effect for this `$watch` should nontheless be registered with Child
- this.comp!.$watch(() => this.show, () => void 0)
+ this.comp!.$watch(
+ () => this.show,
+ () => void 0
+ )
}
})
render() {},
created(this: any) {
instance = this
- this.$watch(source, function() {})
+ this.$watch(source, function () {})
}
})
expect(() => (instanceProxy.$data = {})).toThrow(TypeError)
expect(`Attempting to mutate public property "$data"`).toHaveBeenWarned()
- const nextTickThis = await instanceProxy.$nextTick(function(this: any) {
+ const nextTickThis = await instanceProxy.$nextTick(function (this: any) {
return this
})
expect(nextTickThis).toBe(instanceProxy)
) {
const toggle = ref(true)
const { props, cbs } = mockProps({ mode })
- const root = mount(
- props,
- () => (toggle.value ? trueBranch() : falseBranch())
+ const root = mount(props, () =>
+ toggle.value ? trueBranch() : falseBranch()
)
// without appear: true, enter hooks should not be called on mount
}: ToggleOptions) {
const toggle = ref(false)
const { props, cbs } = mockProps()
- const root = mount(
- props,
- () => (toggle.value ? trueBranch() : falseBranch())
+ const root = mount(props, () =>
+ toggle.value ? trueBranch() : falseBranch()
)
// start enter
const instanceRef = ref<any>(null)
const App = {
render: () => {
- return h(
- KeepAlive,
- { include: 'Foo' },
- () => (toggle.value ? h(AsyncComp, { ref: instanceRef }) : null)
+ return h(KeepAlive, { include: 'Foo' }, () =>
+ toggle.value ? h(AsyncComp, { ref: instanceRef }) : null
)
}
}
const root = nodeOps.createElement('div')
const children = ref([h('div', 'teleported')])
- render(h(() => h(Teleport, { to: target }, children.value)), root)
+ render(
+ h(() => h(Teleport, { to: target }, children.value)),
+ root
+ )
expect(serializeInner(target)).toMatchInlineSnapshot(
`"<div>teleported</div>"`
)
it('should add each slot to the record when given slot is an array', () => {
const dynamicSlot = [
{ name: 'descriptor', fn: slot },
- [{ name: 'descriptor2', fn: slot }, { name: 'descriptor3', fn: slot }]
+ [
+ { name: 'descriptor2', fn: slot },
+ { name: 'descriptor3', fn: slot }
+ ]
]
const actual = createSlots(record, dynamicSlot)
})
it('should render an item for entry in an iterable', () => {
- const iterable = function*() {
+ const iterable = function* () {
yield 1
yield 2
yield 3
})
expect(
- (app.mount(svgContainer).$.subTree as VNode<Node, Element> & {
- el: Element
- }).el instanceof SVGElement
+ (
+ app.mount(svgContainer).$.subTree as VNode<Node, Element> & {
+ el: Element
+ }
+ ).el instanceof SVGElement
)
})
}
for (let n = 0; n < samples; ++n) {
- render(h('span', arr.map(n => spanNumWithOpacity(n, '1'))), root)
+ render(
+ h(
+ 'span',
+ arr.map(n => spanNumWithOpacity(n, '1'))
+ ),
+ root
+ )
elm = root.children[0] as TestElement
for (let i = 0; i < elms; ++i) {
expect(serializeInner(elm.children[i] as TestElement)).toBe(
i.toString()
)
- opacities[i] = Math.random()
- .toFixed(5)
- .toString()
+ opacities[i] = Math.random().toFixed(5).toString()
}
const shufArr = shuffle(arr.slice(0))
render(
- h('span', arr.map(n => spanNumWithOpacity(shufArr[n], opacities[n]))),
+ h(
+ 'span',
+ arr.map(n => spanNumWithOpacity(shufArr[n], opacities[n]))
+ ),
root
)
elm = root.children[0] as TestElement
const Child = {
props: ['value'],
setup(props: any, { emit }: SetupContext) {
- watch(() => props.value, (val: number) => emit('update', val))
+ watch(
+ () => props.value,
+ (val: number) => emit('update', val)
+ )
return () => {
return h('div', props.value)
const Comp = defineComponent({
setup(_props, { slots }) {
return () => {
- const vnode = (openBlock(),
- (block = createBlock('div', null, {
- default: withCtx(() => [renderSlot(slots, 'default')]),
- _: SlotFlags.FORWARDED
- })))
+ const vnode =
+ (openBlock(),
+ (block = createBlock('div', null, {
+ default: withCtx(() => [renderSlot(slots, 'default')]),
+ _: SlotFlags.FORWARDED
+ })))
return vnode
}
expect(block!.dynamicChildren![0].type).toBe(Fragment)
expect(block!.dynamicChildren![0].dynamicChildren!.length).toBe(1)
expect(
- serialize(block!.dynamicChildren![0].dynamicChildren![0]
- .el as TestElement)
+ serialize(
+ block!.dynamicChildren![0].dynamicChildren![0].el as TestElement
+ )
).toBe('<p>0</p>')
foo.value++
test('should work on slots', () => {
const Child = {
__scopeId: 'child',
- render: withChildId(function(this: any) {
+ render: withChildId(function (this: any) {
return h('div', renderSlot(this.$slots, 'default'))
})
}
})
test('handlers', () => {
- let clickHandler1 = function() {}
- let clickHandler2 = function() {}
- let focusHandler2 = function() {}
+ let clickHandler1 = function () {}
+ let clickHandler2 = function () {}
+ let focusHandler2 = function () {}
let props1: Data = { onClick: clickHandler1 }
let props2: Data = { onClick: clickHandler2, onFocus: focusHandler2 }
test('with patchFlags', () => {
const hoist = createVNode('div')
let vnode1
- const vnode = (openBlock(),
- createBlock('div', null, [
- hoist,
- (vnode1 = createVNode('div', null, 'text', PatchFlags.TEXT))
- ]))
+ const vnode =
+ (openBlock(),
+ createBlock('div', null, [
+ hoist,
+ (vnode1 = createVNode('div', null, 'text', PatchFlags.TEXT))
+ ]))
expect(vnode.dynamicChildren).toStrictEqual([vnode1])
})
test('should not track vnodes with only HYDRATE_EVENTS flag', () => {
const hoist = createVNode('div')
- const vnode = (openBlock(),
- createBlock('div', null, [
- hoist,
- createVNode('div', null, 'text', PatchFlags.HYDRATE_EVENTS)
- ]))
+ const vnode =
+ (openBlock(),
+ createBlock('div', null, [
+ hoist,
+ createVNode('div', null, 'text', PatchFlags.HYDRATE_EVENTS)
+ ]))
expect(vnode.dynamicChildren).toStrictEqual([])
})
test('many times call openBlock', () => {
const hoist = createVNode('div')
let vnode1, vnode2, vnode3
- const vnode = (openBlock(),
- createBlock('div', null, [
- hoist,
- (vnode1 = createVNode('div', null, 'text', PatchFlags.TEXT)),
- (vnode2 = (openBlock(),
+ const vnode =
+ (openBlock(),
createBlock('div', null, [
hoist,
- (vnode3 = createVNode('div', null, 'text', PatchFlags.TEXT))
- ])))
- ]))
+ (vnode1 = createVNode('div', null, 'text', PatchFlags.TEXT)),
+ (vnode2 =
+ (openBlock(),
+ createBlock('div', null, [
+ hoist,
+ (vnode3 = createVNode('div', null, 'text', PatchFlags.TEXT))
+ ])))
+ ]))
expect(vnode.dynamicChildren).toStrictEqual([vnode1, vnode2])
expect(vnode2.dynamicChildren).toStrictEqual([vnode3])
})
test('with stateful component', () => {
const hoist = createVNode('div')
let vnode1
- const vnode = (openBlock(),
- createBlock('div', null, [
- hoist,
- (vnode1 = createVNode({}, null, 'text'))
- ]))
+ const vnode =
+ (openBlock(),
+ createBlock('div', null, [
+ hoist,
+ (vnode1 = createVNode({}, null, 'text'))
+ ]))
expect(vnode.dynamicChildren).toStrictEqual([vnode1])
})
test('with functional component', () => {
const hoist = createVNode('div')
let vnode1
- const vnode = (openBlock(),
- createBlock('div', null, [
- hoist,
- (vnode1 = createVNode(() => {}, null, 'text'))
- ]))
+ const vnode =
+ (openBlock(),
+ createBlock('div', null, [
+ hoist,
+ (vnode1 = createVNode(() => {}, null, 'text'))
+ ]))
expect(vnode.dynamicChildren).toStrictEqual([vnode1])
})
test('with suspense', () => {
const hoist = createVNode('div')
let vnode1
- const vnode = (openBlock(),
- createBlock('div', null, [
- hoist,
- (vnode1 = createVNode(() => {}, null, 'text'))
- ]))
+ const vnode =
+ (openBlock(),
+ createBlock('div', null, [
+ hoist,
+ (vnode1 = createVNode(() => {}, null, 'text'))
+ ]))
expect(vnode.dynamicChildren).toStrictEqual([vnode1])
})
test('element block should track normalized slot children', () => {
const hoist = createVNode('div')
let vnode1: any
- const vnode = (openBlock(),
- createBlock('div', null, {
- default: () => {
- return [
- hoist,
- (vnode1 = createVNode('div', null, 'text', PatchFlags.TEXT))
- ]
- }
- }))
+ const vnode =
+ (openBlock(),
+ createBlock('div', null, {
+ default: () => {
+ return [
+ hoist,
+ (vnode1 = createVNode('div', null, 'text', PatchFlags.TEXT))
+ ]
+ }
+ }))
expect(vnode.dynamicChildren).toStrictEqual([vnode1])
})
test('openBlock w/ disableTracking: true', () => {
const hoist = createVNode('div')
let vnode1
- const vnode = (openBlock(),
- createBlock('div', null, [
- // a v-for fragment block generated by the compiler
- // disables tracking because it always diffs its
- // children.
- (vnode1 = (openBlock(true),
- createBlock(Fragment, null, [
- hoist,
- /*vnode2*/ createVNode(() => {}, null, 'text')
- ])))
- ]))
+ const vnode =
+ (openBlock(),
+ createBlock('div', null, [
+ // a v-for fragment block generated by the compiler
+ // disables tracking because it always diffs its
+ // children.
+ (vnode1 =
+ (openBlock(true),
+ createBlock(Fragment, null, [
+ hoist,
+ /*vnode2*/ createVNode(() => {}, null, 'text')
+ ])))
+ ]))
expect(vnode.dynamicChildren).toStrictEqual([vnode1])
expect(vnode1.dynamicChildren).toStrictEqual([])
})
test('openBlock without disableTracking: true', () => {
const hoist = createVNode('div')
let vnode1, vnode2
- const vnode = (openBlock(),
- createBlock('div', null, [
- (vnode1 = (openBlock(),
- createBlock(Fragment, null, [
- hoist,
- (vnode2 = createVNode(() => {}, null, 'text'))
- ])))
- ]))
+ const vnode =
+ (openBlock(),
+ createBlock('div', null, [
+ (vnode1 =
+ (openBlock(),
+ createBlock(Fragment, null, [
+ hoist,
+ (vnode2 = createVNode(() => {}, null, 'text'))
+ ])))
+ ]))
expect(vnode.dynamicChildren).toStrictEqual([vnode1])
expect(vnode1.dynamicChildren).toStrictEqual([vnode2])
})
test('should not track openBlock() when tracking is disabled', () => {
let vnode1
- const vnode = (openBlock(),
- createBlock('div', null, [
- setBlockTracking(-1),
- (vnode1 = (openBlock(), createBlock('div'))),
- setBlockTracking(1),
- vnode1
- ]))
+ const vnode =
+ (openBlock(),
+ createBlock('div', null, [
+ setBlockTracking(-1),
+ (vnode1 = (openBlock(), createBlock('div'))),
+ setBlockTracking(1),
+ vnode1
+ ]))
expect(vnode.dynamicChildren).toStrictEqual([])
})
})
let thisRequest: Promise<ConcreteComponent>
return (
pendingRequest ||
- (thisRequest = pendingRequest = loader()
- .catch(err => {
- err = err instanceof Error ? err : new Error(String(err))
- if (userOnError) {
- return new Promise((resolve, reject) => {
- const userRetry = () => resolve(retry())
- const userFail = () => reject(err)
- userOnError(err, userRetry, userFail, retries + 1)
- })
- } else {
- throw err
- }
- })
- .then((comp: any) => {
- if (thisRequest !== pendingRequest && pendingRequest) {
- return pendingRequest
- }
- if (__DEV__ && !comp) {
- warn(
- `Async component loader resolved to undefined. ` +
- `If you are using retry(), make sure to return its return value.`
- )
- }
- // interop module default
- if (
- comp &&
- (comp.__esModule || comp[Symbol.toStringTag] === 'Module')
- ) {
- comp = comp.default
- }
- if (__DEV__ && comp && !isObject(comp) && !isFunction(comp)) {
- throw new Error(`Invalid async component load result: ${comp}`)
- }
- resolvedComp = comp
- return comp
- }))
+ (thisRequest = pendingRequest =
+ loader()
+ .catch(err => {
+ err = err instanceof Error ? err : new Error(String(err))
+ if (userOnError) {
+ return new Promise((resolve, reject) => {
+ const userRetry = () => resolve(retry())
+ const userFail = () => reject(err)
+ userOnError(err, userRetry, userFail, retries + 1)
+ })
+ } else {
+ throw err
+ }
+ })
+ .then((comp: any) => {
+ if (thisRequest !== pendingRequest && pendingRequest) {
+ return pendingRequest
+ }
+ if (__DEV__ && !comp) {
+ warn(
+ `Async component loader resolved to undefined. ` +
+ `If you are using retry(), make sure to return its return value.`
+ )
+ }
+ // interop module default
+ if (
+ comp &&
+ (comp.__esModule || comp[Symbol.toStringTag] === 'Module')
+ ) {
+ comp = comp.default
+ }
+ if (__DEV__ && comp && !isObject(comp) && !isFunction(comp)) {
+ throw new Error(`Invalid async component load result: ${comp}`)
+ }
+ resolvedComp = comp
+ return comp
+ }))
)
}
type PluginInstallFunction = (app: App, ...options: any[]) => any
export type Plugin =
- | PluginInstallFunction & { install?: PluginInstallFunction }
+ | (PluginInstallFunction & { install?: PluginInstallFunction })
| {
install: PluginInstallFunction
}
}
}
-export const createHook = <T extends Function = () => any>(
- lifecycle: LifecycleHooks
-) => (hook: T, target: ComponentInternalInstance | null = currentInstance) =>
- // post-create lifecycle registrations are noops during SSR (except for serverPrefetch)
- (!isInSSRComponentSetup || lifecycle === LifecycleHooks.SERVER_PREFETCH) &&
- injectHook(lifecycle, hook, target)
+export const createHook =
+ <T extends Function = () => any>(lifecycle: LifecycleHooks) =>
+ (hook: T, target: ComponentInternalInstance | null = currentInstance) =>
+ // post-create lifecycle registrations are noops during SSR (except for serverPrefetch)
+ (!isInSSRComponentSetup || lifecycle === LifecycleHooks.SERVER_PREFETCH) &&
+ injectHook(lifecycle, hook, target)
export const onBeforeMount = createHook(LifecycleHooks.BEFORE_MOUNT)
export const onMounted = createHook(LifecycleHooks.MOUNTED)
type NotUndefined<T> = T extends undefined ? never : T
type InferDefaults<T> = {
- [K in keyof T]?: NotUndefined<T[K]> extends (
+ [K in keyof T]?: NotUndefined<T[K]> extends
| number
| string
| boolean
| symbol
- | Function)
+ | Function
? NotUndefined<T[K]>
: (props: T) => NotUndefined<T[K]>
}
type MapSources<T, Immediate> = {
[K in keyof T]: T[K] extends WatchSource<infer V>
- ? Immediate extends true ? (V | undefined) : V
+ ? Immediate extends true
+ ? V | undefined
+ : V
: T[K] extends object
- ? Immediate extends true ? (T[K] | undefined) : T[K]
- : never
+ ? Immediate extends true
+ ? T[K] | undefined
+ : T[K]
+ : never
}
type InvalidateCbRegistrator = (cb: () => void) => void
effect: WatchEffect,
options?: DebuggerOptions
) {
- return doWatch(effect, null, (__DEV__
- ? Object.assign(options || {}, { flush: 'post' })
- : { flush: 'post' }) as WatchOptionsBase)
+ return doWatch(
+ effect,
+ null,
+ (__DEV__
+ ? Object.assign(options || {}, { flush: 'post' })
+ : { flush: 'post' }) as WatchOptionsBase
+ )
}
// initial value for watchers to trigger on undefined initial values
// overload: single source + cb
export function watch<T, Immediate extends Readonly<boolean> = false>(
source: WatchSource<T>,
- cb: WatchCallback<T, Immediate extends true ? (T | undefined) : T>,
+ cb: WatchCallback<T, Immediate extends true ? T | undefined : T>,
options?: WatchOptions<Immediate>
): WatchStopHandle
Immediate extends Readonly<boolean> = false
>(
source: T,
- cb: WatchCallback<T, Immediate extends true ? (T | undefined) : T>,
+ cb: WatchCallback<T, Immediate extends true ? T | undefined : T>,
options?: WatchOptions<Immediate>
): WatchStopHandle
[DeprecationTypes.INSTANCE_ATTRS_CLASS_STYLE]: {
message: componentName =>
- `Component <${componentName ||
- 'Anonymous'}> has \`inheritAttrs: false\` but is ` +
+ `Component <${
+ componentName || 'Anonymous'
+ }> has \`inheritAttrs: false\` but is ` +
`relying on class/style fallthrough from parent. In Vue 3, class/style ` +
`are now included in $attrs and will no longer fallthrough when ` +
`inheritAttrs is false. If you are already using v-bind="$attrs" on ` +
`${name}="false" instead of removing it in Vue 3. To remove the attribute, ` +
`use \`null\` or \`undefined\` instead. If the usage is intended, ` +
`you can disable the compat behavior and suppress this warning with:` +
- `\n\n configureCompat({ ${
- DeprecationTypes.ATTR_FALSE_VALUE
- }: false })\n`,
+ `\n\n configureCompat({ ${DeprecationTypes.ATTR_FALSE_VALUE}: false })\n`,
link: `https://v3.vuejs.org/guide/migration/attribute-coercion.html`
},
`Always use explicit "true" or "false" values for enumerated attributes. ` +
`If the usage is intended, ` +
`you can disable the compat behavior and suppress this warning with:` +
- `\n\n configureCompat({ ${
- DeprecationTypes.ATTR_ENUMERATED_COERCION
- }: false })\n`,
+ `\n\n configureCompat({ ${DeprecationTypes.ATTR_ENUMERATED_COERCION}: false })\n`,
link: `https://v3.vuejs.org/guide/migration/attribute-coercion.html`
},
`default if no "tag" prop is specified. If you do not rely on the span ` +
`for styling, you can disable the compat behavior and suppress this ` +
`warning with:` +
- `\n\n configureCompat({ ${
- DeprecationTypes.TRANSITION_GROUP_ROOT
- }: false })\n`,
+ `\n\n configureCompat({ ${DeprecationTypes.TRANSITION_GROUP_ROOT}: false })\n`,
link: `https://v3.vuejs.org/guide/migration/transition-group.html`
},
`usage and intend to use plain functions for functional components, ` +
`you can disable the compat behavior and suppress this ` +
`warning with:` +
- `\n\n configureCompat({ ${
- DeprecationTypes.COMPONENT_ASYNC
- }: false })\n`
+ `\n\n configureCompat({ ${DeprecationTypes.COMPONENT_ASYNC}: false })\n`
)
},
link: `https://v3.vuejs.org/guide/migration/async-components.html`
message: (comp: ComponentOptions) => {
const configMsg =
`opt-in to ` +
- `Vue 3 behavior on a per-component basis with \`compatConfig: { ${
- DeprecationTypes.COMPONENT_V_MODEL
- }: false }\`.`
+ `Vue 3 behavior on a per-component basis with \`compatConfig: { ${DeprecationTypes.COMPONENT_V_MODEL}: false }\`.`
if (
comp.props &&
(isArray(comp.props)
message:
`Vue 3's render function API has changed. ` +
`You can opt-in to the new API with:` +
- `\n\n configureCompat({ ${
- DeprecationTypes.RENDER_FUNCTION
- }: false })\n` +
+ `\n\n configureCompat({ ${DeprecationTypes.RENDER_FUNCTION}: false })\n` +
`\n (This can also be done per-component via the "compatConfig" option.)`,
link: `https://v3.vuejs.org/guide/migration/render-function-api.html`
},
if (instance && config[DeprecationTypes.OPTIONS_DATA_MERGE] != null) {
warn(
- `Deprecation config "${
- DeprecationTypes.OPTIONS_DATA_MERGE
- }" can only be configured globally.`
+ `Deprecation config "${DeprecationTypes.OPTIONS_DATA_MERGE}" can only be configured globally.`
)
}
}
mergeBase[key] = isArray(superValue)
? superValue.slice()
: isObject(superValue)
- ? extend(Object.create(null), superValue)
- : superValue
+ ? extend(Object.create(null), superValue)
+ : superValue
}
SubVue.options = mergeOptions(
function convertLegacyProps(
legacyProps: LegacyVNodeProps | undefined,
type: any
-): Data & VNodeProps | null {
+): (Data & VNodeProps) | null {
if (!legacyProps) {
return null
}
if (isSync) {
const on = data.on || (data.on = {})
- on[`update:${key}`] = function($event: any) {
+ on[`update:${key}`] = function ($event: any) {
value[key] = $event
}
}
startMeasure(instance, `compile`)
}
const { isCustomElement, compilerOptions } = instance.appContext.config
- const {
- delimiters,
- compilerOptions: componentCompilerOptions
- } = Component
+ const { delimiters, compilerOptions: componentCompilerOptions } =
+ Component
const finalCompilerOptions: CompilerOptions = extend(
extend(
{
(__ESM_BUNDLER__
? ` Configure your bundler to alias "vue" to "vue/dist/vue.esm-bundler.js".`
: __ESM_BROWSER__
- ? ` Use "vue.esm-browser.js" instead.`
- : __GLOBAL__
- ? ` Use "vue.global.js" instead.`
- : ``) /* should not happen */
+ ? ` Use "vue.esm-browser.js" instead.`
+ : __GLOBAL__
+ ? ` Use "vue.global.js" instead.`
+ : ``) /* should not happen */
)
} else {
warn(`Component is missing template or render function.`)
// don't mark Boolean props as undefined
| BooleanConstructor
| { type: BooleanConstructor }
- ? T[K] extends { default: undefined | (() => undefined) } ? never : K
+ ? T[K] extends { default: undefined | (() => undefined) }
+ ? never
+ : K
: never
}[keyof T]
type InferPropType<T> = [T] extends [null]
? any // null & true would fail to infer
: [T] extends [{ type: null | true }]
- ? any // As TS issue https://github.com/Microsoft/TypeScript/issues/14829 // somehow `ObjectConstructor` when inferred from { (): T } becomes `any` // `BooleanConstructor` when inferred from PropConstructor(with PropMethod) becomes `Boolean`
- : [T] extends [ObjectConstructor | { type: ObjectConstructor }]
- ? Record<string, any>
- : [T] extends [BooleanConstructor | { type: BooleanConstructor }]
- ? boolean
- : [T] extends [DateConstructor | { type: DateConstructor }]
- ? Date
- : [T] extends [Prop<infer V, infer D>]
- ? (unknown extends V ? D : V)
- : T
+ ? any // As TS issue https://github.com/Microsoft/TypeScript/issues/14829 // somehow `ObjectConstructor` when inferred from { (): T } becomes `any` // `BooleanConstructor` when inferred from PropConstructor(with PropMethod) becomes `Boolean`
+ : [T] extends [ObjectConstructor | { type: ObjectConstructor }]
+ ? Record<string, any>
+ : [T] extends [BooleanConstructor | { type: BooleanConstructor }]
+ ? boolean
+ : [T] extends [DateConstructor | { type: DateConstructor }]
+ ? Date
+ : [T] extends [Prop<infer V, infer D>]
+ ? unknown extends V
+ ? D
+ : V
+ : T
export type ExtractPropTypes<O> = O extends object
? { [K in keyof O]?: unknown } & // This is needed to keep the relation between the option prop and the props, allowing to use ctrl+click to navigate to the prop options. see: #3656
setCurrentInstance(instance)
value = propsDefaults[key] = defaultValue.call(
__COMPAT__ &&
- isCompatEnabled(DeprecationTypes.PROPS_DEFAULT_THIS, instance)
+ isCompatEnabled(DeprecationTypes.PROPS_DEFAULT_THIS, instance)
? createPropsDefaultThis(instance, props, key)
: null,
props
export interface ComponentCustomProperties {}
type IsDefaultMixinComponent<T> = T extends ComponentOptionsMixin
- ? ComponentOptionsMixin extends T ? true : false
+ ? ComponentOptionsMixin extends T
+ ? true
+ : false
: false
type MixinToOptionTypes<T> = T extends ComponentOptionsBase<
export const PublicInstanceProxyHandlers: ProxyHandler<any> = {
get({ _: instance }: ComponentRenderContext, key: string) {
- const {
- ctx,
- setupState,
- data,
- props,
- accessCache,
- type,
- appContext
- } = instance
+ const { ctx, setupState, data, props, accessCache, type, appContext } =
+ instance
// for internal formatters to know that this is a Vue instance
if (__DEV__ && key === '__isVue') {
// export the public type for h/tsx inference
// also to avoid inline import() in generated d.ts files
-export const BaseTransition = (BaseTransitionImpl as any) as {
+export const BaseTransition = BaseTransitionImpl as any as {
new (): {
$props: BaseTransitionProps<any>
}
// export the public type for h/tsx inference
// also to avoid inline import() in generated d.ts files
-export const KeepAlive = (KeepAliveImpl as any) as {
+export const KeepAlive = KeepAliveImpl as any as {
__isKeepAlive: true
new (): {
$props: VNodeProps & KeepAliveProps
}
// Force-casted public typing for h and TSX props inference
-export const Suspense = ((__FEATURE_SUSPENSE__
- ? SuspenseImpl
- : null) as any) as {
+export const Suspense = (__FEATURE_SUSPENSE__ ? SuspenseImpl : null) as any as {
__isSuspense: true
new (): { $props: VNodeProps & SuspenseProps }
}
return
}
- const {
- vnode,
- activeBranch,
- parentComponent,
- container,
- isSVG
- } = suspense
+ const { vnode, activeBranch, parentComponent, container, isSVG } =
+ suspense
// invoke @fallback event
triggerEvent(vnode, 'onFallback')
}
// Force-casted public typing for h and TSX props inference
-export const Teleport = (TeleportImpl as any) as {
+export const Teleport = TeleportImpl as any as {
__isTeleport: true
new (): { $props: VNodeProps & TeleportProps }
}
DevtoolsHooks.COMPONENT_ADDED
)
-export const devtoolsComponentUpdated = /*#__PURE__*/ createDevtoolsComponentHook(
- DevtoolsHooks.COMPONENT_UPDATED
-)
+export const devtoolsComponentUpdated =
+ /*#__PURE__*/ createDevtoolsComponentHook(DevtoolsHooks.COMPONENT_UPDATED)
-export const devtoolsComponentRemoved = /*#__PURE__*/ createDevtoolsComponentHook(
- DevtoolsHooks.COMPONENT_REMOVED
-)
+export const devtoolsComponentRemoved =
+ /*#__PURE__*/ createDevtoolsComponentHook(DevtoolsHooks.COMPONENT_REMOVED)
function createDevtoolsComponentHook(hook: DevtoolsHooks) {
return (component: ComponentInternalInstance) => {
dynamicSlots: (
| CompiledSlotDescriptor
| CompiledSlotDescriptor[]
- | undefined)[]
+ | undefined
+ )[]
): Record<string, Slot> {
for (let i = 0; i < dynamicSlots.length; i++) {
const slot = dynamicSlots[i]
-export type UnionToIntersection<U> = (U extends any
- ? (k: U) => void
- : never) extends ((k: infer I) => void)
+export type UnionToIntersection<U> = (
+ U extends any ? (k: U) => void : never
+) extends (k: infer I) => void
? I
: never
typeof global !== 'undefined'
? global
: typeof self !== 'undefined'
- ? self
- : typeof window !== 'undefined'
- ? window
- : {}
+ ? self
+ : typeof window !== 'undefined'
+ ? window
+ : {}
globalObject.__VUE_HMR_RUNTIME__ = {
createRecord: tryWrap(createRecord),
if (
forcePatchValue ||
!optimized ||
- (patchFlag & PatchFlags.FULL_PROPS ||
- patchFlag & PatchFlags.HYDRATE_EVENTS)
+ patchFlag & PatchFlags.FULL_PROPS ||
+ patchFlag & PatchFlags.HYDRATE_EVENTS
) {
for (const key in props) {
if (
hasMismatch = true
__DEV__ &&
warn(
- `Hydration text content mismatch in <${vnode.type as string}>:\n` +
+ `Hydration text content mismatch in <${
+ vnode.type as string
+ }>:\n` +
`- Client: ${el.textContent}\n` +
`- Server: ${vnode.children as string}`
)
node.nodeType === DOMNodeTypes.TEXT
? `(text)`
: isComment(node) && node.data === '['
- ? `(start of fragment)`
- : ``
+ ? `(start of fragment)`
+ : ``
)
vnode.el = null
/**
* @internal only exposed in compat builds.
*/
-export const compatUtils = (__COMPAT__
- ? _compatUtils
- : null) as typeof _compatUtils
+export const compatUtils = (
+ __COMPAT__ ? _compatUtils : null
+) as typeof _compatUtils
// Ref macros ------------------------------------------------------------------
// for dts generation only
}
if (isAsyncWrapper(initialVNode)) {
- (initialVNode.type as ComponentOptions).__asyncLoader!().then(
+ ;(initialVNode.type as ComponentOptions).__asyncLoader!().then(
// note: we are moving the render call into an async callback,
// which means it won't track dependencies - but it's ok because
// a server-rendered async wrapper is already in resolved state
let hydrate: ReturnType<typeof createHydrationFunctions>[0] | undefined
let hydrateNode: ReturnType<typeof createHydrationFunctions>[1] | undefined
if (createHydrationFns) {
- ;[hydrate, hydrateNode] = createHydrationFns(internals as RendererInternals<
- Node,
- Element
- >)
+ ;[hydrate, hydrateNode] = createHydrationFns(
+ internals as RendererInternals<Node, Element>
+ )
}
return {
import { defineLegacyVNodeProperties } from './compat/renderFn'
import { convertLegacyRefInFor } from './compat/ref'
-export const Fragment = (Symbol(__DEV__ ? 'Fragment' : undefined) as any) as {
+export const Fragment = Symbol(__DEV__ ? 'Fragment' : undefined) as any as {
__isFragment: true
new (): {
$props: VNodeProps
export type VNodeNormalizedRef =
| VNodeNormalizedRefAtom
- | (VNodeNormalizedRefAtom)[]
+ | VNodeNormalizedRefAtom[]
type VNodeMountHook = (vnode: VNode) => void
type VNodeUpdateHook = (vnode: VNode, oldVNode: VNode) => void
key != null ? key : null
const normalizeRef = ({ ref }: VNodeProps): VNodeNormalizedRefAtom | null => {
- return (ref != null
- ? isString(ref) || isRef(ref) || isFunction(ref)
- ? { i: currentRenderingInstance, r: ref }
- : ref
- : null) as any
+ return (
+ ref != null
+ ? isString(ref) || isRef(ref) || isFunction(ref)
+ ? { i: currentRenderingInstance, r: ref }
+ : ref
+ : null
+ ) as any
}
function createBaseVNode(
export { createBaseVNode as createElementVNode }
-export const createVNode = (__DEV__
- ? createVNodeWithArgsTransform
- : _createVNode) as typeof _createVNode
+export const createVNode = (
+ __DEV__ ? createVNodeWithArgsTransform : _createVNode
+) as typeof _createVNode
function _createVNode(
type: VNodeTypes | ClassComponent | typeof NULL_DYNAMIC_COMPONENT,
const shapeFlag = isString(type)
? ShapeFlags.ELEMENT
: __FEATURE_SUSPENSE__ && isSuspense(type)
- ? ShapeFlags.SUSPENSE
- : isTeleport(type)
- ? ShapeFlags.TELEPORT
- : isObject(type)
- ? ShapeFlags.STATEFUL_COMPONENT
- : isFunction(type)
- ? ShapeFlags.FUNCTIONAL_COMPONENT
- : 0
+ ? ShapeFlags.SUSPENSE
+ : isTeleport(type)
+ ? ShapeFlags.TELEPORT
+ : isObject(type)
+ ? ShapeFlags.STATEFUL_COMPONENT
+ : isFunction(type)
+ ? ShapeFlags.FUNCTIONAL_COMPONENT
+ : 0
if (__DEV__ && shapeFlag & ShapeFlags.STATEFUL_COMPONENT && isProxy(type)) {
type = toRaw(type)
export function cloneVNode<T, U>(
vnode: VNode<T, U>,
- extraProps?: Data & VNodeProps | null,
+ extraProps?: (Data & VNodeProps) | null,
mergeRef = false
): VNode<T, U> {
// This is intentionally NOT using spread or extend to avoid the runtime
const withVModel = (node: VNode, arg: any, mods?: any) =>
withDirectives(node, [[vModelDynamic, arg, '', mods]])
-const setValue = function(this: any, value: any) {
+const setValue = function (this: any, value: any) {
this.value = value
}
})
test('it should support key modifiers and system modifiers', () => {
- const keyNames = ["ctrl","shift","meta","alt"]
+ const keyNames = ['ctrl', 'shift', 'meta', 'alt']
- keyNames.forEach(keyName=>{
+ keyNames.forEach(keyName => {
const el = document.createElement('div')
const fn = jest.fn()
// <div @keyup[keyName].esc="test"/>
'arrow-left'
])
patchEvent(el, 'onKeyup', null, nextValue, null)
-
+
triggerEvent(el, 'keyup', e => (e.key = 'a'))
expect(fn).not.toBeCalled()
-
+
triggerEvent(el, 'keyup', e => {
e[`${keyName}Key`] = false
e.key = 'esc'
})
expect(fn).not.toBeCalled()
-
+
triggerEvent(el, 'keyup', e => {
e[`${keyName}Key`] = true
e.key = 'Escape'
})
expect(fn).toBeCalledTimes(1)
-
+
triggerEvent(el, 'keyup', e => {
e[`${keyName}Key`] = true
e.key = 'ArrowLeft'
})
expect(fn).toBeCalledTimes(2)
- });
+ })
})
test('it should support "exact" modifier', () => {
const fn = jest.fn()
const handler = withModifiers(fn, [button])
patchEvent(el, 'onMousedown', null, handler, null)
- buttons.filter(b => b !== button).forEach(button => {
- triggerEvent(el, 'mousedown', e => (e.button = buttonCodes[button]))
- })
+ buttons
+ .filter(b => b !== button)
+ .forEach(button => {
+ triggerEvent(el, 'mousedown', e => (e.button = buttonCodes[button]))
+ })
expect(fn).not.toBeCalled()
triggerEvent(el, 'mousedown', e => (e.button = buttonCodes[button]))
expect(fn).toBeCalled()
setup() {
useCssVars(() => state)
return () =>
- h(
- Child,
- null,
- () => (value.value ? [h('div')] : [h('div'), h('div')])
+ h(Child, null, () =>
+ value.value ? [h('div')] : [h('div'), h('div')]
)
}
}
return defineCustomElement(options, hydrate)
}) as typeof defineCustomElement
-const BaseClass = (typeof HTMLElement !== 'undefined'
- ? HTMLElement
- : class {}) as typeof HTMLElement
+const BaseClass = (
+ typeof HTMLElement !== 'undefined' ? HTMLElement : class {}
+) as typeof HTMLElement
export class VueElement extends BaseClass {
/**
leaveToClass: String
}
-export const TransitionPropsValidators = (Transition.props = /*#__PURE__*/ extend(
- {},
- (BaseTransition as any).props,
- DOMTransitionPropsValidators
-))
+export const TransitionPropsValidators = (Transition.props =
+ /*#__PURE__*/ extend(
+ {},
+ (BaseTransition as any).props,
+ DOMTransitionPropsValidators
+ ))
/**
* #3227 Incoming hooks may be merged into arrays when wrapping Transition
const removeMode = (props: any) => delete props.mode
/*#__PURE__*/ removeMode(TransitionGroupImpl.props)
-export const TransitionGroup = (TransitionGroupImpl as unknown) as {
+export const TransitionGroup = TransitionGroupImpl as unknown as {
new (): {
$props: TransitionGroupProps
}
}
moveClass.split(/\s+/).forEach(c => c && clone.classList.add(c))
clone.style.display = 'none'
- const container = (root.nodeType === 1
- ? root
- : root.parentNode) as HTMLElement
+ const container = (
+ root.nodeType === 1 ? root : root.parentNode
+ ) as HTMLElement
container.appendChild(clone)
const { hasTransform } = getTransitionInfo(clone)
container.removeChild(clone)
addEventListener(el, 'change', () => {
const selectedVal = Array.prototype.filter
.call(el.options, (o: HTMLOptionElement) => o.selected)
- .map(
- (o: HTMLOptionElement) =>
- number ? toNumber(getValue(o)) : getValue(o)
+ .map((o: HTMLOptionElement) =>
+ number ? toNumber(getValue(o)) : getValue(o)
)
el._assign(
el.multiple
compatUtils.isCompatEnabled(DeprecationTypes.CONFIG_KEY_CODES, instance)
) {
if (instance) {
- globalKeyCodes = ((instance.appContext.config as any) as LegacyConfig)
+ globalKeyCodes = (instance.appContext.config as any as LegacyConfig)
.keyCodes
}
}
value === null
? 'false'
: typeof value !== 'boolean' && value !== undefined
- ? 'true'
- : null
+ ? 'true'
+ : null
if (
v2CocercedValue &&
compatUtils.softAssertCompatEnabled(
// classes into account.
const transitionClasses = (el as ElementWithTransition)._vtc
if (transitionClasses) {
- value = (value
- ? [value, ...transitionClasses]
- : [...transitionClasses]
+ value = (
+ value ? [value, ...transitionClasses] : [...transitionClasses]
).join(' ')
}
if (value == null) {
key[0] === '.'
? ((key = key.slice(1)), true)
: key[0] === '^'
- ? ((key = key.slice(1)), false)
- : shouldSetAsProp(el, key, nextValue, isSVG)
+ ? ((key = key.slice(1)), false)
+ : shouldSetAsProp(el, key, nextValue, isSVG)
) {
patchDOMProp(
el,
return isOn(key) || value == null
? ``
: value === ``
- ? key
- : `${key}=${JSON.stringify(value)}`
+ ? key
+ : `${key}=${JSON.stringify(value)}`
})
.filter(Boolean)
.join(' ')
test('with client-compiled vnode slots', async () => {
const Child = {
__scopeId: 'data-v-child',
- render: function(this: any) {
+ render: function (this: any) {
return h('div', null, [renderSlot(this.$slots, 'default')])
}
}
renderError = e
}
expect(renderError).toBe(null)
- expect(((capturedError as unknown) as Error).message).toBe('An error')
+ expect((capturedError as unknown as Error).message).toBe('An error')
})
})
}
})
it('should render an item for entry in an iterable', () => {
- const iterable = function*() {
+ const iterable = function* () {
yield 1
yield 2
yield 3
isNativeTag: instance.appContext.config.isNativeTag || NO,
onError(err: CompilerError) {
if (__DEV__) {
- const message = `[@vue/server-renderer] Template compilation error: ${
- err.message
- }`
+ const message = `[@vue/server-renderer] Template compilation error: ${err.message}`
const codeFrame =
err.loc &&
generateCodeFrame(
case 'radio':
return looseEqual(model, value) ? ' checked' : ''
case 'checkbox':
- return (isArray(model)
- ? ssrLooseContain(model, value)
- : model)
+ return (isArray(model) ? ssrLooseContain(model, value) : model)
? ' checked'
: ''
default:
case 'radio':
return looseEqual(model, value) ? { checked: true } : null
case 'checkbox':
- return (isArray(model)
- ? ssrLooseContain(model, value)
- : model)
+ return (isArray(model) ? ssrLooseContain(model, value) : model)
? { checked: true }
: null
default:
for (const key in context.__teleportBuffers) {
// note: it's OK to await sequentially here because the Promises were
// created eagerly in parallel.
- context.teleports[key] = await unrollBuffer((await Promise.all(
- context.__teleportBuffers[key]
- )) as SSRBuffer)
+ context.teleports[key] = await unrollBuffer(
+ (await Promise.all(context.__teleportBuffers[key])) as SSRBuffer
+ )
}
}
}
return [code, compiledScript.bindings]
} catch (e) {
- store.errors = [
- e.stack
- .split('\n')
- .slice(0, 12)
- .join('\n')
- ]
+ store.errors = [e.stack.split('\n').slice(0, 12).join('\n')]
return
}
} else {
const date2 = new Date(2019, 1, 2, 3, 4, 5, 7)
const file1 = new File([''], 'filename.txt', {
type: 'text/plain',
- lastModified: date1.getTime(),
+ lastModified: date1.getTime()
})
const file2 = new File([''], 'filename.txt', {
type: 'text/plain',
- lastModified: date1.getTime(),
+ lastModified: date1.getTime()
})
const file3 = new File([''], 'filename.txt', {
type: 'text/plain',
- lastModified: date2.getTime(),
+ lastModified: date2.getTime()
})
const file4 = new File([''], 'filename.csv', {
type: 'text/csv',
- lastModified: date1.getTime(),
+ lastModified: date1.getTime()
})
const file5 = new File(['abcdef'], 'filename.txt', {
type: 'text/plain',
- lastModified: date1.getTime(),
+ lastModified: date1.getTime()
})
const file6 = new File(['12345'], 'filename.txt', {
type: 'text/plain',
- lastModified: date1.getTime(),
+ lastModified: date1.getTime()
})
// Identical file object references
const date1 = new Date(2019, 1, 2, 3, 4, 5, 6)
const file1 = new File([''], 'filename.txt', {
type: 'text/plain',
- lastModified: date1.getTime(),
+ lastModified: date1.getTime()
})
expect(looseEqual(123, '123')).toBe(true)
})
test('handles array correctly', () => {
- expect(normalizeClass(['foo', undefined, true, false, 'bar'])).toEqual('foo bar')
+ expect(normalizeClass(['foo', undefined, true, false, 'bar'])).toEqual(
+ 'foo bar'
+ )
})
test('handles object correctly', () => {
/**
* @private
*/
-export const camelize = cacheStringFunction(
- (str: string): string => {
- return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''))
- }
-)
+export const camelize = cacheStringFunction((str: string): string => {
+ return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''))
+})
const hyphenateRE = /\B([A-Z])/g
/**
/**
* @private
*/
-export const toHandlerKey = cacheStringFunction(
- (str: string) => (str ? `on${capitalize(str)}` : ``)
+export const toHandlerKey = cacheStringFunction((str: string) =>
+ str ? `on${capitalize(str)}` : ``
)
// compare whether a value has changed, accounting for NaN.
typeof globalThis !== 'undefined'
? globalThis
: typeof self !== 'undefined'
- ? self
- : typeof window !== 'undefined'
- ? window
- : typeof global !== 'undefined'
- ? global
- : {})
+ ? self
+ : typeof window !== 'undefined'
+ ? window
+ : typeof global !== 'undefined'
+ ? global
+ : {})
)
}
return val == null
? ''
: isObject(val)
- ? JSON.stringify(val, replacer, 2)
- : String(val)
+ ? JSON.stringify(val, replacer, 2)
+ : String(val)
}
const replacer = (_key: string, val: any) => {
lastSuccessfulMap = new SourceMapConsumer(map!)
lastSuccessfulMap!.computeColumnSpans()
} catch (e) {
- lastSuccessfulCode = `/* ERROR: ${
- e.message
- } (see console for more info) */`
+ lastSuccessfulCode = `/* ERROR: ${e.message} (see console for more info) */`
console.error(e)
}
return lastSuccessfulCode
if (
pos.line != null &&
pos.column != null &&
- !// ignore mock location
- (pos.line === 1 && pos.column === 0)
+ !(
+ // ignore mock location
+ (pos.line === 1 && pos.column === 0)
+ )
) {
const translatedPos = {
column: pos.column + 1,
h(
'a',
{
- href:
- 'https://app.netlify.com/sites/vue-next-template-explorer/deploys',
+ href: 'https://app.netlify.com/sites/vue-next-template-explorer/deploys',
target: `_blank`
},
'History'
checked: compilerOptions.hoistStatic && !isSSR,
disabled: isSSR,
onChange(e: Event) {
- compilerOptions.hoistStatic = (e.target as HTMLInputElement).checked
+ compilerOptions.hoistStatic = (
+ e.target as HTMLInputElement
+ ).checked
}
}),
h('label', { for: 'hoist' }, 'hoistStatic')
checked: usePrefix && compilerOptions.cacheHandlers && !isSSR,
disabled: !usePrefix || isSSR,
onChange(e: Event) {
- compilerOptions.cacheHandlers = (e.target as HTMLInputElement).checked
+ compilerOptions.cacheHandlers = (
+ e.target as HTMLInputElement
+ ).checked
}
}),
h('label', { for: 'cache' }, 'cacheHandlers')
id: 'inline',
checked: compilerOptions.inline,
onChange(e: Event) {
- compilerOptions.inline = (e.target as HTMLInputElement).checked
+ compilerOptions.inline = (
+ e.target as HTMLInputElement
+ ).checked
}
}),
h('label', { for: 'inline' }, 'inline')
id: 'compat',
checked: compilerOptions.compatConfig!.MODE === 2,
onChange(e: Event) {
- compilerOptions.compatConfig!.MODE = (e.target as HTMLInputElement)
- .checked
+ compilerOptions.compatConfig!.MODE = (
+ e.target as HTMLInputElement
+ ).checked
? 2
: 3
}
)
expect(
- (deprecationData[DeprecationTypes.COMPONENT_FUNCTIONAL]
- .message as Function)(func)
+ (
+ deprecationData[DeprecationTypes.COMPONENT_FUNCTIONAL].message as Function
+ )(func)
).toHaveBeenWarned()
})
}
function reverse(v: string) {
- return v
- .split('')
- .reverse()
- .join('')
+ return v.split('').reverse().join('')
}
function double(v: number) {
})
it('should not merge nested mixins created with Vue.extend', () => {
- const a = jest.fn();
- const b = jest.fn();
- const c = jest.fn();
- const d = jest.fn();
+ const a = jest.fn()
+ const b = jest.fn()
+ const c = jest.fn()
+ const d = jest.fn()
const A = Vue.extend({
created: a
})
const D = Vue.extend({
mixins: [C],
created: d,
- render() { return null },
+ render() {
+ return null
+ }
})
new D().$mount()
expect(a.mock.calls.length).toStrictEqual(1)
})
test('method this context', () => {
- Vue.prototype.$test = function() {
+ Vue.prototype.$test = function () {
return this.msg
}
const vm = new Vue({
})
it('$on', () => {
- vm.$on('test', function(this: any) {
+ vm.$on('test', function (this: any) {
// expect correct context
expect(this).toBe(vm)
spy.apply(this, arguments)
})
it('$on multi event', () => {
- vm.$on(['test1', 'test2'], function(this: any) {
+ vm.$on(['test1', 'test2'], function (this: any) {
expect(this).toBe(vm)
spy.apply(this, arguments)
})
vm.$mount()
expect(spy).toHaveBeenCalled()
expect(
- (deprecationData[DeprecationTypes.INSTANCE_EVENT_HOOKS]
- .message as Function)('hook:mounted')
+ (
+ deprecationData[DeprecationTypes.INSTANCE_EVENT_HOOKS]
+ .message as Function
+ )('hook:mounted')
).toHaveBeenWarned()
})
}).$mount()
expect(spy).toHaveBeenCalled()
expect(
- (deprecationData[DeprecationTypes.INSTANCE_EVENT_HOOKS]
- .message as Function)('hook:mounted')
+ (
+ deprecationData[DeprecationTypes.INSTANCE_EVENT_HOOKS]
+ .message as Function
+ )('hook:mounted')
).toHaveBeenWarned()
})
})
)
expect(
- (deprecationData[DeprecationTypes.INSTANCE_ATTRS_CLASS_STYLE]
- .message as Function)('Anonymous')
+ (
+ deprecationData[DeprecationTypes.INSTANCE_ATTRS_CLASS_STYLE]
+ .message as Function
+ )('Anonymous')
).toHaveBeenWarned()
})
expect(vm.$el.getAttribute('spellcheck')).toBe('true')
expect(vm.$el.getAttribute('contenteditable')).toBe('true')
expect(
- (deprecationData[DeprecationTypes.ATTR_ENUMERATED_COERCION]
- .message as Function)('draggable', null, 'false')
+ (
+ deprecationData[DeprecationTypes.ATTR_ENUMERATED_COERCION]
+ .message as Function
+ )('draggable', null, 'false')
).toHaveBeenWarned()
expect(
- (deprecationData[DeprecationTypes.ATTR_ENUMERATED_COERCION]
- .message as Function)('spellcheck', 0, 'true')
+ (
+ deprecationData[DeprecationTypes.ATTR_ENUMERATED_COERCION]
+ .message as Function
+ )('spellcheck', 0, 'true')
).toHaveBeenWarned()
expect(
- (deprecationData[DeprecationTypes.ATTR_ENUMERATED_COERCION]
- .message as Function)('contenteditable', 'foo', 'true')
+ (
+ deprecationData[DeprecationTypes.ATTR_ENUMERATED_COERCION]
+ .message as Function
+ )('contenteditable', 'foo', 'true')
).toHaveBeenWarned()
})
// with keys that cannot be mangled, and can be quite heavy size-wise.
// In the global build we know `Vue` is available globally so we can avoid
// the wildcard object.
- const render = (__GLOBAL__
- ? new Function(code)()
- : new Function('Vue', code)(runtimeDom)) as RenderFunction
+ const render = (
+ __GLOBAL__ ? new Function(code)() : new Function('Vue', code)(runtimeDom)
+ ) as RenderFunction
// mark the function as runtime compiled
;(render as InternalRenderFunction)._rc = true
(__ESM_BUNDLER__
? ` Configure your bundler to alias "vue" to "@vue/compat/dist/vue.esm-bundler.js".`
: __ESM_BROWSER__
- ? ` Use "vue.esm-browser.js" instead.`
- : __GLOBAL__
- ? ` Use "vue.global.js" instead.`
- : ``) /* should not happen */
+ ? ` Use "vue.esm-browser.js" instead.`
+ : __GLOBAL__
+ ? ` Use "vue.global.js" instead.`
+ : ``) /* should not happen */
)
}
}) as any
import { h, createApp, Transition, ref, nextTick } from 'vue'
describe('e2e: Transition', () => {
- const {
- page,
- html,
- classList,
- isVisible,
- timeout,
- nextFrame,
- click
- } = setupPuppeteer()
+ const { page, html, classList, isVisible, timeout, nextFrame, click } =
+ setupPuppeteer()
const baseUrl = `file://${path.resolve(__dirname, './transition.html')}`
const duration = process.env.CI ? 200 : 50
const classWhenTransitionStart = () =>
page().evaluate(() => {
- (document.querySelector('#toggleBtn') as any)!.click()
+ ;(document.querySelector('#toggleBtn') as any)!.click()
return Promise.resolve().then(() => {
return document.querySelector('#container div')!.className.split(/\s+/g)
})
// change view -> 'two'
await page().evaluate(() => {
- (document.querySelector('#changeViewBtn') as any)!.click()
+ ;(document.querySelector('#changeViewBtn') as any)!.click()
})
// enter
expect(await classWhenTransitionStart()).toStrictEqual([
// change view -> 'one'
await page().evaluate(() => {
- (document.querySelector('#changeViewBtn') as any)!.click()
+ ;(document.querySelector('#changeViewBtn') as any)!.click()
})
// leave
expect(await classWhenTransitionStart()).toStrictEqual([
// enter
const enterClass = await page().evaluate(async () => {
- (document.querySelector('#toggleBtn') as any)!.click()
+ ;(document.querySelector('#toggleBtn') as any)!.click()
// nextTrick for patch start
await Promise.resolve()
// nextTrick for Suspense resolve
const root = document.createElement('div')
createApp({
render() {
- return h(
- MyTransition,
- { onLeave: () => outerSpy() },
- () => (toggle.value ? h('div') : null)
+ return h(MyTransition, { onLeave: () => outerSpy() }, () =>
+ toggle.value ? h('div') : null
)
}
}).mount(root)
const htmlWhenTransitionStart = () =>
page().evaluate(() => {
- (document.querySelector('#toggleBtn') as any)!.click()
+ ;(document.querySelector('#toggleBtn') as any)!.click()
return Promise.resolve().then(() => {
return document.querySelector('#container')!.innerHTML
})
message: 'test: add test for runtime-dom/modules/class (#75)',
tree: {
sha: 'f53f761827af281db86c31d113086c068c1d0789',
- url:
- 'https://api.github.com/repos/vuejs/vue-next/git/trees/f53f761827af281db86c31d113086c068c1d0789'
+ url: 'https://api.github.com/repos/vuejs/vue-next/git/trees/f53f761827af281db86c31d113086c068c1d0789'
},
- url:
- 'https://api.github.com/repos/vuejs/vue-next/git/commits/d1527fbee422c7170e56845e55b49c4fd6de72a7',
+ url: 'https://api.github.com/repos/vuejs/vue-next/git/commits/d1527fbee422c7170e56845e55b49c4fd6de72a7',
comment_count: 0,
verification: {
verified: false,
payload: null
}
},
- url:
- 'https://api.github.com/repos/vuejs/vue-next/commits/d1527fbee422c7170e56845e55b49c4fd6de72a7',
+ url: 'https://api.github.com/repos/vuejs/vue-next/commits/d1527fbee422c7170e56845e55b49c4fd6de72a7',
html_url:
'https://github.com/vuejs/vue-next/commit/d1527fbee422c7170e56845e55b49c4fd6de72a7',
comments_url:
parents: [
{
sha: '2383b45e322272ddc102d6914c149b284a25d04f',
- url:
- 'https://api.github.com/repos/vuejs/vue-next/commits/2383b45e322272ddc102d6914c149b284a25d04f',
+ url: 'https://api.github.com/repos/vuejs/vue-next/commits/2383b45e322272ddc102d6914c149b284a25d04f',
html_url:
'https://github.com/vuejs/vue-next/commit/2383b45e322272ddc102d6914c149b284a25d04f'
}
message: 'chore: fix typo (#530) [ci skip]',
tree: {
sha: '2a5872ff8dc8ccb8121abd7e890ac3c0c9f1209f',
- url:
- 'https://api.github.com/repos/vuejs/vue-next/git/trees/2a5872ff8dc8ccb8121abd7e890ac3c0c9f1209f'
+ url: 'https://api.github.com/repos/vuejs/vue-next/git/trees/2a5872ff8dc8ccb8121abd7e890ac3c0c9f1209f'
},
- url:
- 'https://api.github.com/repos/vuejs/vue-next/git/commits/2383b45e322272ddc102d6914c149b284a25d04f',
+ url: 'https://api.github.com/repos/vuejs/vue-next/git/commits/2383b45e322272ddc102d6914c149b284a25d04f',
comment_count: 0,
verification: {
verified: false,
payload: null
}
},
- url:
- 'https://api.github.com/repos/vuejs/vue-next/commits/2383b45e322272ddc102d6914c149b284a25d04f',
+ url: 'https://api.github.com/repos/vuejs/vue-next/commits/2383b45e322272ddc102d6914c149b284a25d04f',
html_url:
'https://github.com/vuejs/vue-next/commit/2383b45e322272ddc102d6914c149b284a25d04f',
comments_url:
parents: [
{
sha: 'e7e1314cccd1a66fcf8b8526ec21350ec16cc3ad',
- url:
- 'https://api.github.com/repos/vuejs/vue-next/commits/e7e1314cccd1a66fcf8b8526ec21350ec16cc3ad',
+ url: 'https://api.github.com/repos/vuejs/vue-next/commits/e7e1314cccd1a66fcf8b8526ec21350ec16cc3ad',
html_url:
'https://github.com/vuejs/vue-next/commit/e7e1314cccd1a66fcf8b8526ec21350ec16cc3ad'
}
message: 'test: fix warning',
tree: {
sha: 'd942b17681e2e2fbbcd2ee04092390c7f2cf534d',
- url:
- 'https://api.github.com/repos/vuejs/vue-next/git/trees/d942b17681e2e2fbbcd2ee04092390c7f2cf534d'
+ url: 'https://api.github.com/repos/vuejs/vue-next/git/trees/d942b17681e2e2fbbcd2ee04092390c7f2cf534d'
},
- url:
- 'https://api.github.com/repos/vuejs/vue-next/git/commits/e7e1314cccd1a66fcf8b8526ec21350ec16cc3ad',
+ url: 'https://api.github.com/repos/vuejs/vue-next/git/commits/e7e1314cccd1a66fcf8b8526ec21350ec16cc3ad',
comment_count: 0,
verification: {
verified: false,
payload: null
}
},
- url:
- 'https://api.github.com/repos/vuejs/vue-next/commits/e7e1314cccd1a66fcf8b8526ec21350ec16cc3ad',
+ url: 'https://api.github.com/repos/vuejs/vue-next/commits/e7e1314cccd1a66fcf8b8526ec21350ec16cc3ad',
html_url:
'https://github.com/vuejs/vue-next/commit/e7e1314cccd1a66fcf8b8526ec21350ec16cc3ad',
comments_url:
parents: [
{
sha: '12ec62e6881f83dfa6c7f8a3c3650ec2567e6b1e',
- url:
- 'https://api.github.com/repos/vuejs/vue-next/commits/12ec62e6881f83dfa6c7f8a3c3650ec2567e6b1e',
+ url: 'https://api.github.com/repos/vuejs/vue-next/commits/12ec62e6881f83dfa6c7f8a3c3650ec2567e6b1e',
html_url:
'https://github.com/vuejs/vue-next/commit/12ec62e6881f83dfa6c7f8a3c3650ec2567e6b1e'
}
message: 'chore: fix tests',
tree: {
sha: '6ac7bd078a6eb0ad32b5102e0c5d2c29f2b20a48',
- url:
- 'https://api.github.com/repos/vuejs/vue-next/git/trees/6ac7bd078a6eb0ad32b5102e0c5d2c29f2b20a48'
+ url: 'https://api.github.com/repos/vuejs/vue-next/git/trees/6ac7bd078a6eb0ad32b5102e0c5d2c29f2b20a48'
},
- url:
- 'https://api.github.com/repos/vuejs/vue-next/git/commits/ecf4da822eea97f5db5fa769d39f994755384a4b',
+ url: 'https://api.github.com/repos/vuejs/vue-next/git/commits/ecf4da822eea97f5db5fa769d39f994755384a4b',
comment_count: 0,
verification: {
verified: false,
payload: null
}
},
- url:
- 'https://api.github.com/repos/vuejs/vue-next/commits/ecf4da822eea97f5db5fa769d39f994755384a4b',
+ url: 'https://api.github.com/repos/vuejs/vue-next/commits/ecf4da822eea97f5db5fa769d39f994755384a4b',
html_url:
'https://github.com/vuejs/vue-next/commit/ecf4da822eea97f5db5fa769d39f994755384a4b',
comments_url:
parents: [
{
sha: 'ca296812d54aff123472d7147b83fddfb634d9bc',
- url:
- 'https://api.github.com/repos/vuejs/vue-next/commits/ca296812d54aff123472d7147b83fddfb634d9bc',
+ url: 'https://api.github.com/repos/vuejs/vue-next/commits/ca296812d54aff123472d7147b83fddfb634d9bc',
html_url:
'https://github.com/vuejs/vue-next/commit/ca296812d54aff123472d7147b83fddfb634d9bc'
}
message: 'refactor: bring back clone for reused nodes',
tree: {
sha: '2cec32c97686e0ee9af1b87f0abdbbbdc18b6de6',
- url:
- 'https://api.github.com/repos/vuejs/vue-next/git/trees/2cec32c97686e0ee9af1b87f0abdbbbdc18b6de6'
+ url: 'https://api.github.com/repos/vuejs/vue-next/git/trees/2cec32c97686e0ee9af1b87f0abdbbbdc18b6de6'
},
- url:
- 'https://api.github.com/repos/vuejs/vue-next/git/commits/ca296812d54aff123472d7147b83fddfb634d9bc',
+ url: 'https://api.github.com/repos/vuejs/vue-next/git/commits/ca296812d54aff123472d7147b83fddfb634d9bc',
comment_count: 0,
verification: {
verified: false,
payload: null
}
},
- url:
- 'https://api.github.com/repos/vuejs/vue-next/commits/ca296812d54aff123472d7147b83fddfb634d9bc',
+ url: 'https://api.github.com/repos/vuejs/vue-next/commits/ca296812d54aff123472d7147b83fddfb634d9bc',
html_url:
'https://github.com/vuejs/vue-next/commit/ca296812d54aff123472d7147b83fddfb634d9bc',
comments_url:
parents: [
{
sha: 'e6be55a4989edb6f8750dbaa14eb693ec1f0d67b',
- url:
- 'https://api.github.com/repos/vuejs/vue-next/commits/e6be55a4989edb6f8750dbaa14eb693ec1f0d67b',
+ url: 'https://api.github.com/repos/vuejs/vue-next/commits/e6be55a4989edb6f8750dbaa14eb693ec1f0d67b',
html_url:
'https://github.com/vuejs/vue-next/commit/e6be55a4989edb6f8750dbaa14eb693ec1f0d67b'
}
message: 'chore: relax render type for tsx',
tree: {
sha: '7e2b3bb92ab91f755b2251e4a7903e6dd2042602',
- url:
- 'https://api.github.com/repos/vuejs/vue-next/git/trees/7e2b3bb92ab91f755b2251e4a7903e6dd2042602'
+ url: 'https://api.github.com/repos/vuejs/vue-next/git/trees/7e2b3bb92ab91f755b2251e4a7903e6dd2042602'
},
- url:
- 'https://api.github.com/repos/vuejs/vue-next/git/commits/e6be55a4989edb6f8750dbaa14eb693ec1f0d67b',
+ url: 'https://api.github.com/repos/vuejs/vue-next/git/commits/e6be55a4989edb6f8750dbaa14eb693ec1f0d67b',
comment_count: 0,
verification: {
verified: false,
payload: null
}
},
- url:
- 'https://api.github.com/repos/vuejs/vue-next/commits/e6be55a4989edb6f8750dbaa14eb693ec1f0d67b',
+ url: 'https://api.github.com/repos/vuejs/vue-next/commits/e6be55a4989edb6f8750dbaa14eb693ec1f0d67b',
html_url:
'https://github.com/vuejs/vue-next/commit/e6be55a4989edb6f8750dbaa14eb693ec1f0d67b',
comments_url:
parents: [
{
sha: 'ccc835caff0344baad3c92ce786ad4f804bf667b',
- url:
- 'https://api.github.com/repos/vuejs/vue-next/commits/ccc835caff0344baad3c92ce786ad4f804bf667b',
+ url: 'https://api.github.com/repos/vuejs/vue-next/commits/ccc835caff0344baad3c92ce786ad4f804bf667b',
html_url:
'https://github.com/vuejs/vue-next/commit/ccc835caff0344baad3c92ce786ad4f804bf667b'
}
// with keys that cannot be mangled, and can be quite heavy size-wise.
// In the global build we know `Vue` is available globally so we can avoid
// the wildcard object.
- const render = (__GLOBAL__
- ? new Function(code)()
- : new Function('Vue', code)(runtimeDom)) as RenderFunction
+ const render = (
+ __GLOBAL__ ? new Function(code)() : new Function('Vue', code)(runtimeDom)
+ ) as RenderFunction
// mark the function as runtime compiled
;(render as InternalRenderFunction)._rc = true
(__ESM_BUNDLER__
? ` Configure your bundler to alias "vue" to "vue/dist/vue.esm-bundler.js".`
: __ESM_BROWSER__
- ? ` Use "vue.esm-browser.js" instead.`
- : __GLOBAL__
- ? ` Use "vue.global.js" instead.`
- : ``) /* should not happen */
+ ? ` Use "vue.esm-browser.js" instead.`
+ : __GLOBAL__
+ ? ` Use "vue.global.js" instead.`
+ : ``) /* should not happen */
)
}
}