hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 6, "code_window": [ " addTransitionClass(el, leaveFromClass)\n", " nextFrame(() => {\n", " const resolve = () => finishLeave(el, done)\n", " onLeave && callHookWithErrorHandling(onLeave as Hook, [el, resolve])\n", " removeTransitionClass(el, leaveFromClass)\n", " addTransitionClass(el, leaveToClass)\n", " if (!(onLeave && onLeave.length > 1)) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " callHook(onLeave, [el, resolve])\n" ], "file_path": "packages/runtime-dom/src/components/Transition.ts", "type": "replace", "edit_start_line_idx": 160 }
import { NodeTypes, ElementNode, locStub, Namespaces, ElementTypes, VNodeCall } from '../src' import { isString, PatchFlags, PatchFlagNames, isArray } from '@vue/shared' const leadingBracketRE = /^\[/ const bracketsRE = /^\[|\]$/g // Create a matcher for an object // where non-static expressions should be wrapped in [] // e.g. // - createObjectMatcher({ 'foo': '[bar]' }) matches { foo: bar } // - createObjectMatcher({ '[foo]': 'bar' }) matches { [foo]: "bar" } export function createObjectMatcher(obj: Record<string, any>) { return { type: NodeTypes.JS_OBJECT_EXPRESSION, properties: Object.keys(obj).map(key => ({ type: NodeTypes.JS_PROPERTY, key: { type: NodeTypes.SIMPLE_EXPRESSION, content: key.replace(bracketsRE, ''), isStatic: !leadingBracketRE.test(key) }, value: isString(obj[key]) ? { type: NodeTypes.SIMPLE_EXPRESSION, content: obj[key].replace(bracketsRE, ''), isStatic: !leadingBracketRE.test(obj[key]) } : obj[key] })) } } export function createElementWithCodegen( tag: VNodeCall['tag'], props?: VNodeCall['props'], children?: VNodeCall['children'], patchFlag?: VNodeCall['patchFlag'], dynamicProps?: VNodeCall['dynamicProps'] ): ElementNode { return { type: NodeTypes.ELEMENT, loc: locStub, ns: Namespaces.HTML, tag: 'div', tagType: ElementTypes.ELEMENT, isSelfClosing: false, props: [], children: [], codegenNode: { type: NodeTypes.VNODE_CALL, tag, props, children, patchFlag, dynamicProps, directives: undefined, isBlock: false, disableTracking: false, loc: locStub } } } export function genFlagText(flag: PatchFlags | PatchFlags[]) { if (isArray(flag)) { let f = 0 flag.forEach(ff => { f |= ff }) return `${f} /* ${flag.map(f => PatchFlagNames[f]).join(', ')} */` } else { return `${flag} /* ${PatchFlagNames[flag]} */` } }
packages/compiler-core/__tests__/testUtils.ts
0
https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02
[ 0.00017462274990975857, 0.0001712702796794474, 0.00016543164383620024, 0.00017180366558022797, 0.0000027310309178574244 ]
{ "id": 6, "code_window": [ " addTransitionClass(el, leaveFromClass)\n", " nextFrame(() => {\n", " const resolve = () => finishLeave(el, done)\n", " onLeave && callHookWithErrorHandling(onLeave as Hook, [el, resolve])\n", " removeTransitionClass(el, leaveFromClass)\n", " addTransitionClass(el, leaveToClass)\n", " if (!(onLeave && onLeave.length > 1)) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " callHook(onLeave, [el, resolve])\n" ], "file_path": "packages/runtime-dom/src/components/Transition.ts", "type": "replace", "edit_start_line_idx": 160 }
{ "extends": "./tsconfig.json", "compilerOptions": { "paths": { "@vue/*": ["../packages/*/dist"], "vue": ["../packages/vue/dist"] } }, "exclude": ["../packages/*/__tests__", "../packages/*/src"] }
test-dts/tsconfig.build.json
0
https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02
[ 0.0001710494834696874, 0.00016829324886202812, 0.00016553701425436884, 0.00016829324886202812, 0.0000027562346076592803 ]
{ "id": 7, "code_window": [ " whenTransitionEnds(el, type, resolve)\n", " }\n", " }\n", " })\n", " },\n", " onEnterCancelled: finishEnter,\n", " onLeaveCancelled: finishLeave\n", " } as BaseTransitionProps<Element>)\n", "}\n", "\n", "function normalizeDuration(\n", " duration: TransitionProps['duration']\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " onEnterCancelled(el) {\n", " finishEnter(el)\n", " onEnterCancelled && onEnterCancelled(el)\n", " },\n", " onLeaveCancelled(el) {\n", " finishLeave(el)\n", " onLeaveCancelled && onLeaveCancelled(el)\n", " }\n" ], "file_path": "packages/runtime-dom/src/components/Transition.ts", "type": "replace", "edit_start_line_idx": 172 }
import { BaseTransition, BaseTransitionProps, h, warn, FunctionalComponent, getCurrentInstance, callWithAsyncErrorHandling } from '@vue/runtime-core' import { isObject, toNumber, extend } from '@vue/shared' import { ErrorCodes } from 'packages/runtime-core/src/errorHandling' const TRANSITION = 'transition' const ANIMATION = 'animation' export interface TransitionProps extends BaseTransitionProps<Element> { name?: string type?: typeof TRANSITION | typeof ANIMATION css?: boolean duration?: number | { enter: number; leave: number } // custom transition classes enterFromClass?: string enterActiveClass?: string enterToClass?: string appearFromClass?: string appearActiveClass?: string appearToClass?: string leaveFromClass?: string leaveActiveClass?: string leaveToClass?: string } // DOM Transition is a higher-order-component based on the platform-agnostic // base Transition component, with DOM-specific logic. export const Transition: FunctionalComponent<TransitionProps> = ( props, { slots } ) => h(BaseTransition, resolveTransitionProps(props), slots) Transition.inheritRef = true const DOMTransitionPropsValidators = { name: String, type: String, css: { type: Boolean, default: true }, duration: [String, Number, Object], enterFromClass: String, enterActiveClass: String, enterToClass: String, appearFromClass: String, appearActiveClass: String, appearToClass: String, leaveFromClass: String, leaveActiveClass: String, leaveToClass: String } export const TransitionPropsValidators = (Transition.props = extend( {}, (BaseTransition as any).props, DOMTransitionPropsValidators )) export function resolveTransitionProps( rawProps: TransitionProps ): BaseTransitionProps<Element> { let { name = 'v', type, css = true, duration, enterFromClass = `${name}-enter-from`, enterActiveClass = `${name}-enter-active`, enterToClass = `${name}-enter-to`, appearFromClass = enterFromClass, appearActiveClass = enterActiveClass, appearToClass = enterToClass, leaveFromClass = `${name}-leave-from`, leaveActiveClass = `${name}-leave-active`, leaveToClass = `${name}-leave-to` } = rawProps const baseProps: BaseTransitionProps<Element> = {} for (const key in rawProps) { if (!(key in DOMTransitionPropsValidators)) { ;(baseProps as any)[key] = (rawProps as any)[key] } } if (!css) { return baseProps } const originEnterClass = [enterFromClass, enterActiveClass, enterToClass] const instance = getCurrentInstance()! const durations = normalizeDuration(duration) const enterDuration = durations && durations[0] const leaveDuration = durations && durations[1] const { appear, onBeforeEnter, onEnter, onLeave } = baseProps // is appearing if (appear && !instance.isMounted) { enterFromClass = appearFromClass enterActiveClass = appearActiveClass enterToClass = appearToClass } type Hook = (el: Element, done?: () => void) => void const finishEnter: Hook = (el, done) => { removeTransitionClass(el, enterToClass) removeTransitionClass(el, enterActiveClass) done && done() // reset enter class if (appear) { ;[enterFromClass, enterActiveClass, enterToClass] = originEnterClass } } const finishLeave: Hook = (el, done) => { removeTransitionClass(el, leaveToClass) removeTransitionClass(el, leaveActiveClass) done && done() } // only needed for user hooks called in nextFrame // sync errors are already handled by BaseTransition function callHookWithErrorHandling(hook: Hook, args: any[]) { callWithAsyncErrorHandling(hook, instance, ErrorCodes.TRANSITION_HOOK, args) } return extend(baseProps, { onBeforeEnter(el) { onBeforeEnter && onBeforeEnter(el) addTransitionClass(el, enterActiveClass) addTransitionClass(el, enterFromClass) }, onEnter(el, done) { nextFrame(() => { const resolve = () => finishEnter(el, done) onEnter && callHookWithErrorHandling(onEnter as Hook, [el, resolve]) removeTransitionClass(el, enterFromClass) addTransitionClass(el, enterToClass) if (!(onEnter && onEnter.length > 1)) { if (enterDuration) { setTimeout(resolve, enterDuration) } else { whenTransitionEnds(el, type, resolve) } } }) }, onLeave(el, done) { addTransitionClass(el, leaveActiveClass) addTransitionClass(el, leaveFromClass) nextFrame(() => { const resolve = () => finishLeave(el, done) onLeave && callHookWithErrorHandling(onLeave as Hook, [el, resolve]) removeTransitionClass(el, leaveFromClass) addTransitionClass(el, leaveToClass) if (!(onLeave && onLeave.length > 1)) { if (leaveDuration) { setTimeout(resolve, leaveDuration) } else { whenTransitionEnds(el, type, resolve) } } }) }, onEnterCancelled: finishEnter, onLeaveCancelled: finishLeave } as BaseTransitionProps<Element>) } function normalizeDuration( duration: TransitionProps['duration'] ): [number, number] | null { if (duration == null) { return null } else if (isObject(duration)) { return [NumberOf(duration.enter), NumberOf(duration.leave)] } else { const n = NumberOf(duration) return [n, n] } } function NumberOf(val: unknown): number { const res = toNumber(val) if (__DEV__) validateDuration(res) return res } function validateDuration(val: unknown) { if (typeof val !== 'number') { warn( `<transition> explicit duration is not a valid number - ` + `got ${JSON.stringify(val)}.` ) } else if (isNaN(val)) { warn( `<transition> explicit duration is NaN - ` + 'the duration expression might be incorrect.' ) } } export interface ElementWithTransition extends HTMLElement { // _vtc = Vue Transition Classes. // Store the temporarily-added transition classes on the element // so that we can avoid overwriting them if the element's class is patched // during the transition. _vtc?: Set<string> } export function addTransitionClass(el: Element, cls: string) { cls.split(/\s+/).forEach(c => c && el.classList.add(c)) ;( (el as ElementWithTransition)._vtc || ((el as ElementWithTransition)._vtc = new Set()) ).add(cls) } export function removeTransitionClass(el: Element, cls: string) { cls.split(/\s+/).forEach(c => c && el.classList.remove(c)) const { _vtc } = el as ElementWithTransition if (_vtc) { _vtc.delete(cls) if (!_vtc!.size) { ;(el as ElementWithTransition)._vtc = undefined } } } function nextFrame(cb: () => void) { requestAnimationFrame(() => { requestAnimationFrame(cb) }) } function whenTransitionEnds( el: Element, expectedType: TransitionProps['type'] | undefined, cb: () => void ) { const { type, timeout, propCount } = getTransitionInfo(el, expectedType) if (!type) { return cb() } const endEvent = type + 'end' let ended = 0 const end = () => { el.removeEventListener(endEvent, onEnd) cb() } const onEnd = (e: Event) => { if (e.target === el) { if (++ended >= propCount) { end() } } } setTimeout(() => { if (ended < propCount) { end() } }, timeout + 1) el.addEventListener(endEvent, onEnd) } interface CSSTransitionInfo { type: typeof TRANSITION | typeof ANIMATION | null propCount: number timeout: number hasTransform: boolean } export function getTransitionInfo( el: Element, expectedType?: TransitionProps['type'] ): CSSTransitionInfo { const styles: any = window.getComputedStyle(el) // JSDOM may return undefined for transition properties const getStyleProperties = (key: string) => (styles[key] || '').split(', ') const transitionDelays = getStyleProperties(TRANSITION + 'Delay') const transitionDurations = getStyleProperties(TRANSITION + 'Duration') const transitionTimeout = getTimeout(transitionDelays, transitionDurations) const animationDelays = getStyleProperties(ANIMATION + 'Delay') const animationDurations = getStyleProperties(ANIMATION + 'Duration') const animationTimeout = getTimeout(animationDelays, animationDurations) let type: CSSTransitionInfo['type'] = null let timeout = 0 let propCount = 0 /* istanbul ignore if */ if (expectedType === TRANSITION) { if (transitionTimeout > 0) { type = TRANSITION timeout = transitionTimeout propCount = transitionDurations.length } } else if (expectedType === ANIMATION) { if (animationTimeout > 0) { type = ANIMATION timeout = animationTimeout propCount = animationDurations.length } } else { timeout = Math.max(transitionTimeout, animationTimeout) type = timeout > 0 ? transitionTimeout > animationTimeout ? TRANSITION : ANIMATION : null propCount = type ? type === TRANSITION ? transitionDurations.length : animationDurations.length : 0 } const hasTransform = type === TRANSITION && /\b(transform|all)(,|$)/.test(styles[TRANSITION + 'Property']) return { type, timeout, propCount, hasTransform } } function getTimeout(delays: string[], durations: string[]): number { while (delays.length < durations.length) { delays = delays.concat(delays) } return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i]))) } // Old versions of Chromium (below 61.0.3163.100) formats floating pointer // numbers in a locale-dependent way, using a comma instead of a dot. // If comma is not replaced with a dot, the input will be rounded down // (i.e. acting as a floor function) causing unexpected behaviors function toMs(s: string): number { return Number(s.slice(0, -1).replace(',', '.')) * 1000 }
packages/runtime-dom/src/components/Transition.ts
1
https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02
[ 0.9984883069992065, 0.059210605919361115, 0.00016245702863670886, 0.002281629014760256, 0.22481639683246613 ]
{ "id": 7, "code_window": [ " whenTransitionEnds(el, type, resolve)\n", " }\n", " }\n", " })\n", " },\n", " onEnterCancelled: finishEnter,\n", " onLeaveCancelled: finishLeave\n", " } as BaseTransitionProps<Element>)\n", "}\n", "\n", "function normalizeDuration(\n", " duration: TransitionProps['duration']\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " onEnterCancelled(el) {\n", " finishEnter(el)\n", " onEnterCancelled && onEnterCancelled(el)\n", " },\n", " onLeaveCancelled(el) {\n", " finishLeave(el)\n", " onLeaveCancelled && onLeaveCancelled(el)\n", " }\n" ], "file_path": "packages/runtime-dom/src/components/Transition.ts", "type": "replace", "edit_start_line_idx": 172 }
import { ComponentInternalInstance, Data, SetupContext, ComponentInternalOptions, PublicAPIComponent, Component } from './component' import { isFunction, extend, isString, isObject, isArray, EMPTY_OBJ, NOOP, hasOwn, isPromise } from '@vue/shared' import { computed } from './apiComputed' import { watch, WatchOptions, WatchCallback } from './apiWatch' import { provide, inject } from './apiInject' import { onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onErrorCaptured, onRenderTracked, onBeforeUnmount, onUnmounted, onActivated, onDeactivated, onRenderTriggered, DebuggerHook, ErrorCapturedHook } from './apiLifecycle' import { reactive, ComputedGetter, WritableComputedOptions, toRaw } from '@vue/reactivity' import { ComponentObjectPropsOptions, ExtractPropTypes, normalizePropsOptions } from './componentProps' import { EmitsOptions } from './componentEmits' import { Directive } from './directives' import { CreateComponentPublicInstance, ComponentPublicInstance } from './componentProxy' import { warn } from './warning' import { VNodeChild } from './vnode' /** * Interface for declaring custom options. * * @example * ```ts * declare module '@vue/runtime-core' { * interface ComponentCustomOptions { * beforeRouteUpdate?( * to: Route, * from: Route, * next: () => void * ): void * } * } * ``` */ export interface ComponentCustomOptions {} export type RenderFunction = () => VNodeChild export interface ComponentOptionsBase< Props, RawBindings, D, C extends ComputedOptions, M extends MethodOptions, Mixin extends ComponentOptionsMixin, Extends extends ComponentOptionsMixin, E extends EmitsOptions, EE extends string = string > extends LegacyOptions<Props, D, C, M, Mixin, Extends>, ComponentInternalOptions, ComponentCustomOptions { setup?: ( this: void, props: Props, ctx: SetupContext<E> ) => RawBindings | RenderFunction | void name?: string template?: string | object // can be a direct DOM node // Note: we are intentionally using the signature-less `Function` type here // since any type with signature will cause the whole inference to fail when // the return expression contains reference to `this`. // Luckily `render()` doesn't need any arguments nor does it care about return // type. render?: Function components?: Record<string, PublicAPIComponent> directives?: Record<string, Directive> inheritAttrs?: boolean inheritRef?: boolean emits?: E | EE[] // Internal ------------------------------------------------------------------ /** * SSR only. This is produced by compiler-ssr and attached in compiler-sfc * not user facing, so the typing is lax and for test only. * * @internal */ ssrRender?: ( ctx: any, push: (item: any) => void, parentInstance: ComponentInternalInstance ) => void /** * marker for AsyncComponentWrapper * @internal */ __asyncLoader?: () => Promise<Component> /** * cache for merged $options * @internal */ __merged?: ComponentOptions // Type differentiators ------------------------------------------------------ // Note these are internal but need to be exposed in d.ts for type inference // to work! // type-only differentiator to separate OptionWithoutProps from a constructor // type returned by defineComponent() or FunctionalComponent call?: (this: unknown, ...args: unknown[]) => never // type-only differentiators for built-in Vnode types __isFragment?: never __isTeleport?: never __isSuspense?: never } export type ComponentOptionsWithoutProps< Props = {}, RawBindings = {}, D = {}, C extends ComputedOptions = {}, M extends MethodOptions = {}, Mixin extends ComponentOptionsMixin = ComponentOptionsMixin, Extends extends ComponentOptionsMixin = ComponentOptionsMixin, E extends EmitsOptions = EmitsOptions, EE extends string = string > = ComponentOptionsBase<Props, RawBindings, D, C, M, Mixin, Extends, E, EE> & { props?: undefined } & ThisType< CreateComponentPublicInstance< {}, RawBindings, D, C, M, Mixin, Extends, E, Readonly<Props> > > export type ComponentOptionsWithArrayProps< PropNames extends string = string, RawBindings = {}, D = {}, C extends ComputedOptions = {}, M extends MethodOptions = {}, Mixin extends ComponentOptionsMixin = ComponentOptionsMixin, Extends extends ComponentOptionsMixin = ComponentOptionsMixin, E extends EmitsOptions = EmitsOptions, EE extends string = string, Props = Readonly<{ [key in PropNames]?: any }> > = ComponentOptionsBase<Props, RawBindings, D, C, M, Mixin, Extends, E, EE> & { props: PropNames[] } & ThisType< CreateComponentPublicInstance< Props, RawBindings, D, C, M, Mixin, Extends, E > > export type ComponentOptionsWithObjectProps< PropsOptions = ComponentObjectPropsOptions, RawBindings = {}, D = {}, C extends ComputedOptions = {}, M extends MethodOptions = {}, Mixin extends ComponentOptionsMixin = ComponentOptionsMixin, Extends extends ComponentOptionsMixin = ComponentOptionsMixin, E extends EmitsOptions = EmitsOptions, EE extends string = string, Props = Readonly<ExtractPropTypes<PropsOptions>> > = ComponentOptionsBase<Props, RawBindings, D, C, M, Mixin, Extends, E, EE> & { props: PropsOptions } & ThisType< CreateComponentPublicInstance< Props, RawBindings, D, C, M, Mixin, Extends, E > > export type ComponentOptions = | ComponentOptionsWithoutProps<any, any, any, any, any> | ComponentOptionsWithObjectProps<any, any, any, any, any> | ComponentOptionsWithArrayProps<any, any, any, any, any> export type ComponentOptionsMixin = ComponentOptionsBase< any, any, any, any, any, any, any, any, any > export type ComputedOptions = Record< string, ComputedGetter<any> | WritableComputedOptions<any> > export interface MethodOptions { [key: string]: Function } export type ExtractComputedReturns<T extends any> = { [key in keyof T]: T[key] extends { get: (...args: any[]) => infer TReturn } ? TReturn : T[key] extends (...args: any[]) => infer TReturn ? TReturn : never } type WatchOptionItem = | string | WatchCallback | { handler: WatchCallback } & WatchOptions type ComponentWatchOptionItem = WatchOptionItem | WatchOptionItem[] type ComponentWatchOptions = Record<string, ComponentWatchOptionItem> type ComponentInjectOptions = | string[] | Record< string | symbol, string | symbol | { from: string | symbol; default?: unknown } > interface LegacyOptions< Props, D, C extends ComputedOptions, M extends MethodOptions, Mixin extends ComponentOptionsMixin, Extends extends ComponentOptionsMixin > { // allow any custom options [key: string]: any // state // Limitation: we cannot expose RawBindings on the `this` context for data // since that leads to some sort of circular inference and breaks ThisType // for the entire component. data?: ( this: CreateComponentPublicInstance<Props>, vm: CreateComponentPublicInstance<Props> ) => D computed?: C methods?: M watch?: ComponentWatchOptions provide?: Data | Function inject?: ComponentInjectOptions // composition mixins?: Mixin[] extends?: Extends // lifecycle beforeCreate?(): void created?(): void beforeMount?(): void mounted?(): void beforeUpdate?(): void updated?(): void activated?(): void deactivated?(): void beforeUnmount?(): void unmounted?(): void renderTracked?: DebuggerHook renderTriggered?: DebuggerHook errorCaptured?: ErrorCapturedHook } export type OptionTypesKeys = 'P' | 'B' | 'D' | 'C' | 'M' export type OptionTypesType< P = {}, B = {}, D = {}, C extends ComputedOptions = {}, M extends MethodOptions = {} > = { P: P B: B D: D C: C M: M } const enum OptionTypes { PROPS = 'Props', DATA = 'Data', COMPUTED = 'Computed', METHODS = 'Methods', INJECT = 'Inject' } function createDuplicateChecker() { const cache = Object.create(null) return (type: OptionTypes, key: string) => { if (cache[key]) { warn(`${type} property "${key}" is already defined in ${cache[key]}.`) } else { cache[key] = type } } } type DataFn = (vm: ComponentPublicInstance) => any export function applyOptions( instance: ComponentInternalInstance, options: ComponentOptions, deferredData: DataFn[] = [], deferredWatch: ComponentWatchOptions[] = [], asMixin: boolean = false ) { const { // composition mixins, extends: extendsOptions, // state data: dataOptions, computed: computedOptions, methods, watch: watchOptions, provide: provideOptions, inject: injectOptions, // assets components, directives, // lifecycle beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeUnmount, unmounted, renderTracked, renderTriggered, errorCaptured } = options const publicThis = instance.proxy! const ctx = instance.ctx const globalMixins = instance.appContext.mixins // call it only during dev // applyOptions is called non-as-mixin once per instance if (!asMixin) { callSyncHook('beforeCreate', options, publicThis, globalMixins) // global mixins are applied first applyMixins(instance, globalMixins, deferredData, deferredWatch) } // extending a base component... if (extendsOptions) { applyOptions(instance, extendsOptions, deferredData, deferredWatch, true) } // local mixins if (mixins) { applyMixins(instance, mixins, deferredData, deferredWatch) } const checkDuplicateProperties = __DEV__ ? createDuplicateChecker() : null if (__DEV__) { const propsOptions = normalizePropsOptions(options)[0] if (propsOptions) { for (const key in propsOptions) { checkDuplicateProperties!(OptionTypes.PROPS, key) } } } // options initialization order (to be consistent with Vue 2): // - props (already done outside of this function) // - inject // - methods // - data (deferred since it relies on `this` access) // - computed // - watch (deferred since it relies on `this` access) if (injectOptions) { if (isArray(injectOptions)) { for (let i = 0; i < injectOptions.length; i++) { const key = injectOptions[i] ctx[key] = inject(key) if (__DEV__) { checkDuplicateProperties!(OptionTypes.INJECT, key) } } } else { for (const key in injectOptions) { const opt = injectOptions[key] if (isObject(opt)) { ctx[key] = inject(opt.from, opt.default) } else { ctx[key] = inject(opt) } if (__DEV__) { checkDuplicateProperties!(OptionTypes.INJECT, key) } } } } if (methods) { for (const key in methods) { const methodHandler = (methods as MethodOptions)[key] if (isFunction(methodHandler)) { ctx[key] = methodHandler.bind(publicThis) if (__DEV__) { checkDuplicateProperties!(OptionTypes.METHODS, key) } } else if (__DEV__) { warn( `Method "${key}" has type "${typeof methodHandler}" in the component definition. ` + `Did you reference the function correctly?` ) } } } if (dataOptions) { if (__DEV__ && !isFunction(dataOptions)) { warn( `The data option must be a function. ` + `Plain object usage is no longer supported.` ) } if (asMixin) { deferredData.push(dataOptions as DataFn) } else { resolveData(instance, dataOptions, publicThis) } } if (!asMixin) { if (deferredData.length) { deferredData.forEach(dataFn => resolveData(instance, dataFn, publicThis)) } if (__DEV__) { const rawData = toRaw(instance.data) for (const key in rawData) { checkDuplicateProperties!(OptionTypes.DATA, key) // expose data on ctx during dev if (key[0] !== '$' && key[0] !== '_') { Object.defineProperty(ctx, key, { configurable: true, enumerable: true, get: () => rawData[key], set: NOOP }) } } } } if (computedOptions) { for (const key in computedOptions) { const opt = (computedOptions as ComputedOptions)[key] const get = isFunction(opt) ? opt.bind(publicThis, publicThis) : isFunction(opt.get) ? opt.get.bind(publicThis, publicThis) : NOOP if (__DEV__ && get === NOOP) { warn(`Computed property "${key}" has no getter.`) } const set = !isFunction(opt) && isFunction(opt.set) ? opt.set.bind(publicThis) : __DEV__ ? () => { warn( `Write operation failed: computed property "${key}" is readonly.` ) } : NOOP const c = computed({ get, set }) Object.defineProperty(ctx, key, { enumerable: true, configurable: true, get: () => c.value, set: v => (c.value = v) }) if (__DEV__) { checkDuplicateProperties!(OptionTypes.COMPUTED, key) } } } if (watchOptions) { deferredWatch.push(watchOptions) } if (!asMixin && deferredWatch.length) { deferredWatch.forEach(watchOptions => { for (const key in watchOptions) { createWatcher(watchOptions[key], ctx, publicThis, key) } }) } if (provideOptions) { const provides = isFunction(provideOptions) ? provideOptions.call(publicThis) : provideOptions for (const key in provides) { provide(key, provides[key]) } } // asset options if (components) { extend(instance.components, components) } if (directives) { extend(instance.directives, directives) } // lifecycle options if (!asMixin) { callSyncHook('created', options, publicThis, globalMixins) } if (beforeMount) { onBeforeMount(beforeMount.bind(publicThis)) } if (mounted) { onMounted(mounted.bind(publicThis)) } if (beforeUpdate) { onBeforeUpdate(beforeUpdate.bind(publicThis)) } if (updated) { onUpdated(updated.bind(publicThis)) } if (activated) { onActivated(activated.bind(publicThis)) } if (deactivated) { onDeactivated(deactivated.bind(publicThis)) } if (errorCaptured) { onErrorCaptured(errorCaptured.bind(publicThis)) } if (renderTracked) { onRenderTracked(renderTracked.bind(publicThis)) } if (renderTriggered) { onRenderTriggered(renderTriggered.bind(publicThis)) } if (beforeUnmount) { onBeforeUnmount(beforeUnmount.bind(publicThis)) } if (unmounted) { onUnmounted(unmounted.bind(publicThis)) } } function callSyncHook( name: 'beforeCreate' | 'created', options: ComponentOptions, ctx: ComponentPublicInstance, globalMixins: ComponentOptions[] ) { callHookFromMixins(name, globalMixins, ctx) const baseHook = options.extends && options.extends[name] if (baseHook) { baseHook.call(ctx) } const mixins = options.mixins if (mixins) { callHookFromMixins(name, mixins, ctx) } const selfHook = options[name] if (selfHook) { selfHook.call(ctx) } } function callHookFromMixins( name: 'beforeCreate' | 'created', mixins: ComponentOptions[], ctx: ComponentPublicInstance ) { for (let i = 0; i < mixins.length; i++) { const fn = mixins[i][name] if (fn) { fn.call(ctx) } } } function applyMixins( instance: ComponentInternalInstance, mixins: ComponentOptions[], deferredData: DataFn[], deferredWatch: ComponentWatchOptions[] ) { for (let i = 0; i < mixins.length; i++) { applyOptions(instance, mixins[i], deferredData, deferredWatch, true) } } function resolveData( instance: ComponentInternalInstance, dataFn: DataFn, publicThis: ComponentPublicInstance ) { const data = dataFn.call(publicThis, publicThis) if (__DEV__ && isPromise(data)) { warn( `data() returned a Promise - note data() cannot be async; If you ` + `intend to perform data fetching before component renders, use ` + `async setup() + <Suspense>.` ) } if (!isObject(data)) { __DEV__ && warn(`data() should return an object.`) } else if (instance.data === EMPTY_OBJ) { instance.data = reactive(data) } else { // existing data: this is a mixin or extends. extend(instance.data, data) } } function createWatcher( raw: ComponentWatchOptionItem, ctx: Data, publicThis: ComponentPublicInstance, key: string ) { const getter = () => (publicThis as any)[key] if (isString(raw)) { const handler = ctx[raw] if (isFunction(handler)) { watch(getter, handler as WatchCallback) } else if (__DEV__) { warn(`Invalid watch handler specified by key "${raw}"`, handler) } } else if (isFunction(raw)) { watch(getter, raw.bind(publicThis)) } else if (isObject(raw)) { if (isArray(raw)) { raw.forEach(r => createWatcher(r, ctx, publicThis, key)) } else { watch(getter, raw.handler.bind(publicThis), raw) } } else if (__DEV__) { warn(`Invalid watch option: "${key}"`) } } export function resolveMergedOptions( instance: ComponentInternalInstance ): ComponentOptions { const raw = instance.type as ComponentOptions const { __merged, mixins, extends: extendsOptions } = raw if (__merged) return __merged const globalMixins = instance.appContext.mixins if (!globalMixins.length && !mixins && !extendsOptions) return raw const options = {} globalMixins.forEach(m => mergeOptions(options, m, instance)) extendsOptions && mergeOptions(options, extendsOptions, instance) mixins && mixins.forEach(m => mergeOptions(options, m, instance)) mergeOptions(options, raw, instance) return (raw.__merged = options) } function mergeOptions(to: any, from: any, instance: ComponentInternalInstance) { const strats = instance.appContext.config.optionMergeStrategies for (const key in from) { const strat = strats && strats[key] if (strat) { to[key] = strat(to[key], from[key], instance.proxy, key) } else if (!hasOwn(to, key)) { to[key] = from[key] } } }
packages/runtime-core/src/componentOptions.ts
0
https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02
[ 0.0020805816166102886, 0.00021841994021087885, 0.00016088526172097772, 0.00017192101222462952, 0.00022817040735390037 ]
{ "id": 7, "code_window": [ " whenTransitionEnds(el, type, resolve)\n", " }\n", " }\n", " })\n", " },\n", " onEnterCancelled: finishEnter,\n", " onLeaveCancelled: finishLeave\n", " } as BaseTransitionProps<Element>)\n", "}\n", "\n", "function normalizeDuration(\n", " duration: TransitionProps['duration']\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " onEnterCancelled(el) {\n", " finishEnter(el)\n", " onEnterCancelled && onEnterCancelled(el)\n", " },\n", " onLeaveCancelled(el) {\n", " finishLeave(el)\n", " onLeaveCancelled && onLeaveCancelled(el)\n", " }\n" ], "file_path": "packages/runtime-dom/src/components/Transition.ts", "type": "replace", "edit_start_line_idx": 172 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`compiler: v-for codegen basic v-for 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { renderList: _renderList, Fragment: _Fragment, openBlock: _openBlock, createBlock: _createBlock, createVNode: _createVNode } = _Vue return (_openBlock(true), _createBlock(_Fragment, null, _renderList(items, (item) => { return (_openBlock(), _createBlock(\\"span\\")) }), 256 /* UNKEYED_FRAGMENT */)) } }" `; exports[`compiler: v-for codegen keyed template v-for 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { renderList: _renderList, Fragment: _Fragment, openBlock: _openBlock, createBlock: _createBlock, createVNode: _createVNode } = _Vue return (_openBlock(true), _createBlock(_Fragment, null, _renderList(items, (item) => { return (_openBlock(), _createBlock(_Fragment, { key: item }, [ \\"hello\\", _createVNode(\\"span\\") ], 64 /* STABLE_FRAGMENT */)) }), 128 /* KEYED_FRAGMENT */)) } }" `; exports[`compiler: v-for codegen keyed v-for 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { renderList: _renderList, Fragment: _Fragment, openBlock: _openBlock, createBlock: _createBlock } = _Vue return (_openBlock(true), _createBlock(_Fragment, null, _renderList(items, (item) => { return (_openBlock(), _createBlock(\\"span\\", { key: item })) }), 128 /* KEYED_FRAGMENT */)) } }" `; exports[`compiler: v-for codegen skipped key 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { renderList: _renderList, Fragment: _Fragment, openBlock: _openBlock, createBlock: _createBlock, createVNode: _createVNode } = _Vue return (_openBlock(true), _createBlock(_Fragment, null, _renderList(items, (item, __, index) => { return (_openBlock(), _createBlock(\\"span\\")) }), 256 /* UNKEYED_FRAGMENT */)) } }" `; exports[`compiler: v-for codegen skipped value & key 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { renderList: _renderList, Fragment: _Fragment, openBlock: _openBlock, createBlock: _createBlock, createVNode: _createVNode } = _Vue return (_openBlock(true), _createBlock(_Fragment, null, _renderList(items, (_, __, index) => { return (_openBlock(), _createBlock(\\"span\\")) }), 256 /* UNKEYED_FRAGMENT */)) } }" `; exports[`compiler: v-for codegen skipped value 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { renderList: _renderList, Fragment: _Fragment, openBlock: _openBlock, createBlock: _createBlock, createVNode: _createVNode } = _Vue return (_openBlock(true), _createBlock(_Fragment, null, _renderList(items, (_, key, index) => { return (_openBlock(), _createBlock(\\"span\\")) }), 256 /* UNKEYED_FRAGMENT */)) } }" `; exports[`compiler: v-for codegen template v-for 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { renderList: _renderList, Fragment: _Fragment, openBlock: _openBlock, createBlock: _createBlock, createVNode: _createVNode } = _Vue return (_openBlock(true), _createBlock(_Fragment, null, _renderList(items, (item) => { return (_openBlock(), _createBlock(_Fragment, null, [ \\"hello\\", _createVNode(\\"span\\") ], 64 /* STABLE_FRAGMENT */)) }), 256 /* UNKEYED_FRAGMENT */)) } }" `; exports[`compiler: v-for codegen template v-for w/ <slot/> 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { renderList: _renderList, Fragment: _Fragment, openBlock: _openBlock, createBlock: _createBlock, renderSlot: _renderSlot } = _Vue return (_openBlock(true), _createBlock(_Fragment, null, _renderList(items, (item) => { return _renderSlot($slots, \\"default\\") }), 256 /* UNKEYED_FRAGMENT */)) } }" `; exports[`compiler: v-for codegen v-for on <slot/> 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { renderList: _renderList, Fragment: _Fragment, openBlock: _openBlock, createBlock: _createBlock, renderSlot: _renderSlot } = _Vue return (_openBlock(true), _createBlock(_Fragment, null, _renderList(items, (item) => { return _renderSlot($slots, \\"default\\") }), 256 /* UNKEYED_FRAGMENT */)) } }" `; exports[`compiler: v-for codegen v-for on element with custom directive 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { renderList: _renderList, Fragment: _Fragment, openBlock: _openBlock, createBlock: _createBlock, resolveDirective: _resolveDirective, createVNode: _createVNode, withDirectives: _withDirectives } = _Vue const _directive_foo = _resolveDirective(\\"foo\\") return (_openBlock(true), _createBlock(_Fragment, null, _renderList(list, (i) => { return _withDirectives((_openBlock(), _createBlock(\\"div\\", null, null, 512 /* NEED_PATCH */)), [ [_directive_foo] ]) }), 256 /* UNKEYED_FRAGMENT */)) } }" `; exports[`compiler: v-for codegen v-for with constant expression 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { renderList: _renderList, Fragment: _Fragment, openBlock: _openBlock, createBlock: _createBlock, toDisplayString: _toDisplayString, createVNode: _createVNode } = _Vue return (_openBlock(), _createBlock(_Fragment, null, _renderList(10, (item) => { return _createVNode(\\"p\\", null, _toDisplayString(item), 1 /* TEXT */) }), 64 /* STABLE_FRAGMENT */)) } }" `; exports[`compiler: v-for codegen v-if + v-for 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { renderList: _renderList, Fragment: _Fragment, openBlock: _openBlock, createBlock: _createBlock, createVNode: _createVNode, createCommentVNode: _createCommentVNode } = _Vue return ok ? (_openBlock(true), _createBlock(_Fragment, { key: 0 }, _renderList(list, (i) => { return (_openBlock(), _createBlock(\\"div\\")) }), 256 /* UNKEYED_FRAGMENT */)) : _createCommentVNode(\\"v-if\\", true) } }" `; exports[`compiler: v-for codegen value + key + index 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { renderList: _renderList, Fragment: _Fragment, openBlock: _openBlock, createBlock: _createBlock, createVNode: _createVNode } = _Vue return (_openBlock(true), _createBlock(_Fragment, null, _renderList(items, (item, key, index) => { return (_openBlock(), _createBlock(\\"span\\")) }), 256 /* UNKEYED_FRAGMENT */)) } }" `;
packages/compiler-core/__tests__/transforms/__snapshots__/vFor.spec.ts.snap
0
https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02
[ 0.0001742081221891567, 0.00016862779739312828, 0.0001612943015061319, 0.00016873469576239586, 0.000003528679144437774 ]
{ "id": 7, "code_window": [ " whenTransitionEnds(el, type, resolve)\n", " }\n", " }\n", " })\n", " },\n", " onEnterCancelled: finishEnter,\n", " onLeaveCancelled: finishLeave\n", " } as BaseTransitionProps<Element>)\n", "}\n", "\n", "function normalizeDuration(\n", " duration: TransitionProps['duration']\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " onEnterCancelled(el) {\n", " finishEnter(el)\n", " onEnterCancelled && onEnterCancelled(el)\n", " },\n", " onLeaveCancelled(el) {\n", " finishLeave(el)\n", " onLeaveCancelled && onLeaveCancelled(el)\n", " }\n" ], "file_path": "packages/runtime-dom/src/components/Transition.ts", "type": "replace", "edit_start_line_idx": 172 }
import { CodegenOptions } from './options' import { RootNode, TemplateChildNode, TextNode, CommentNode, ExpressionNode, NodeTypes, JSChildNode, CallExpression, ArrayExpression, ObjectExpression, Position, InterpolationNode, CompoundExpressionNode, SimpleExpressionNode, FunctionExpression, ConditionalExpression, CacheExpression, locStub, SSRCodegenNode, TemplateLiteral, IfStatement, AssignmentExpression, ReturnStatement, VNodeCall, SequenceExpression } from './ast' import { SourceMapGenerator, RawSourceMap } from 'source-map' import { advancePositionWithMutation, assert, isSimpleIdentifier, toValidAssetId } from './utils' import { isString, isArray, isSymbol } from '@vue/shared' import { helperNameMap, TO_DISPLAY_STRING, CREATE_VNODE, RESOLVE_COMPONENT, RESOLVE_DIRECTIVE, SET_BLOCK_TRACKING, CREATE_COMMENT, CREATE_TEXT, PUSH_SCOPE_ID, POP_SCOPE_ID, WITH_SCOPE_ID, WITH_DIRECTIVES, CREATE_BLOCK, OPEN_BLOCK, CREATE_STATIC, WITH_CTX } from './runtimeHelpers' import { ImportItem } from './transform' const PURE_ANNOTATION = `/*#__PURE__*/` type CodegenNode = TemplateChildNode | JSChildNode | SSRCodegenNode export interface CodegenResult { code: string ast: RootNode map?: RawSourceMap } export interface CodegenContext extends Required<CodegenOptions> { source: string code: string line: number column: number offset: number indentLevel: number pure: boolean map?: SourceMapGenerator helper(key: symbol): string push(code: string, node?: CodegenNode): void indent(): void deindent(withoutNewLine?: boolean): void newline(): void } function createCodegenContext( ast: RootNode, { mode = 'function', prefixIdentifiers = mode === 'module', sourceMap = false, filename = `template.vue.html`, scopeId = null, optimizeBindings = false, runtimeGlobalName = `Vue`, runtimeModuleName = `vue`, ssr = false }: CodegenOptions ): CodegenContext { const context: CodegenContext = { mode, prefixIdentifiers, sourceMap, filename, scopeId, optimizeBindings, runtimeGlobalName, runtimeModuleName, ssr, source: ast.loc.source, code: ``, column: 1, line: 1, offset: 0, indentLevel: 0, pure: false, map: undefined, helper(key) { return `_${helperNameMap[key]}` }, push(code, node) { context.code += code if (!__BROWSER__ && context.map) { if (node) { let name if (node.type === NodeTypes.SIMPLE_EXPRESSION && !node.isStatic) { const content = node.content.replace(/^_ctx\./, '') if (content !== node.content && isSimpleIdentifier(content)) { name = content } } addMapping(node.loc.start, name) } advancePositionWithMutation(context, code) if (node && node.loc !== locStub) { addMapping(node.loc.end) } } }, indent() { newline(++context.indentLevel) }, deindent(withoutNewLine = false) { if (withoutNewLine) { --context.indentLevel } else { newline(--context.indentLevel) } }, newline() { newline(context.indentLevel) } } function newline(n: number) { context.push('\n' + ` `.repeat(n)) } function addMapping(loc: Position, name?: string) { context.map!.addMapping({ name, source: context.filename, original: { line: loc.line, column: loc.column - 1 // source-map column is 0 based }, generated: { line: context.line, column: context.column - 1 } }) } if (!__BROWSER__ && sourceMap) { // lazy require source-map implementation, only in non-browser builds context.map = new SourceMapGenerator() context.map!.setSourceContent(filename, context.source) } return context } export function generate( ast: RootNode, options: CodegenOptions = {} ): CodegenResult { const context = createCodegenContext(ast, options) const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context const hasHelpers = ast.helpers.length > 0 const useWithBlock = !prefixIdentifiers && mode !== 'module' const genScopeId = !__BROWSER__ && scopeId != null && mode === 'module' // preambles if (!__BROWSER__ && mode === 'module') { genModulePreamble(ast, context, genScopeId) } else { genFunctionPreamble(ast, context) } // enter render function if (genScopeId && !ssr) { push(`const render = ${PURE_ANNOTATION}_withId(`) } if (!ssr) { push(`function render(_ctx, _cache) {`) } else { push(`function ssrRender(_ctx, _push, _parent) {`) } indent() if (useWithBlock) { push(`with (_ctx) {`) indent() // function mode const declarations should be inside with block // also they should be renamed to avoid collision with user properties if (hasHelpers) { push( `const { ${ast.helpers .map(s => `${helperNameMap[s]}: _${helperNameMap[s]}`) .join(', ')} } = _Vue` ) push(`\n`) newline() } } // generate asset resolution statements if (ast.components.length) { genAssets(ast.components, 'component', context) if (ast.directives.length || ast.temps > 0) { newline() } } if (ast.directives.length) { genAssets(ast.directives, 'directive', context) if (ast.temps > 0) { newline() } } if (ast.temps > 0) { push(`let `) for (let i = 0; i < ast.temps; i++) { push(`${i > 0 ? `, ` : ``}_temp${i}`) } } if (ast.components.length || ast.directives.length || ast.temps) { push(`\n`) newline() } // generate the VNode tree expression if (!ssr) { push(`return `) } if (ast.codegenNode) { genNode(ast.codegenNode, context) } else { push(`null`) } if (useWithBlock) { deindent() push(`}`) } deindent() push(`}`) if (genScopeId && !ssr) { push(`)`) } return { ast, code: context.code, // SourceMapGenerator does have toJSON() method but it's not in the types map: context.map ? (context.map as any).toJSON() : undefined } } function genFunctionPreamble(ast: RootNode, context: CodegenContext) { const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName } = context const VueBinding = !__BROWSER__ && ssr ? `require(${JSON.stringify(runtimeModuleName)})` : runtimeGlobalName const aliasHelper = (s: symbol) => `${helperNameMap[s]}: _${helperNameMap[s]}` // Generate const declaration for helpers // In prefix mode, we place the const declaration at top so it's done // only once; But if we not prefixing, we place the declaration inside the // with block so it doesn't incur the `in` check cost for every helper access. if (ast.helpers.length > 0) { if (!__BROWSER__ && prefixIdentifiers) { push( `const { ${ast.helpers.map(aliasHelper).join(', ')} } = ${VueBinding}\n` ) } else { // "with" mode. // save Vue in a separate variable to avoid collision push(`const _Vue = ${VueBinding}\n`) // in "with" mode, helpers are declared inside the with block to avoid // has check cost, but hoists are lifted out of the function - we need // to provide the helper here. if (ast.hoists.length) { const staticHelpers = [ CREATE_VNODE, CREATE_COMMENT, CREATE_TEXT, CREATE_STATIC ] .filter(helper => ast.helpers.includes(helper)) .map(aliasHelper) .join(', ') push(`const { ${staticHelpers} } = _Vue\n`) } } } // generate variables for ssr helpers if (!__BROWSER__ && ast.ssrHelpers && ast.ssrHelpers.length) { // ssr guaruntees prefixIdentifier: true push( `const { ${ast.ssrHelpers .map(aliasHelper) .join(', ')} } = require("@vue/server-renderer")\n` ) } genHoists(ast.hoists, context) newline() push(`return `) } function genModulePreamble( ast: RootNode, context: CodegenContext, genScopeId: boolean ) { const { push, helper, newline, scopeId, optimizeBindings, runtimeModuleName } = context if (genScopeId) { ast.helpers.push(WITH_SCOPE_ID) if (ast.hoists.length) { ast.helpers.push(PUSH_SCOPE_ID, POP_SCOPE_ID) } } // generate import statements for helpers if (ast.helpers.length) { if (optimizeBindings) { // when bundled with webpack with code-split, calling an import binding // as a function leads to it being wrapped with `Object(a.b)` or `(0,a.b)`, // incurring both payload size increase and potential perf overhead. // therefore we assign the imports to vairables (which is a constant ~50b // cost per-component instead of scaling with template size) push( `import { ${ast.helpers .map(s => helperNameMap[s]) .join(', ')} } from ${JSON.stringify(runtimeModuleName)}\n` ) push( `\n// Binding optimization for webpack code-split\nconst ${ast.helpers .map(s => `_${helperNameMap[s]} = ${helperNameMap[s]}`) .join(', ')}\n` ) } else { push( `import { ${ast.helpers .map(s => `${helperNameMap[s]} as _${helperNameMap[s]}`) .join(', ')} } from ${JSON.stringify(runtimeModuleName)}\n` ) } } if (ast.ssrHelpers && ast.ssrHelpers.length) { push( `import { ${ast.ssrHelpers .map(s => `${helperNameMap[s]} as _${helperNameMap[s]}`) .join(', ')} } from "@vue/server-renderer"\n` ) } if (ast.imports.length) { genImports(ast.imports, context) newline() } if (genScopeId) { push( `const _withId = ${PURE_ANNOTATION}${helper(WITH_SCOPE_ID)}("${scopeId}")` ) newline() } genHoists(ast.hoists, context) newline() push(`export `) } function genAssets( assets: string[], type: 'component' | 'directive', { helper, push, newline }: CodegenContext ) { const resolver = helper( type === 'component' ? RESOLVE_COMPONENT : RESOLVE_DIRECTIVE ) for (let i = 0; i < assets.length; i++) { const id = assets[i] push( `const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)})` ) if (i < assets.length - 1) { newline() } } } function genHoists(hoists: (JSChildNode | null)[], context: CodegenContext) { if (!hoists.length) { return } context.pure = true const { push, newline, helper, scopeId, mode } = context const genScopeId = !__BROWSER__ && scopeId != null && mode !== 'function' newline() // push scope Id before initilaizing hoisted vnodes so that these vnodes // get the proper scopeId as well. if (genScopeId) { push(`${helper(PUSH_SCOPE_ID)}("${scopeId}")`) newline() } hoists.forEach((exp, i) => { if (exp) { push(`const _hoisted_${i + 1} = `) genNode(exp, context) newline() } }) if (genScopeId) { push(`${helper(POP_SCOPE_ID)}()`) newline() } context.pure = false } function genImports(importsOptions: ImportItem[], context: CodegenContext) { if (!importsOptions.length) { return } importsOptions.forEach(imports => { context.push(`import `) genNode(imports.exp, context) context.push(` from '${imports.path}'`) context.newline() }) } function isText(n: string | CodegenNode) { return ( isString(n) || n.type === NodeTypes.SIMPLE_EXPRESSION || n.type === NodeTypes.TEXT || n.type === NodeTypes.INTERPOLATION || n.type === NodeTypes.COMPOUND_EXPRESSION ) } function genNodeListAsArray( nodes: (string | CodegenNode | TemplateChildNode[])[], context: CodegenContext ) { const multilines = nodes.length > 3 || ((!__BROWSER__ || __DEV__) && nodes.some(n => isArray(n) || !isText(n))) context.push(`[`) multilines && context.indent() genNodeList(nodes, context, multilines) multilines && context.deindent() context.push(`]`) } function genNodeList( nodes: (string | symbol | CodegenNode | TemplateChildNode[])[], context: CodegenContext, multilines: boolean = false, comma: boolean = true ) { const { push, newline } = context for (let i = 0; i < nodes.length; i++) { const node = nodes[i] if (isString(node)) { push(node) } else if (isArray(node)) { genNodeListAsArray(node, context) } else { genNode(node, context) } if (i < nodes.length - 1) { if (multilines) { comma && push(',') newline() } else { comma && push(', ') } } } } function genNode(node: CodegenNode | symbol | string, context: CodegenContext) { if (isString(node)) { context.push(node) return } if (isSymbol(node)) { context.push(context.helper(node)) return } switch (node.type) { case NodeTypes.ELEMENT: case NodeTypes.IF: case NodeTypes.FOR: __DEV__ && assert( node.codegenNode != null, `Codegen node is missing for element/if/for node. ` + `Apply appropriate transforms first.` ) genNode(node.codegenNode!, context) break case NodeTypes.TEXT: genText(node, context) break case NodeTypes.SIMPLE_EXPRESSION: genExpression(node, context) break case NodeTypes.INTERPOLATION: genInterpolation(node, context) break case NodeTypes.TEXT_CALL: genNode(node.codegenNode, context) break case NodeTypes.COMPOUND_EXPRESSION: genCompoundExpression(node, context) break case NodeTypes.COMMENT: genComment(node, context) break case NodeTypes.VNODE_CALL: genVNodeCall(node, context) break case NodeTypes.JS_CALL_EXPRESSION: genCallExpression(node, context) break case NodeTypes.JS_OBJECT_EXPRESSION: genObjectExpression(node, context) break case NodeTypes.JS_ARRAY_EXPRESSION: genArrayExpression(node, context) break case NodeTypes.JS_FUNCTION_EXPRESSION: genFunctionExpression(node, context) break case NodeTypes.JS_CONDITIONAL_EXPRESSION: genConditionalExpression(node, context) break case NodeTypes.JS_CACHE_EXPRESSION: genCacheExpression(node, context) break // SSR only types case NodeTypes.JS_BLOCK_STATEMENT: !__BROWSER__ && genNodeList(node.body, context, true, false) break case NodeTypes.JS_TEMPLATE_LITERAL: !__BROWSER__ && genTemplateLiteral(node, context) break case NodeTypes.JS_IF_STATEMENT: !__BROWSER__ && genIfStatement(node, context) break case NodeTypes.JS_ASSIGNMENT_EXPRESSION: !__BROWSER__ && genAssignmentExpression(node, context) break case NodeTypes.JS_SEQUENCE_EXPRESSION: !__BROWSER__ && genSequenceExpression(node, context) break case NodeTypes.JS_RETURN_STATEMENT: !__BROWSER__ && genReturnStatement(node, context) break /* istanbul ignore next */ case NodeTypes.IF_BRANCH: // noop break default: if (__DEV__) { assert(false, `unhandled codegen node type: ${(node as any).type}`) // make sure we exhaust all possible types const exhaustiveCheck: never = node return exhaustiveCheck } } } function genText( node: TextNode | SimpleExpressionNode, context: CodegenContext ) { context.push(JSON.stringify(node.content), node) } function genExpression(node: SimpleExpressionNode, context: CodegenContext) { const { content, isStatic } = node context.push(isStatic ? JSON.stringify(content) : content, node) } function genInterpolation(node: InterpolationNode, context: CodegenContext) { const { push, helper, pure } = context if (pure) push(PURE_ANNOTATION) push(`${helper(TO_DISPLAY_STRING)}(`) genNode(node.content, context) push(`)`) } function genCompoundExpression( node: CompoundExpressionNode, context: CodegenContext ) { for (let i = 0; i < node.children!.length; i++) { const child = node.children![i] if (isString(child)) { context.push(child) } else { genNode(child, context) } } } function genExpressionAsPropertyKey( node: ExpressionNode, context: CodegenContext ) { const { push } = context if (node.type === NodeTypes.COMPOUND_EXPRESSION) { push(`[`) genCompoundExpression(node, context) push(`]`) } else if (node.isStatic) { // only quote keys if necessary const text = isSimpleIdentifier(node.content) ? node.content : JSON.stringify(node.content) push(text, node) } else { push(`[${node.content}]`, node) } } function genComment(node: CommentNode, context: CodegenContext) { if (__DEV__) { const { push, helper, pure } = context if (pure) { push(PURE_ANNOTATION) } push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node) } } function genVNodeCall(node: VNodeCall, context: CodegenContext) { const { push, helper, pure } = context const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking } = node if (directives) { push(helper(WITH_DIRECTIVES) + `(`) } if (isBlock) { push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `) } if (pure) { push(PURE_ANNOTATION) } push(helper(isBlock ? CREATE_BLOCK : CREATE_VNODE) + `(`, node) genNodeList( genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context ) push(`)`) if (isBlock) { push(`)`) } if (directives) { push(`, `) genNode(directives, context) push(`)`) } } function genNullableArgs(args: any[]): CallExpression['arguments'] { let i = args.length while (i--) { if (args[i] != null) break } return args.slice(0, i + 1).map(arg => arg || `null`) } // JavaScript 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 + `(`, node) genNodeList(node.arguments, context) push(`)`) } function genObjectExpression(node: ObjectExpression, context: CodegenContext) { const { push, indent, deindent, newline } = context const { properties } = node if (!properties.length) { push(`{}`, node) return } const multilines = properties.length > 1 || ((!__BROWSER__ || __DEV__) && properties.some(p => p.value.type !== NodeTypes.SIMPLE_EXPRESSION)) push(multilines ? `{` : `{ `) multilines && indent() for (let i = 0; i < properties.length; i++) { const { key, value } = properties[i] // key genExpressionAsPropertyKey(key, context) push(`: `) // value genNode(value, context) if (i < properties.length - 1) { // will only reach this if it's multilines push(`,`) newline() } } multilines && deindent() push(multilines ? `}` : ` }`) } function genArrayExpression(node: ArrayExpression, context: CodegenContext) { genNodeListAsArray(node.elements, context) } function genFunctionExpression( node: FunctionExpression, context: CodegenContext ) { const { push, indent, deindent, scopeId, mode } = context const { params, returns, body, newline, isSlot } = node // slot functions also need to push scopeId before rendering its content const genScopeId = !__BROWSER__ && isSlot && scopeId != null && mode !== 'function' if (genScopeId) { push(`_withId(`) } else if (isSlot) { push(`_${helperNameMap[WITH_CTX]}(`) } push(`(`, node) if (isArray(params)) { genNodeList(params, context) } else if (params) { genNode(params, context) } push(`) => `) if (newline || body) { push(`{`) indent() } if (returns) { if (newline) { push(`return `) } if (isArray(returns)) { genNodeListAsArray(returns, context) } else { genNode(returns, context) } } else if (body) { genNode(body, context) } if (newline || body) { deindent() push(`}`) } if (genScopeId || isSlot) { push(`)`) } } function genConditionalExpression( node: ConditionalExpression, context: CodegenContext ) { const { test, consequent, alternate, newline: needNewline } = node const { push, indent, deindent, newline } = context if (test.type === NodeTypes.SIMPLE_EXPRESSION) { const needsParens = !isSimpleIdentifier(test.content) needsParens && push(`(`) genExpression(test, context) needsParens && push(`)`) } else { push(`(`) genNode(test, context) push(`)`) } needNewline && indent() context.indentLevel++ needNewline || push(` `) push(`? `) genNode(consequent, context) context.indentLevel-- needNewline && newline() needNewline || push(` `) push(`: `) const isNested = alternate.type === NodeTypes.JS_CONDITIONAL_EXPRESSION if (!isNested) { context.indentLevel++ } genNode(alternate, context) if (!isNested) { context.indentLevel-- } needNewline && deindent(true /* without newline */) } function genCacheExpression(node: CacheExpression, context: CodegenContext) { const { push, helper, indent, deindent, newline } = context push(`_cache[${node.index}] || (`) if (node.isVNode) { indent() push(`${helper(SET_BLOCK_TRACKING)}(-1),`) newline() } push(`_cache[${node.index}] = `) genNode(node.value, context) if (node.isVNode) { push(`,`) newline() push(`${helper(SET_BLOCK_TRACKING)}(1),`) newline() push(`_cache[${node.index}]`) deindent() } push(`)`) } function genTemplateLiteral(node: TemplateLiteral, context: CodegenContext) { const { push, indent, deindent } = context push('`') const l = node.elements.length const multilines = l > 3 for (let i = 0; i < l; i++) { const e = node.elements[i] if (isString(e)) { push(e.replace(/(`|\$|\\)/g, '\\$1')) } else { push('${') if (multilines) indent() genNode(e, context) if (multilines) deindent() push('}') } } push('`') } function genIfStatement(node: IfStatement, context: CodegenContext) { const { push, indent, deindent } = context const { test, consequent, alternate } = node push(`if (`) genNode(test, context) push(`) {`) indent() genNode(consequent, context) deindent() push(`}`) if (alternate) { push(` else `) if (alternate.type === NodeTypes.JS_IF_STATEMENT) { genIfStatement(alternate, context) } else { push(`{`) indent() genNode(alternate, context) deindent() push(`}`) } } } function genAssignmentExpression( node: AssignmentExpression, context: CodegenContext ) { genNode(node.left, context) context.push(` = `) genNode(node.right, context) } function genSequenceExpression( node: SequenceExpression, context: CodegenContext ) { context.push(`(`) genNodeList(node.expressions, context) context.push(`)`) } function genReturnStatement( { returns }: ReturnStatement, context: CodegenContext ) { context.push(`return `) if (isArray(returns)) { genNodeListAsArray(returns, context) } else { genNode(returns, context) } }
packages/compiler-core/src/codegen.ts
0
https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02
[ 0.0005224927444942296, 0.0001750781520968303, 0.00016070003039203584, 0.00017165261670015752, 0.000035980920074507594 ]
{ "id": 8, "code_window": [ " 'test-leave-active',\n", " 'test-leave-from'\n", " ])\n", " // fixme\n", " expect(enterCancelledSpy).not.toBeCalled()\n", " await nextFrame()\n", " expect(await classList('.test')).toStrictEqual([\n", " 'test',\n", " 'test-leave-active',\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(enterCancelledSpy).toBeCalled()\n" ], "file_path": "packages/vue/__tests__/Transition.spec.ts", "type": "replace", "edit_start_line_idx": 435 }
import { E2E_TIMEOUT, setupPuppeteer } from './e2eUtils' import path from 'path' import { mockWarn } from '@vue/shared' import { h, createApp, Transition } from 'vue' describe('e2e: Transition', () => { mockWarn() const { page, html, classList, isVisible } = setupPuppeteer() const baseUrl = `file://${path.resolve(__dirname, './transition.html')}` const duration = 50 const buffer = 5 const classWhenTransitionStart = () => page().evaluate(() => { (document.querySelector('#toggleBtn') as any)!.click() return Promise.resolve().then(() => { return document.querySelector('#container div')!.className.split(/\s+/g) }) }) const transitionFinish = (time = duration) => new Promise(r => { setTimeout(r, time + buffer) }) const nextFrame = () => { return page().evaluate(() => { return new Promise(resolve => { requestAnimationFrame(() => { requestAnimationFrame(resolve) }) }) }) } beforeEach(async () => { await page().goto(baseUrl) await page().waitFor('#app') }) describe('transition with v-if', () => { test( 'basic transition', async () => { await page().evaluate(() => { const { createApp, ref } = (window as any).Vue createApp({ template: ` <div id="container"> <transition> <div v-if="toggle" class="test">content</div> </transition> </div> <button id="toggleBtn" @click="click">button</button> `, setup: () => { const toggle = ref(true) const click = () => (toggle.value = !toggle.value) return { toggle, click } } }).mount('#app') }) expect(await html('#container')).toBe('<div class="test">content</div>') // leave expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'v-leave-active', 'v-leave-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'v-leave-active', 'v-leave-to' ]) await transitionFinish() expect(await html('#container')).toBe('<!--v-if-->') // enter expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'v-enter-active', 'v-enter-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'v-enter-active', 'v-enter-to' ]) await transitionFinish() expect(await html('#container')).toBe('<div class="test">content</div>') }, E2E_TIMEOUT ) test( 'named transition', async () => { await page().evaluate(() => { const { createApp, ref } = (window as any).Vue createApp({ template: ` <div id="container"> <transition name="test"> <div v-if="toggle" class="test">content</div> </transition> </div> <button id="toggleBtn" @click="click">button</button> `, setup: () => { const toggle = ref(true) const click = () => (toggle.value = !toggle.value) return { toggle, click } } }).mount('#app') }) expect(await html('#container')).toBe('<div class="test">content</div>') // leave expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-to' ]) await transitionFinish() expect(await html('#container')).toBe('<!--v-if-->') // enter expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-to' ]) await transitionFinish() expect(await html('#container')).toBe('<div class="test">content</div>') }, E2E_TIMEOUT ) test( 'custom transition classes', async () => { await page().evaluate(() => { const { createApp, ref } = (window as any).Vue createApp({ template: ` <div id="container"> <transition enter-from-class="hello-from" enter-active-class="hello-active" enter-to-class="hello-to" leave-from-class="bye-from" leave-active-class="bye-active" leave-to-class="bye-to"> <div v-if="toggle" class="test">content</div> </transition> </div> <button id="toggleBtn" @click="click">button</button> `, setup: () => { const toggle = ref(true) const click = () => (toggle.value = !toggle.value) return { toggle, click } } }).mount('#app') }) expect(await html('#container')).toBe('<div class="test">content</div>') // leave expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'bye-active', 'bye-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'bye-active', 'bye-to' ]) await transitionFinish() expect(await html('#container')).toBe('<!--v-if-->') // enter expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'hello-active', 'hello-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'hello-active', 'hello-to' ]) await transitionFinish() expect(await html('#container')).toBe('<div class="test">content</div>') }, E2E_TIMEOUT ) test( 'transition with dynamic name', async () => { await page().evaluate(() => { const { createApp, ref } = (window as any).Vue createApp({ template: ` <div id="container"> <transition :name="name"> <div v-if="toggle" class="test">content</div> </transition> </div> <button id="toggleBtn" @click="click">button</button> <button id="changeNameBtn" @click="changeName">button</button> `, setup: () => { const name = ref('test') const toggle = ref(true) const click = () => (toggle.value = !toggle.value) const changeName = () => (name.value = 'changed') return { toggle, click, name, changeName } } }).mount('#app') }) expect(await html('#container')).toBe('<div class="test">content</div>') // leave expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-to' ]) await transitionFinish() expect(await html('#container')).toBe('<!--v-if-->') // enter await page().evaluate(() => { ;(document.querySelector('#changeNameBtn') as any).click() }) expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'changed-enter-active', 'changed-enter-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'changed-enter-active', 'changed-enter-to' ]) await transitionFinish() expect(await html('#container')).toBe('<div class="test">content</div>') }, E2E_TIMEOUT ) test( 'transition events without appear', async () => { const beforeLeaveSpy = jest.fn() const onLeaveSpy = jest.fn() const afterLeaveSpy = jest.fn() const beforeEnterSpy = jest.fn() const onEnterSpy = jest.fn() const afterEnterSpy = jest.fn() await page().exposeFunction('onLeaveSpy', onLeaveSpy) await page().exposeFunction('onEnterSpy', onEnterSpy) await page().exposeFunction('beforeLeaveSpy', beforeLeaveSpy) await page().exposeFunction('beforeEnterSpy', beforeEnterSpy) await page().exposeFunction('afterLeaveSpy', afterLeaveSpy) await page().exposeFunction('afterEnterSpy', afterEnterSpy) await page().evaluate(() => { const { beforeEnterSpy, onEnterSpy, afterEnterSpy, beforeLeaveSpy, onLeaveSpy, afterLeaveSpy } = window as any const { createApp, ref } = (window as any).Vue createApp({ template: ` <div id="container"> <transition name="test" @before-enter="beforeEnterSpy" @enter="onEnterSpy" @after-enter="afterEnterSpy" @before-leave="beforeLeaveSpy" @leave="onLeaveSpy" @after-leave="afterLeaveSpy"> <div v-if="toggle" class="test">content</div> </transition> </div> <button id="toggleBtn" @click="click">button</button> `, setup: () => { const toggle = ref(true) const click = () => (toggle.value = !toggle.value) return { toggle, click, beforeEnterSpy, onEnterSpy, afterEnterSpy, beforeLeaveSpy, onLeaveSpy, afterLeaveSpy } } }).mount('#app') }) expect(await html('#container')).toBe('<div class="test">content</div>') // leave expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-from' ]) // todo test event with arguments. Note: not get dom, get object. '{}' expect(beforeLeaveSpy).toBeCalled() expect(onLeaveSpy).not.toBeCalled() expect(afterLeaveSpy).not.toBeCalled() await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-to' ]) expect(beforeLeaveSpy).toBeCalled() expect(afterLeaveSpy).not.toBeCalled() await transitionFinish() expect(await html('#container')).toBe('<!--v-if-->') expect(afterLeaveSpy).toBeCalled() // enter expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-from' ]) expect(beforeEnterSpy).toBeCalled() expect(onEnterSpy).not.toBeCalled() expect(afterEnterSpy).not.toBeCalled() await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-to' ]) expect(onEnterSpy).toBeCalled() expect(afterEnterSpy).not.toBeCalled() await transitionFinish() expect(await html('#container')).toBe('<div class="test">content</div>') expect(afterEnterSpy).toBeCalled() }, E2E_TIMEOUT ) test('onEnterCancelled', async () => { const enterCancelledSpy = jest.fn() await page().exposeFunction('enterCancelledSpy', enterCancelledSpy) await page().evaluate(() => { const { enterCancelledSpy } = window as any const { createApp, ref } = (window as any).Vue createApp({ template: ` <div id="container"> <transition name="test" @enter-cancelled="enterCancelledSpy"> <div v-if="toggle" class="test">content</div> </transition> </div> <button id="toggleBtn" @click="click">button</button> `, setup: () => { const toggle = ref(false) const click = () => (toggle.value = !toggle.value) return { toggle, click, enterCancelledSpy } } }).mount('#app') }) expect(await html('#container')).toBe('<!--v-if-->') // enter expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-to' ]) // cancel (leave) expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-from' ]) // fixme expect(enterCancelledSpy).not.toBeCalled() await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-to' ]) await transitionFinish() expect(await html('#container')).toBe('<!--v-if-->') }) test( 'transition on appear', async () => { await page().evaluate(async () => { const { createApp, ref } = (window as any).Vue createApp({ template: ` <div id="container"> <transition name="test" appear appear-from-class="test-appear-from" appear-to-class="test-appear-to" appear-active-class="test-appear-active"> <div v-if="toggle" class="test">content</div> </transition> </div> <button id="toggleBtn" @click="click">button</button> `, setup: () => { const toggle = ref(true) const click = () => (toggle.value = !toggle.value) return { toggle, click } } }).mount('#app') }) // appear expect(await classList('.test')).toStrictEqual([ 'test', 'test-appear-active', 'test-appear-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-appear-active', 'test-appear-to' ]) await transitionFinish() expect(await html('#container')).toBe('<div class="test">content</div>') // leave expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-to' ]) await transitionFinish() expect(await html('#container')).toBe('<!--v-if-->') // enter expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-to' ]) await transitionFinish() expect(await html('#container')).toBe('<div class="test">content</div>') }, E2E_TIMEOUT ) test( 'transition events with appear', async () => { const onLeaveSpy = jest.fn() const onEnterSpy = jest.fn() const onAppearSpy = jest.fn() const beforeLeaveSpy = jest.fn() const beforeEnterSpy = jest.fn() const beforeAppearSpy = jest.fn() const afterLeaveSpy = jest.fn() const afterEnterSpy = jest.fn() const afterAppearSpy = jest.fn() await page().exposeFunction('onLeaveSpy', onLeaveSpy) await page().exposeFunction('onEnterSpy', onEnterSpy) await page().exposeFunction('onAppearSpy', onAppearSpy) await page().exposeFunction('beforeLeaveSpy', beforeLeaveSpy) await page().exposeFunction('beforeEnterSpy', beforeEnterSpy) await page().exposeFunction('beforeAppearSpy', beforeAppearSpy) await page().exposeFunction('afterLeaveSpy', afterLeaveSpy) await page().exposeFunction('afterEnterSpy', afterEnterSpy) await page().exposeFunction('afterAppearSpy', afterAppearSpy) const appearClass = await page().evaluate(async () => { const { beforeAppearSpy, onAppearSpy, afterAppearSpy, beforeEnterSpy, onEnterSpy, afterEnterSpy, beforeLeaveSpy, onLeaveSpy, afterLeaveSpy } = window as any const { createApp, ref } = (window as any).Vue createApp({ template: ` <div id="container"> <transition name="test" appear appear-from-class="test-appear-from" appear-to-class="test-appear-to" appear-active-class="test-appear-active" @before-enter="beforeEnterSpy" @enter="onEnterSpy" @after-enter="afterEnterSpy" @before-leave="beforeLeaveSpy" @leave="onLeaveSpy" @after-leave="afterLeaveSpy" @before-appear="beforeAppearSpy" @appear="onAppearSpy" @after-appear="afterAppearSpy"> <div v-if="toggle" class="test">content</div> </transition> </div> <button id="toggleBtn" @click="click">button</button> `, setup: () => { const toggle = ref(true) const click = () => (toggle.value = !toggle.value) return { toggle, click, beforeAppearSpy, onAppearSpy, afterAppearSpy, beforeEnterSpy, onEnterSpy, afterEnterSpy, beforeLeaveSpy, onLeaveSpy, afterLeaveSpy } } }).mount('#app') return Promise.resolve().then(() => { return document.querySelector('.test')!.className.split(/\s+/g) }) }) // appear fixme spy called expect(appearClass).toStrictEqual([ 'test', 'test-appear-active', 'test-appear-from' ]) expect(beforeAppearSpy).not.toBeCalled() expect(onAppearSpy).not.toBeCalled() expect(afterAppearSpy).not.toBeCalled() await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-appear-active', 'test-appear-to' ]) expect(onAppearSpy).not.toBeCalled() expect(afterAppearSpy).not.toBeCalled() await transitionFinish() expect(await html('#container')).toBe('<div class="test">content</div>') expect(afterAppearSpy).not.toBeCalled() // leave expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-from' ]) expect(beforeLeaveSpy).toBeCalled() expect(onLeaveSpy).not.toBeCalled() expect(afterLeaveSpy).not.toBeCalled() await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-to' ]) expect(onLeaveSpy).toBeCalled() expect(afterLeaveSpy).not.toBeCalled() await transitionFinish() expect(await html('#container')).toBe('<!--v-if-->') expect(afterLeaveSpy).toBeCalled() // enter fixme spy called expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-from' ]) expect(beforeEnterSpy).toBeCalled() expect(onEnterSpy).toBeCalled() expect(afterEnterSpy).toBeCalled() await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-to' ]) expect(onEnterSpy).toBeCalled() expect(afterEnterSpy).toBeCalled() await transitionFinish() expect(await html('#container')).toBe('<div class="test">content</div>') expect(afterEnterSpy).toBeCalled() }, E2E_TIMEOUT ) // fixme test( 'css: false', async () => { const onLeaveSpy = jest.fn() const onEnterSpy = jest.fn() await page().exposeFunction('onLeaveSpy', onLeaveSpy) await page().exposeFunction('onEnterSpy', onEnterSpy) await page().evaluate(() => { const { onLeaveSpy, onEnterSpy } = window as any const { createApp, ref } = (window as any).Vue createApp({ template: ` <div id="container"> <transition :css="false" name="test" @enter="onEnterSpy" @leave="onLeaveSpy"> <div v-if="toggle" class="test">content</div> </transition> </div> <button id="toggleBtn" @click="click"></button> `, setup: () => { const toggle = ref(true) const click = () => (toggle.value = !toggle.value) return { toggle, click, onLeaveSpy, onEnterSpy } } }).mount('#app') }) expect(await html('#container')).toBe('<div class="test">content</div>') // leave await classWhenTransitionStart() expect(onLeaveSpy).toBeCalled() expect(await html('#container')).toBe( '<div class="test">content</div><!--v-if-->' ) // enter await classWhenTransitionStart() expect(onEnterSpy).toBeCalled() expect(await html('#container')).toBe('<div class="test">content</div>') }, E2E_TIMEOUT ) test( 'no transition detected', async () => { await page().evaluate(() => { const { createApp, ref } = (window as any).Vue createApp({ template: ` <div id="container"> <transition name="noop"> <div v-if="toggle">content</div> </transition> </div> <button id="toggleBtn" @click="click">button</button> `, setup: () => { const toggle = ref(true) const click = () => (toggle.value = !toggle.value) return { toggle, click } } }).mount('#app') }) expect(await html('#container')).toBe('<div>content</div>') // leave expect(await classWhenTransitionStart()).toStrictEqual([ 'noop-leave-active', 'noop-leave-from' ]) await nextFrame() expect(await html('#container')).toBe('<!--v-if-->') // enter expect(await classWhenTransitionStart()).toStrictEqual([ 'noop-enter-active', 'noop-enter-from' ]) await nextFrame() expect(await html('#container')).toBe('<div class="">content</div>') }, E2E_TIMEOUT ) test( 'animations', async () => { await page().evaluate(() => { const { createApp, ref } = (window as any).Vue createApp({ template: ` <div id="container"> <transition name="test-anim"> <div v-if="toggle">content</div> </transition> </div> <button id="toggleBtn" @click="click">button</button> `, setup: () => { const toggle = ref(true) const click = () => (toggle.value = !toggle.value) return { toggle, click } } }).mount('#app') }) expect(await html('#container')).toBe('<div>content</div>') // leave expect(await classWhenTransitionStart()).toStrictEqual([ 'test-anim-leave-active', 'test-anim-leave-from' ]) await nextFrame() expect(await classList('#container div')).toStrictEqual([ 'test-anim-leave-active', 'test-anim-leave-to' ]) await transitionFinish(duration * 2) expect(await html('#container')).toBe('<!--v-if-->') // enter expect(await classWhenTransitionStart()).toStrictEqual([ 'test-anim-enter-active', 'test-anim-enter-from' ]) await nextFrame() expect(await classList('#container div')).toStrictEqual([ 'test-anim-enter-active', 'test-anim-enter-to' ]) await transitionFinish() expect(await html('#container')).toBe('<div class="">content</div>') }, E2E_TIMEOUT ) test( 'explicit transition type', async () => { await page().evaluate(() => { const { createApp, ref } = (window as any).Vue createApp({ template: ` <div id="container"><transition name="test-anim-long" type="animation"><div v-if="toggle">content</div></transition></div> <button id="toggleBtn" @click="click">button</button> `, setup: () => { const toggle = ref(true) const click = () => (toggle.value = !toggle.value) return { toggle, click } } }).mount('#app') }) expect(await html('#container')).toBe('<div>content</div>') // leave expect(await classWhenTransitionStart()).toStrictEqual([ 'test-anim-long-leave-active', 'test-anim-long-leave-from' ]) await nextFrame() expect(await classList('#container div')).toStrictEqual([ 'test-anim-long-leave-active', 'test-anim-long-leave-to' ]) await new Promise(r => { setTimeout(r, duration + 5) }) expect(await classList('#container div')).toStrictEqual([ 'test-anim-long-leave-active', 'test-anim-long-leave-to' ]) await transitionFinish(duration * 2) expect(await html('#container')).toBe('<!--v-if-->') // enter expect(await classWhenTransitionStart()).toStrictEqual([ 'test-anim-long-enter-active', 'test-anim-long-enter-from' ]) await nextFrame() expect(await classList('#container div')).toStrictEqual([ 'test-anim-long-enter-active', 'test-anim-long-enter-to' ]) await new Promise(r => { setTimeout(r, duration + 5) }) expect(await classList('#container div')).toStrictEqual([ 'test-anim-long-enter-active', 'test-anim-long-enter-to' ]) await transitionFinish(duration * 2) expect(await html('#container')).toBe('<div class="">content</div>') }, E2E_TIMEOUT ) test( 'transition on SVG elements', async () => { await page().evaluate(() => { const { createApp, ref } = (window as any).Vue createApp({ template: ` <svg id="container"> <transition name="test"> <circle v-if="toggle" cx="0" cy="0" r="10" class="test"></circle> </transition> </svg> <button id="toggleBtn" @click="click">button</button> `, setup: () => { const toggle = ref(true) const click = () => (toggle.value = !toggle.value) return { toggle, click } } }).mount('#app') }) expect(await html('#container')).toBe( '<circle cx="0" cy="0" r="10" class="test"></circle>' ) const svgTransitionStart = () => page().evaluate(() => { document.querySelector('button')!.click() return Promise.resolve().then(() => { return document .querySelector('.test')! .getAttribute('class')! .split(/\s+/g) }) }) // leave expect(await svgTransitionStart()).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-to' ]) await transitionFinish() expect(await html('#container')).toBe('<!--v-if-->') // enter expect(await svgTransitionStart()).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-to' ]) await transitionFinish() expect(await html('#container')).toBe( '<circle cx="0" cy="0" r="10" class="test"></circle>' ) }, E2E_TIMEOUT ) test( 'custom transition higher-order component', async () => { await page().evaluate(() => { const { createApp, ref, h, Transition } = (window as any).Vue createApp({ template: ` <div id="container"><my-transition><div v-if="toggle" class="test">content</div></my-transition></div> <button id="toggleBtn" @click="click">button</button> `, components: { 'my-transition': (props: any, { slots }: any) => { return h(Transition, { name: 'test' }, slots) } }, setup: () => { const toggle = ref(true) const click = () => (toggle.value = !toggle.value) return { toggle, click } } }).mount('#app') }) expect(await html('#container')).toBe('<div class="test">content</div>') // leave expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-to' ]) await transitionFinish() expect(await html('#container')).toBe('<!--v-if-->') // enter expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-to' ]) await transitionFinish() expect(await html('#container')).toBe('<div class="test">content</div>') }, E2E_TIMEOUT ) test( 'transition on child components with empty root node', async () => { await page().evaluate(() => { const { createApp, ref } = (window as any).Vue createApp({ template: ` <div id="container"> <transition name="test"> <component class="test" :is="view"></component> </transition> </div> <button id="toggleBtn" @click="click">button</button> <button id="changeViewBtn" @click="change">button</button> `, components: { one: { template: '<div v-if="false">one</div>' }, two: { template: '<div>two</div>' } }, setup: () => { const toggle = ref(true) const view = ref('one') const click = () => (toggle.value = !toggle.value) const change = () => (view.value = view.value === 'one' ? 'two' : 'one') return { toggle, click, change, view } } }).mount('#app') }) expect(await html('#container')).toBe('<!--v-if-->') // change view -> 'two' await page().evaluate(() => { (document.querySelector('#changeViewBtn') as any)!.click() }) // enter expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-to' ]) await transitionFinish() expect(await html('#container')).toBe('<div class="test">two</div>') // change view -> 'one' await page().evaluate(() => { (document.querySelector('#changeViewBtn') as any)!.click() }) // leave expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-to' ]) await transitionFinish() expect(await html('#container')).toBe('<!--v-if-->') }, E2E_TIMEOUT ) }) describe('transition with v-show', () => { test( 'named transition with v-show', async () => { await page().evaluate(() => { const { createApp, ref } = (window as any).Vue createApp({ template: ` <div id="container"> <transition name="test"> <div v-show="toggle" class="test">content</div> </transition> </div> <button id="toggleBtn" @click="click">button</button> `, setup: () => { const toggle = ref(true) const click = () => (toggle.value = !toggle.value) return { toggle, click } } }).mount('#app') }) expect(await html('#container')).toBe('<div class="test">content</div>') expect(await isVisible('.test')).toBe(true) // leave expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-to' ]) await transitionFinish() expect(await isVisible('.test')).toBe(false) // enter expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-to' ]) await transitionFinish() expect(await html('#container')).toBe( '<div class="test" style="">content</div>' ) }, E2E_TIMEOUT ) test( 'transition events with v-show', async () => { const beforeLeaveSpy = jest.fn() const onLeaveSpy = jest.fn() const afterLeaveSpy = jest.fn() const beforeEnterSpy = jest.fn() const onEnterSpy = jest.fn() const afterEnterSpy = jest.fn() await page().exposeFunction('onLeaveSpy', onLeaveSpy) await page().exposeFunction('onEnterSpy', onEnterSpy) await page().exposeFunction('beforeLeaveSpy', beforeLeaveSpy) await page().exposeFunction('beforeEnterSpy', beforeEnterSpy) await page().exposeFunction('afterLeaveSpy', afterLeaveSpy) await page().exposeFunction('afterEnterSpy', afterEnterSpy) await page().evaluate(() => { const { beforeEnterSpy, onEnterSpy, afterEnterSpy, beforeLeaveSpy, onLeaveSpy, afterLeaveSpy } = window as any const { createApp, ref } = (window as any).Vue createApp({ template: ` <div id="container"> <transition name="test" @before-enter="beforeEnterSpy" @enter="onEnterSpy" @after-enter="afterEnterSpy" @before-leave="beforeLeaveSpy" @leave="onLeaveSpy" @after-leave="afterLeaveSpy"> <div v-show="toggle" class="test">content</div> </transition> </div> <button id="toggleBtn" @click="click">button</button> `, setup: () => { const toggle = ref(true) const click = () => (toggle.value = !toggle.value) return { toggle, click, beforeEnterSpy, onEnterSpy, afterEnterSpy, beforeLeaveSpy, onLeaveSpy, afterLeaveSpy } } }).mount('#app') }) expect(await html('#container')).toBe('<div class="test">content</div>') // leave expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-from' ]) expect(beforeLeaveSpy).toBeCalled() expect(onLeaveSpy).not.toBeCalled() expect(afterLeaveSpy).not.toBeCalled() await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-to' ]) expect(beforeLeaveSpy).toBeCalled() expect(afterLeaveSpy).not.toBeCalled() await transitionFinish() expect(await isVisible('.test')).toBe(false) expect(afterLeaveSpy).toBeCalled() // enter expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-from' ]) expect(beforeEnterSpy).toBeCalled() expect(onEnterSpy).not.toBeCalled() expect(afterEnterSpy).not.toBeCalled() await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-to' ]) expect(onEnterSpy).toBeCalled() expect(afterEnterSpy).not.toBeCalled() await transitionFinish() expect(await html('#container')).toBe( '<div class="test" style="">content</div>' ) expect(afterEnterSpy).toBeCalled() }, E2E_TIMEOUT ) test( 'onLeaveCancelled (v-show only)', async () => { const onLeaveCancelledSpy = jest.fn() await page().exposeFunction('onLeaveCancelledSpy', onLeaveCancelledSpy) await page().evaluate(() => { const { onLeaveCancelledSpy } = window as any const { createApp, ref } = (window as any).Vue createApp({ template: ` <div id="container"> <transition name="test"> <div v-show="toggle" class="test" @leave-cancelled="onLeaveCancelledSpy">content</div> </transition> </div> <button id="toggleBtn" @click="click">button</button> `, setup: () => { const toggle = ref(true) const click = () => (toggle.value = !toggle.value) return { toggle, click, onLeaveCancelledSpy } } }).mount('#app') }) expect(await html('#container')).toBe('<div class="test">content</div>') expect(await isVisible('.test')).toBe(true) // leave expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-to' ]) // cancel (enter) expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-from' ]) // fixme expect(onLeaveCancelledSpy).not.toBeCalled() await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-to' ]) await transitionFinish() expect(await html('#container')).toBe( '<div class="test" style="">content</div>' ) }, E2E_TIMEOUT ) test( 'transition on appear with v-show', async () => { const appearClass = await page().evaluate(async () => { const { createApp, ref } = (window as any).Vue createApp({ template: ` <div id="container"> <transition name="test" appear appear-from-class="test-appear-from" appear-to-class="test-appear-to" appear-active-class="test-appear-active"> <div v-show="toggle" class="test">content</div> </transition> </div> <button id="toggleBtn" @click="click">button</button> `, setup: () => { const toggle = ref(true) const click = () => (toggle.value = !toggle.value) return { toggle, click } } }).mount('#app') return Promise.resolve().then(() => { return document.querySelector('.test')!.className.split(/\s+/g) }) }) // appear expect(appearClass).toStrictEqual([ 'test', 'test-appear-active', 'test-appear-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-appear-active', 'test-appear-to' ]) await transitionFinish() expect(await html('#container')).toBe('<div class="test">content</div>') // leave expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-to' ]) await transitionFinish() expect(await isVisible('.test')).toBe(false) // enter expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-to' ]) await transitionFinish() expect(await html('#container')).toBe( '<div class="test" style="">content</div>' ) }, E2E_TIMEOUT ) }) test( 'warn when used on multiple elements', async () => { createApp({ render() { return h(Transition, null, { default: () => [h('div'), h('div')] }) } }).mount(document.createElement('div')) expect( '<transition> can only be used on a single element or component' ).toHaveBeenWarned() }, E2E_TIMEOUT ) describe('explicit durations', () => { test( 'single value', async () => { await page().evaluate(duration => { const { createApp, ref } = (window as any).Vue createApp({ template: ` <div id="container"> <transition name="test" duration="${duration * 2}"> <div v-if="toggle" class="test">content</div> </transition> </div> <button id="toggleBtn" @click="click">button</button> `, setup: () => { const toggle = ref(true) const click = () => (toggle.value = !toggle.value) return { toggle, click } } }).mount('#app') }, duration) expect(await html('#container')).toBe('<div class="test">content</div>') // leave expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-to' ]) await transitionFinish(duration * 2) expect(await html('#container')).toBe('<!--v-if-->') // enter expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-to' ]) await transitionFinish(duration * 2) expect(await html('#container')).toBe('<div class="test">content</div>') }, E2E_TIMEOUT ) test( 'enter with explicit durations', async () => { await page().evaluate(duration => { const { createApp, ref } = (window as any).Vue createApp({ template: ` <div id="container"> <transition name="test" :duration="{ enter: ${duration * 2} }"> <div v-if="toggle" class="test">content</div> </transition> </div> <button id="toggleBtn" @click="click">button</button> `, setup: () => { const toggle = ref(true) const click = () => (toggle.value = !toggle.value) return { toggle, click } } }).mount('#app') }, duration) expect(await html('#container')).toBe('<div class="test">content</div>') // leave expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-to' ]) await transitionFinish() expect(await html('#container')).toBe('<!--v-if-->') // enter expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-to' ]) await transitionFinish(duration * 2) expect(await html('#container')).toBe('<div class="test">content</div>') }, E2E_TIMEOUT ) test( 'leave with explicit durations', async () => { await page().evaluate(duration => { const { createApp, ref } = (window as any).Vue createApp({ template: ` <div id="container"> <transition name="test" :duration="{ leave: ${duration * 2} }"> <div v-if="toggle" class="test">content</div> </transition> </div> <button id="toggleBtn" @click="click">button</button> `, setup: () => { const toggle = ref(true) const click = () => (toggle.value = !toggle.value) return { toggle, click } } }).mount('#app') }, duration) expect(await html('#container')).toBe('<div class="test">content</div>') // leave expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-to' ]) await transitionFinish(duration * 2) expect(await html('#container')).toBe('<!--v-if-->') // enter expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-to' ]) await transitionFinish() expect(await html('#container')).toBe('<div class="test">content</div>') }, E2E_TIMEOUT ) test( 'separate enter and leave', async () => { await page().evaluate(duration => { const { createApp, ref } = (window as any).Vue createApp({ template: ` <div id="container"> <transition name="test" :duration="{ enter: ${duration * 4}, leave: ${duration * 2} }"> <div v-if="toggle" class="test">content</div> </transition> </div> <button id="toggleBtn" @click="click">button</button> `, setup: () => { const toggle = ref(true) const click = () => (toggle.value = !toggle.value) return { toggle, click } } }).mount('#app') }, duration) expect(await html('#container')).toBe('<div class="test">content</div>') // leave expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-leave-active', 'test-leave-to' ]) await transitionFinish(duration * 2) expect(await html('#container')).toBe('<!--v-if-->') // enter expect(await classWhenTransitionStart()).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-from' ]) await nextFrame() expect(await classList('.test')).toStrictEqual([ 'test', 'test-enter-active', 'test-enter-to' ]) await transitionFinish(200) expect(await html('#container')).toBe('<div class="test">content</div>') }, E2E_TIMEOUT ) // fixme test.todo('warn invalid durations') }) })
packages/vue/__tests__/Transition.spec.ts
1
https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02
[ 0.9818061590194702, 0.047078151255846024, 0.0001626006851438433, 0.0007026897510513663, 0.13577140867710114 ]
{ "id": 8, "code_window": [ " 'test-leave-active',\n", " 'test-leave-from'\n", " ])\n", " // fixme\n", " expect(enterCancelledSpy).not.toBeCalled()\n", " await nextFrame()\n", " expect(await classList('.test')).toStrictEqual([\n", " 'test',\n", " 'test-leave-active',\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(enterCancelledSpy).toBeCalled()\n" ], "file_path": "packages/vue/__tests__/Transition.spec.ts", "type": "replace", "edit_start_line_idx": 435 }
<script src="../../dist/vue.global.js"></script> <!-- item template --> <script type="text/x-template" id="item-template"> <li> <div :class="{bold: isFolder}" @click="toggle" @dblclick="changeType"> {{model.name}} <span v-if="isFolder">[{{open ? '-' : '+'}}]</span> </div> <ul v-show="open" v-if="isFolder"> <tree-item class="item" v-for="model in model.children" :model="model"> </tree-item> <li class="add" @click="addChild">+</li> </ul> </li> </script> <!-- item script --> <script> const TreeItem = { name: 'TreeItem', // necessary for self-reference template: '#item-template', props: { model: Object }, data() { return { open: false } }, computed: { isFolder() { return this.model.children && this.model.children.length } }, methods: { toggle() { if (this.isFolder) { this.open = !this.open } }, changeType() { if (!this.isFolder) { this.model.children = [] this.addChild() this.open = true } }, addChild() { this.model.children.push({ name: 'new stuff' }) } } } </script> <p>(You can double click on an item to turn it into a folder.)</p> <!-- the app root element --> <ul id="demo"> <tree-item class="item" :model="treeData"></tree-item> </ul> <script> const treeData = { name: 'My Tree', children: [ { name: 'hello' }, { name: 'wat' }, { name: 'child folder', children: [ { name: 'child folder', children: [ { name: 'hello' }, { name: 'wat' } ] }, { name: 'hello' }, { name: 'wat' }, { name: 'child folder', children: [ { name: 'hello' }, { name: 'wat' } ] } ] } ] } Vue.createApp({ components: { TreeItem }, data: () => ({ treeData }) }).mount('#demo') </script> <style> body { font-family: Menlo, Consolas, monospace; color: #444; } .item { cursor: pointer; } .bold { font-weight: bold; } ul { padding-left: 1em; line-height: 1.5em; list-style-type: dot; } </style>
packages/vue/examples/classic/tree.html
0
https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02
[ 0.00017887917056214064, 0.00017365928215440363, 0.0001703663292573765, 0.00017418671632185578, 0.000002167421371268574 ]
{ "id": 8, "code_window": [ " 'test-leave-active',\n", " 'test-leave-from'\n", " ])\n", " // fixme\n", " expect(enterCancelledSpy).not.toBeCalled()\n", " await nextFrame()\n", " expect(await classList('.test')).toStrictEqual([\n", " 'test',\n", " 'test-leave-active',\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(enterCancelledSpy).toBeCalled()\n" ], "file_path": "packages/vue/__tests__/Transition.spec.ts", "type": "replace", "edit_start_line_idx": 435 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`compiler: v-if codegen basic v-if 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { createVNode: _createVNode, openBlock: _openBlock, createBlock: _createBlock, createCommentVNode: _createCommentVNode } = _Vue return ok ? (_openBlock(), _createBlock(\\"div\\", { key: 0 })) : _createCommentVNode(\\"v-if\\", true) } }" `; exports[`compiler: v-if codegen template v-if 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { createVNode: _createVNode, Fragment: _Fragment, openBlock: _openBlock, createBlock: _createBlock, createCommentVNode: _createCommentVNode } = _Vue return ok ? (_openBlock(), _createBlock(_Fragment, { key: 0 }, [ _createVNode(\\"div\\"), \\"hello\\", _createVNode(\\"p\\") ], 64 /* STABLE_FRAGMENT */)) : _createCommentVNode(\\"v-if\\", true) } }" `; exports[`compiler: v-if codegen template v-if w/ single <slot/> child 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { renderSlot: _renderSlot, createCommentVNode: _createCommentVNode } = _Vue return ok ? _renderSlot($slots, \\"default\\", { key: 0 }) : _createCommentVNode(\\"v-if\\", true) } }" `; exports[`compiler: v-if codegen v-if + v-else 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { createVNode: _createVNode, openBlock: _openBlock, createBlock: _createBlock, createCommentVNode: _createCommentVNode } = _Vue return ok ? (_openBlock(), _createBlock(\\"div\\", { key: 0 })) : (_openBlock(), _createBlock(\\"p\\", { key: 1 })) } }" `; exports[`compiler: v-if codegen v-if + v-else-if + v-else 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { createVNode: _createVNode, openBlock: _openBlock, createBlock: _createBlock, createCommentVNode: _createCommentVNode, Fragment: _Fragment } = _Vue return ok ? (_openBlock(), _createBlock(\\"div\\", { key: 0 })) : orNot ? (_openBlock(), _createBlock(\\"p\\", { key: 1 })) : (_openBlock(), _createBlock(_Fragment, { key: 2 }, [\\"fine\\"], 64 /* STABLE_FRAGMENT */)) } }" `; exports[`compiler: v-if codegen v-if + v-else-if 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { createVNode: _createVNode, openBlock: _openBlock, createBlock: _createBlock, createCommentVNode: _createCommentVNode } = _Vue return ok ? (_openBlock(), _createBlock(\\"div\\", { key: 0 })) : orNot ? (_openBlock(), _createBlock(\\"p\\", { key: 1 })) : _createCommentVNode(\\"v-if\\", true) } }" `; exports[`compiler: v-if codegen v-if on <slot/> 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { renderSlot: _renderSlot, createCommentVNode: _createCommentVNode } = _Vue return ok ? _renderSlot($slots, \\"default\\", { key: 0 }) : _createCommentVNode(\\"v-if\\", true) } }" `; exports[`compiler: v-if codegen v-if with key 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { createVNode: _createVNode, openBlock: _openBlock, createBlock: _createBlock, createCommentVNode: _createCommentVNode } = _Vue return ok ? (_openBlock(), _createBlock(\\"div\\", { key: \\"some-key\\" })) : _createCommentVNode(\\"v-if\\", true) } }" `;
packages/compiler-core/__tests__/transforms/__snapshots__/vIf.spec.ts.snap
0
https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02
[ 0.0001742365420795977, 0.00016921712085604668, 0.00016280997078865767, 0.0001703760790405795, 0.0000033331609756714897 ]
{ "id": 8, "code_window": [ " 'test-leave-active',\n", " 'test-leave-from'\n", " ])\n", " // fixme\n", " expect(enterCancelledSpy).not.toBeCalled()\n", " await nextFrame()\n", " expect(await classList('.test')).toStrictEqual([\n", " 'test',\n", " 'test-leave-active',\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(enterCancelledSpy).toBeCalled()\n" ], "file_path": "packages/vue/__tests__/Transition.spec.ts", "type": "replace", "edit_start_line_idx": 435 }
import { renderToString } from '../src/renderToString' import { createApp, h, withDirectives, vShow, vModelText, vModelRadio, vModelCheckbox } from 'vue' describe('ssr: directives', () => { describe('template v-show', () => { test('basic', async () => { expect( await renderToString( createApp({ template: `<div v-show="true"/>` }) ) ).toBe(`<div style=""></div>`) expect( await renderToString( createApp({ template: `<div v-show="false"/>` }) ) ).toBe(`<div style="display:none;"></div>`) }) test('with static style', async () => { expect( await renderToString( createApp({ template: `<div style="color:red" v-show="false"/>` }) ) ).toBe(`<div style="color:red;display:none;"></div>`) }) test('with dynamic style', async () => { expect( await renderToString( createApp({ data: () => ({ style: { color: 'red' } }), template: `<div :style="style" v-show="false"/>` }) ) ).toBe(`<div style="color:red;display:none;"></div>`) }) test('with static + dynamic style', async () => { expect( await renderToString( createApp({ data: () => ({ style: { color: 'red' } }), template: `<div :style="style" style="font-size:12;" v-show="false"/>` }) ) ).toBe(`<div style="color:red;font-size:12;display:none;"></div>`) }) }) describe('template v-model', () => { test('text', async () => { expect( await renderToString( createApp({ data: () => ({ text: 'hello' }), template: `<input v-model="text">` }) ) ).toBe(`<input value="hello">`) }) test('radio', async () => { expect( await renderToString( createApp({ data: () => ({ selected: 'foo' }), template: `<input type="radio" value="foo" v-model="selected">` }) ) ).toBe(`<input type="radio" value="foo" checked>`) expect( await renderToString( createApp({ data: () => ({ selected: 'foo' }), template: `<input type="radio" value="bar" v-model="selected">` }) ) ).toBe(`<input type="radio" value="bar">`) // non-string values expect( await renderToString( createApp({ data: () => ({ selected: 'foo' }), template: `<input type="radio" :value="{}" v-model="selected">` }) ) ).toBe(`<input type="radio">`) }) test('checkbox', async () => { expect( await renderToString( createApp({ data: () => ({ checked: true }), template: `<input type="checkbox" v-model="checked">` }) ) ).toBe(`<input type="checkbox" checked>`) expect( await renderToString( createApp({ data: () => ({ checked: false }), template: `<input type="checkbox" v-model="checked">` }) ) ).toBe(`<input type="checkbox">`) expect( await renderToString( createApp({ data: () => ({ checked: ['foo'] }), template: `<input type="checkbox" value="foo" v-model="checked">` }) ) ).toBe(`<input type="checkbox" value="foo" checked>`) expect( await renderToString( createApp({ data: () => ({ checked: [] }), template: `<input type="checkbox" value="foo" v-model="checked">` }) ) ).toBe(`<input type="checkbox" value="foo">`) }) test('textarea', async () => { expect( await renderToString( createApp({ data: () => ({ foo: 'hello' }), template: `<textarea v-model="foo"/>` }) ) ).toBe(`<textarea>hello</textarea>`) }) test('dynamic type', async () => { expect( await renderToString( createApp({ data: () => ({ type: 'text', model: 'hello' }), template: `<input :type="type" v-model="model">` }) ) ).toBe(`<input type="text" value="hello">`) expect( await renderToString( createApp({ data: () => ({ type: 'checkbox', model: true }), template: `<input :type="type" v-model="model">` }) ) ).toBe(`<input type="checkbox" checked>`) expect( await renderToString( createApp({ data: () => ({ type: 'checkbox', model: false }), template: `<input :type="type" v-model="model">` }) ) ).toBe(`<input type="checkbox">`) expect( await renderToString( createApp({ data: () => ({ type: 'checkbox', model: ['hello'] }), template: `<input :type="type" value="hello" v-model="model">` }) ) ).toBe(`<input type="checkbox" value="hello" checked>`) expect( await renderToString( createApp({ data: () => ({ type: 'checkbox', model: [] }), template: `<input :type="type" value="hello" v-model="model">` }) ) ).toBe(`<input type="checkbox" value="hello">`) expect( await renderToString( createApp({ data: () => ({ type: 'radio', model: 'hello' }), template: `<input :type="type" value="hello" v-model="model">` }) ) ).toBe(`<input type="radio" value="hello" checked>`) expect( await renderToString( createApp({ data: () => ({ type: 'radio', model: 'hello' }), template: `<input :type="type" value="bar" v-model="model">` }) ) ).toBe(`<input type="radio" value="bar">`) }) test('with v-bind', async () => { expect( await renderToString( createApp({ data: () => ({ obj: { type: 'radio', value: 'hello' }, model: 'hello' }), template: `<input v-bind="obj" v-model="model">` }) ) ).toBe(`<input type="radio" value="hello" checked>`) }) }) describe('vnode v-show', () => { test('basic', async () => { expect( await renderToString( createApp({ render() { return withDirectives(h('div'), [[vShow, true]]) } }) ) ).toBe(`<div></div>`) expect( await renderToString( createApp({ render() { return withDirectives(h('div'), [[vShow, false]]) } }) ) ).toBe(`<div style="display:none;"></div>`) }) test('with merge', async () => { expect( await renderToString( createApp({ render() { return withDirectives( h('div', { style: { color: 'red' } }), [[vShow, false]] ) } }) ) ).toBe(`<div style="color:red;display:none;"></div>`) }) }) describe('vnode v-model', () => { test('text', async () => { expect( await renderToString( createApp({ render() { return withDirectives(h('input'), [[vModelText, 'hello']]) } }) ) ).toBe(`<input value="hello">`) }) test('radio', async () => { expect( await renderToString( createApp({ render() { return withDirectives( h('input', { type: 'radio', value: 'hello' }), [[vModelRadio, 'hello']] ) } }) ) ).toBe(`<input type="radio" value="hello" checked>`) expect( await renderToString( createApp({ render() { return withDirectives( h('input', { type: 'radio', value: 'hello' }), [[vModelRadio, 'foo']] ) } }) ) ).toBe(`<input type="radio" value="hello">`) }) test('checkbox', async () => { expect( await renderToString( createApp({ render() { return withDirectives(h('input', { type: 'checkbox' }), [ [vModelCheckbox, true] ]) } }) ) ).toBe(`<input type="checkbox" checked>`) expect( await renderToString( createApp({ render() { return withDirectives(h('input', { type: 'checkbox' }), [ [vModelCheckbox, false] ]) } }) ) ).toBe(`<input type="checkbox">`) expect( await renderToString( createApp({ render() { return withDirectives( h('input', { type: 'checkbox', value: 'foo' }), [[vModelCheckbox, ['foo']]] ) } }) ) ).toBe(`<input type="checkbox" value="foo" checked>`) expect( await renderToString( createApp({ render() { return withDirectives( h('input', { type: 'checkbox', value: 'foo' }), [[vModelCheckbox, []]] ) } }) ) ).toBe(`<input type="checkbox" value="foo">`) }) }) test('custom directive w/ getSSRProps', async () => { expect( await renderToString( createApp({ render() { return withDirectives(h('div'), [ [ { getSSRProps({ value }) { return { id: value } } }, 'foo' ] ]) } }) ) ).toBe(`<div id="foo"></div>`) }) })
packages/server-renderer/__tests__/ssrDirectives.spec.ts
0
https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02
[ 0.00017714720161166042, 0.00017118519463110715, 0.00016585334378760308, 0.0001713161909719929, 0.0000026557274850347312 ]
{ "id": 9, "code_window": [ " const { createApp, ref } = (window as any).Vue\n", " createApp({\n", " template: `\n", " <div id=\"container\">\n", " <transition name=\"test\">\n", " <div v-show=\"toggle\" class=\"test\" @leave-cancelled=\"onLeaveCancelledSpy\">content</div>\n", " </transition>\n", " </div>\n", " <button id=\"toggleBtn\" @click=\"click\">button</button>\n", " `,\n", " setup: () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <transition name=\"test\" @leave-cancelled=\"onLeaveCancelledSpy\">\n", " <div v-show=\"toggle\" class=\"test\">content</div>\n" ], "file_path": "packages/vue/__tests__/Transition.spec.ts", "type": "replace", "edit_start_line_idx": 1257 }
import { BaseTransition, BaseTransitionProps, h, warn, FunctionalComponent, getCurrentInstance, callWithAsyncErrorHandling } from '@vue/runtime-core' import { isObject, toNumber, extend } from '@vue/shared' import { ErrorCodes } from 'packages/runtime-core/src/errorHandling' const TRANSITION = 'transition' const ANIMATION = 'animation' export interface TransitionProps extends BaseTransitionProps<Element> { name?: string type?: typeof TRANSITION | typeof ANIMATION css?: boolean duration?: number | { enter: number; leave: number } // custom transition classes enterFromClass?: string enterActiveClass?: string enterToClass?: string appearFromClass?: string appearActiveClass?: string appearToClass?: string leaveFromClass?: string leaveActiveClass?: string leaveToClass?: string } // DOM Transition is a higher-order-component based on the platform-agnostic // base Transition component, with DOM-specific logic. export const Transition: FunctionalComponent<TransitionProps> = ( props, { slots } ) => h(BaseTransition, resolveTransitionProps(props), slots) Transition.inheritRef = true const DOMTransitionPropsValidators = { name: String, type: String, css: { type: Boolean, default: true }, duration: [String, Number, Object], enterFromClass: String, enterActiveClass: String, enterToClass: String, appearFromClass: String, appearActiveClass: String, appearToClass: String, leaveFromClass: String, leaveActiveClass: String, leaveToClass: String } export const TransitionPropsValidators = (Transition.props = extend( {}, (BaseTransition as any).props, DOMTransitionPropsValidators )) export function resolveTransitionProps( rawProps: TransitionProps ): BaseTransitionProps<Element> { let { name = 'v', type, css = true, duration, enterFromClass = `${name}-enter-from`, enterActiveClass = `${name}-enter-active`, enterToClass = `${name}-enter-to`, appearFromClass = enterFromClass, appearActiveClass = enterActiveClass, appearToClass = enterToClass, leaveFromClass = `${name}-leave-from`, leaveActiveClass = `${name}-leave-active`, leaveToClass = `${name}-leave-to` } = rawProps const baseProps: BaseTransitionProps<Element> = {} for (const key in rawProps) { if (!(key in DOMTransitionPropsValidators)) { ;(baseProps as any)[key] = (rawProps as any)[key] } } if (!css) { return baseProps } const originEnterClass = [enterFromClass, enterActiveClass, enterToClass] const instance = getCurrentInstance()! const durations = normalizeDuration(duration) const enterDuration = durations && durations[0] const leaveDuration = durations && durations[1] const { appear, onBeforeEnter, onEnter, onLeave } = baseProps // is appearing if (appear && !instance.isMounted) { enterFromClass = appearFromClass enterActiveClass = appearActiveClass enterToClass = appearToClass } type Hook = (el: Element, done?: () => void) => void const finishEnter: Hook = (el, done) => { removeTransitionClass(el, enterToClass) removeTransitionClass(el, enterActiveClass) done && done() // reset enter class if (appear) { ;[enterFromClass, enterActiveClass, enterToClass] = originEnterClass } } const finishLeave: Hook = (el, done) => { removeTransitionClass(el, leaveToClass) removeTransitionClass(el, leaveActiveClass) done && done() } // only needed for user hooks called in nextFrame // sync errors are already handled by BaseTransition function callHookWithErrorHandling(hook: Hook, args: any[]) { callWithAsyncErrorHandling(hook, instance, ErrorCodes.TRANSITION_HOOK, args) } return extend(baseProps, { onBeforeEnter(el) { onBeforeEnter && onBeforeEnter(el) addTransitionClass(el, enterActiveClass) addTransitionClass(el, enterFromClass) }, onEnter(el, done) { nextFrame(() => { const resolve = () => finishEnter(el, done) onEnter && callHookWithErrorHandling(onEnter as Hook, [el, resolve]) removeTransitionClass(el, enterFromClass) addTransitionClass(el, enterToClass) if (!(onEnter && onEnter.length > 1)) { if (enterDuration) { setTimeout(resolve, enterDuration) } else { whenTransitionEnds(el, type, resolve) } } }) }, onLeave(el, done) { addTransitionClass(el, leaveActiveClass) addTransitionClass(el, leaveFromClass) nextFrame(() => { const resolve = () => finishLeave(el, done) onLeave && callHookWithErrorHandling(onLeave as Hook, [el, resolve]) removeTransitionClass(el, leaveFromClass) addTransitionClass(el, leaveToClass) if (!(onLeave && onLeave.length > 1)) { if (leaveDuration) { setTimeout(resolve, leaveDuration) } else { whenTransitionEnds(el, type, resolve) } } }) }, onEnterCancelled: finishEnter, onLeaveCancelled: finishLeave } as BaseTransitionProps<Element>) } function normalizeDuration( duration: TransitionProps['duration'] ): [number, number] | null { if (duration == null) { return null } else if (isObject(duration)) { return [NumberOf(duration.enter), NumberOf(duration.leave)] } else { const n = NumberOf(duration) return [n, n] } } function NumberOf(val: unknown): number { const res = toNumber(val) if (__DEV__) validateDuration(res) return res } function validateDuration(val: unknown) { if (typeof val !== 'number') { warn( `<transition> explicit duration is not a valid number - ` + `got ${JSON.stringify(val)}.` ) } else if (isNaN(val)) { warn( `<transition> explicit duration is NaN - ` + 'the duration expression might be incorrect.' ) } } export interface ElementWithTransition extends HTMLElement { // _vtc = Vue Transition Classes. // Store the temporarily-added transition classes on the element // so that we can avoid overwriting them if the element's class is patched // during the transition. _vtc?: Set<string> } export function addTransitionClass(el: Element, cls: string) { cls.split(/\s+/).forEach(c => c && el.classList.add(c)) ;( (el as ElementWithTransition)._vtc || ((el as ElementWithTransition)._vtc = new Set()) ).add(cls) } export function removeTransitionClass(el: Element, cls: string) { cls.split(/\s+/).forEach(c => c && el.classList.remove(c)) const { _vtc } = el as ElementWithTransition if (_vtc) { _vtc.delete(cls) if (!_vtc!.size) { ;(el as ElementWithTransition)._vtc = undefined } } } function nextFrame(cb: () => void) { requestAnimationFrame(() => { requestAnimationFrame(cb) }) } function whenTransitionEnds( el: Element, expectedType: TransitionProps['type'] | undefined, cb: () => void ) { const { type, timeout, propCount } = getTransitionInfo(el, expectedType) if (!type) { return cb() } const endEvent = type + 'end' let ended = 0 const end = () => { el.removeEventListener(endEvent, onEnd) cb() } const onEnd = (e: Event) => { if (e.target === el) { if (++ended >= propCount) { end() } } } setTimeout(() => { if (ended < propCount) { end() } }, timeout + 1) el.addEventListener(endEvent, onEnd) } interface CSSTransitionInfo { type: typeof TRANSITION | typeof ANIMATION | null propCount: number timeout: number hasTransform: boolean } export function getTransitionInfo( el: Element, expectedType?: TransitionProps['type'] ): CSSTransitionInfo { const styles: any = window.getComputedStyle(el) // JSDOM may return undefined for transition properties const getStyleProperties = (key: string) => (styles[key] || '').split(', ') const transitionDelays = getStyleProperties(TRANSITION + 'Delay') const transitionDurations = getStyleProperties(TRANSITION + 'Duration') const transitionTimeout = getTimeout(transitionDelays, transitionDurations) const animationDelays = getStyleProperties(ANIMATION + 'Delay') const animationDurations = getStyleProperties(ANIMATION + 'Duration') const animationTimeout = getTimeout(animationDelays, animationDurations) let type: CSSTransitionInfo['type'] = null let timeout = 0 let propCount = 0 /* istanbul ignore if */ if (expectedType === TRANSITION) { if (transitionTimeout > 0) { type = TRANSITION timeout = transitionTimeout propCount = transitionDurations.length } } else if (expectedType === ANIMATION) { if (animationTimeout > 0) { type = ANIMATION timeout = animationTimeout propCount = animationDurations.length } } else { timeout = Math.max(transitionTimeout, animationTimeout) type = timeout > 0 ? transitionTimeout > animationTimeout ? TRANSITION : ANIMATION : null propCount = type ? type === TRANSITION ? transitionDurations.length : animationDurations.length : 0 } const hasTransform = type === TRANSITION && /\b(transform|all)(,|$)/.test(styles[TRANSITION + 'Property']) return { type, timeout, propCount, hasTransform } } function getTimeout(delays: string[], durations: string[]): number { while (delays.length < durations.length) { delays = delays.concat(delays) } return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i]))) } // Old versions of Chromium (below 61.0.3163.100) formats floating pointer // numbers in a locale-dependent way, using a comma instead of a dot. // If comma is not replaced with a dot, the input will be rounded down // (i.e. acting as a floor function) causing unexpected behaviors function toMs(s: string): number { return Number(s.slice(0, -1).replace(',', '.')) * 1000 }
packages/runtime-dom/src/components/Transition.ts
1
https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02
[ 0.002569357166066766, 0.00048122057341970503, 0.00016316090477630496, 0.00018348584126215428, 0.0006267418502829969 ]
{ "id": 9, "code_window": [ " const { createApp, ref } = (window as any).Vue\n", " createApp({\n", " template: `\n", " <div id=\"container\">\n", " <transition name=\"test\">\n", " <div v-show=\"toggle\" class=\"test\" @leave-cancelled=\"onLeaveCancelledSpy\">content</div>\n", " </transition>\n", " </div>\n", " <button id=\"toggleBtn\" @click=\"click\">button</button>\n", " `,\n", " setup: () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <transition name=\"test\" @leave-cancelled=\"onLeaveCancelledSpy\">\n", " <div v-show=\"toggle\" class=\"test\">content</div>\n" ], "file_path": "packages/vue/__tests__/Transition.spec.ts", "type": "replace", "edit_start_line_idx": 1257 }
# @vue/compiler-core
packages/compiler-core/README.md
0
https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02
[ 0.00016746725304983556, 0.00016746725304983556, 0.00016746725304983556, 0.00016746725304983556, 0 ]
{ "id": 9, "code_window": [ " const { createApp, ref } = (window as any).Vue\n", " createApp({\n", " template: `\n", " <div id=\"container\">\n", " <transition name=\"test\">\n", " <div v-show=\"toggle\" class=\"test\" @leave-cancelled=\"onLeaveCancelledSpy\">content</div>\n", " </transition>\n", " </div>\n", " <button id=\"toggleBtn\" @click=\"click\">button</button>\n", " `,\n", " setup: () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <transition name=\"test\" @leave-cancelled=\"onLeaveCancelledSpy\">\n", " <div v-show=\"toggle\" class=\"test\">content</div>\n" ], "file_path": "packages/vue/__tests__/Transition.spec.ts", "type": "replace", "edit_start_line_idx": 1257 }
import { isArray } from '@vue/shared' import { TestElement } from './nodeOps' export function triggerEvent( el: TestElement, event: string, payload: any[] = [] ) { const { eventListeners } = el if (eventListeners) { const listener = eventListeners[event] if (listener) { if (isArray(listener)) { for (let i = 0; i < listener.length; i++) { listener[i](...payload) } } else { listener(...payload) } } } }
packages/runtime-test/src/triggerEvent.ts
0
https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02
[ 0.00017177600238937885, 0.0001683644368313253, 0.00016538762429263443, 0.0001679296838119626, 0.0000026260997856297763 ]
{ "id": 9, "code_window": [ " const { createApp, ref } = (window as any).Vue\n", " createApp({\n", " template: `\n", " <div id=\"container\">\n", " <transition name=\"test\">\n", " <div v-show=\"toggle\" class=\"test\" @leave-cancelled=\"onLeaveCancelledSpy\">content</div>\n", " </transition>\n", " </div>\n", " <button id=\"toggleBtn\" @click=\"click\">button</button>\n", " `,\n", " setup: () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <transition name=\"test\" @leave-cancelled=\"onLeaveCancelledSpy\">\n", " <div v-show=\"toggle\" class=\"test\">content</div>\n" ], "file_path": "packages/vue/__tests__/Transition.spec.ts", "type": "replace", "edit_start_line_idx": 1257 }
{ "extends": "../../api-extractor.json", "mainEntryPointFilePath": "./dist/packages/<unscopedPackageName>/src/index.d.ts", "dtsRollup": { "publicTrimmedFilePath": "./dist/<unscopedPackageName>.d.ts" } }
packages/runtime-core/api-extractor.json
0
https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02
[ 0.00017536811355967075, 0.00017536811355967075, 0.00017536811355967075, 0.00017536811355967075, 0 ]
{ "id": 10, "code_window": [ " 'test-enter-active',\n", " 'test-enter-from'\n", " ])\n", " // fixme\n", " expect(onLeaveCancelledSpy).not.toBeCalled()\n", " await nextFrame()\n", " expect(await classList('.test')).toStrictEqual([\n", " 'test',\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " expect(onLeaveCancelledSpy).toBeCalled()\n" ], "file_path": "packages/vue/__tests__/Transition.spec.ts", "type": "replace", "edit_start_line_idx": 1292 }
import { BaseTransition, BaseTransitionProps, h, warn, FunctionalComponent, getCurrentInstance, callWithAsyncErrorHandling } from '@vue/runtime-core' import { isObject, toNumber, extend } from '@vue/shared' import { ErrorCodes } from 'packages/runtime-core/src/errorHandling' const TRANSITION = 'transition' const ANIMATION = 'animation' export interface TransitionProps extends BaseTransitionProps<Element> { name?: string type?: typeof TRANSITION | typeof ANIMATION css?: boolean duration?: number | { enter: number; leave: number } // custom transition classes enterFromClass?: string enterActiveClass?: string enterToClass?: string appearFromClass?: string appearActiveClass?: string appearToClass?: string leaveFromClass?: string leaveActiveClass?: string leaveToClass?: string } // DOM Transition is a higher-order-component based on the platform-agnostic // base Transition component, with DOM-specific logic. export const Transition: FunctionalComponent<TransitionProps> = ( props, { slots } ) => h(BaseTransition, resolveTransitionProps(props), slots) Transition.inheritRef = true const DOMTransitionPropsValidators = { name: String, type: String, css: { type: Boolean, default: true }, duration: [String, Number, Object], enterFromClass: String, enterActiveClass: String, enterToClass: String, appearFromClass: String, appearActiveClass: String, appearToClass: String, leaveFromClass: String, leaveActiveClass: String, leaveToClass: String } export const TransitionPropsValidators = (Transition.props = extend( {}, (BaseTransition as any).props, DOMTransitionPropsValidators )) export function resolveTransitionProps( rawProps: TransitionProps ): BaseTransitionProps<Element> { let { name = 'v', type, css = true, duration, enterFromClass = `${name}-enter-from`, enterActiveClass = `${name}-enter-active`, enterToClass = `${name}-enter-to`, appearFromClass = enterFromClass, appearActiveClass = enterActiveClass, appearToClass = enterToClass, leaveFromClass = `${name}-leave-from`, leaveActiveClass = `${name}-leave-active`, leaveToClass = `${name}-leave-to` } = rawProps const baseProps: BaseTransitionProps<Element> = {} for (const key in rawProps) { if (!(key in DOMTransitionPropsValidators)) { ;(baseProps as any)[key] = (rawProps as any)[key] } } if (!css) { return baseProps } const originEnterClass = [enterFromClass, enterActiveClass, enterToClass] const instance = getCurrentInstance()! const durations = normalizeDuration(duration) const enterDuration = durations && durations[0] const leaveDuration = durations && durations[1] const { appear, onBeforeEnter, onEnter, onLeave } = baseProps // is appearing if (appear && !instance.isMounted) { enterFromClass = appearFromClass enterActiveClass = appearActiveClass enterToClass = appearToClass } type Hook = (el: Element, done?: () => void) => void const finishEnter: Hook = (el, done) => { removeTransitionClass(el, enterToClass) removeTransitionClass(el, enterActiveClass) done && done() // reset enter class if (appear) { ;[enterFromClass, enterActiveClass, enterToClass] = originEnterClass } } const finishLeave: Hook = (el, done) => { removeTransitionClass(el, leaveToClass) removeTransitionClass(el, leaveActiveClass) done && done() } // only needed for user hooks called in nextFrame // sync errors are already handled by BaseTransition function callHookWithErrorHandling(hook: Hook, args: any[]) { callWithAsyncErrorHandling(hook, instance, ErrorCodes.TRANSITION_HOOK, args) } return extend(baseProps, { onBeforeEnter(el) { onBeforeEnter && onBeforeEnter(el) addTransitionClass(el, enterActiveClass) addTransitionClass(el, enterFromClass) }, onEnter(el, done) { nextFrame(() => { const resolve = () => finishEnter(el, done) onEnter && callHookWithErrorHandling(onEnter as Hook, [el, resolve]) removeTransitionClass(el, enterFromClass) addTransitionClass(el, enterToClass) if (!(onEnter && onEnter.length > 1)) { if (enterDuration) { setTimeout(resolve, enterDuration) } else { whenTransitionEnds(el, type, resolve) } } }) }, onLeave(el, done) { addTransitionClass(el, leaveActiveClass) addTransitionClass(el, leaveFromClass) nextFrame(() => { const resolve = () => finishLeave(el, done) onLeave && callHookWithErrorHandling(onLeave as Hook, [el, resolve]) removeTransitionClass(el, leaveFromClass) addTransitionClass(el, leaveToClass) if (!(onLeave && onLeave.length > 1)) { if (leaveDuration) { setTimeout(resolve, leaveDuration) } else { whenTransitionEnds(el, type, resolve) } } }) }, onEnterCancelled: finishEnter, onLeaveCancelled: finishLeave } as BaseTransitionProps<Element>) } function normalizeDuration( duration: TransitionProps['duration'] ): [number, number] | null { if (duration == null) { return null } else if (isObject(duration)) { return [NumberOf(duration.enter), NumberOf(duration.leave)] } else { const n = NumberOf(duration) return [n, n] } } function NumberOf(val: unknown): number { const res = toNumber(val) if (__DEV__) validateDuration(res) return res } function validateDuration(val: unknown) { if (typeof val !== 'number') { warn( `<transition> explicit duration is not a valid number - ` + `got ${JSON.stringify(val)}.` ) } else if (isNaN(val)) { warn( `<transition> explicit duration is NaN - ` + 'the duration expression might be incorrect.' ) } } export interface ElementWithTransition extends HTMLElement { // _vtc = Vue Transition Classes. // Store the temporarily-added transition classes on the element // so that we can avoid overwriting them if the element's class is patched // during the transition. _vtc?: Set<string> } export function addTransitionClass(el: Element, cls: string) { cls.split(/\s+/).forEach(c => c && el.classList.add(c)) ;( (el as ElementWithTransition)._vtc || ((el as ElementWithTransition)._vtc = new Set()) ).add(cls) } export function removeTransitionClass(el: Element, cls: string) { cls.split(/\s+/).forEach(c => c && el.classList.remove(c)) const { _vtc } = el as ElementWithTransition if (_vtc) { _vtc.delete(cls) if (!_vtc!.size) { ;(el as ElementWithTransition)._vtc = undefined } } } function nextFrame(cb: () => void) { requestAnimationFrame(() => { requestAnimationFrame(cb) }) } function whenTransitionEnds( el: Element, expectedType: TransitionProps['type'] | undefined, cb: () => void ) { const { type, timeout, propCount } = getTransitionInfo(el, expectedType) if (!type) { return cb() } const endEvent = type + 'end' let ended = 0 const end = () => { el.removeEventListener(endEvent, onEnd) cb() } const onEnd = (e: Event) => { if (e.target === el) { if (++ended >= propCount) { end() } } } setTimeout(() => { if (ended < propCount) { end() } }, timeout + 1) el.addEventListener(endEvent, onEnd) } interface CSSTransitionInfo { type: typeof TRANSITION | typeof ANIMATION | null propCount: number timeout: number hasTransform: boolean } export function getTransitionInfo( el: Element, expectedType?: TransitionProps['type'] ): CSSTransitionInfo { const styles: any = window.getComputedStyle(el) // JSDOM may return undefined for transition properties const getStyleProperties = (key: string) => (styles[key] || '').split(', ') const transitionDelays = getStyleProperties(TRANSITION + 'Delay') const transitionDurations = getStyleProperties(TRANSITION + 'Duration') const transitionTimeout = getTimeout(transitionDelays, transitionDurations) const animationDelays = getStyleProperties(ANIMATION + 'Delay') const animationDurations = getStyleProperties(ANIMATION + 'Duration') const animationTimeout = getTimeout(animationDelays, animationDurations) let type: CSSTransitionInfo['type'] = null let timeout = 0 let propCount = 0 /* istanbul ignore if */ if (expectedType === TRANSITION) { if (transitionTimeout > 0) { type = TRANSITION timeout = transitionTimeout propCount = transitionDurations.length } } else if (expectedType === ANIMATION) { if (animationTimeout > 0) { type = ANIMATION timeout = animationTimeout propCount = animationDurations.length } } else { timeout = Math.max(transitionTimeout, animationTimeout) type = timeout > 0 ? transitionTimeout > animationTimeout ? TRANSITION : ANIMATION : null propCount = type ? type === TRANSITION ? transitionDurations.length : animationDurations.length : 0 } const hasTransform = type === TRANSITION && /\b(transform|all)(,|$)/.test(styles[TRANSITION + 'Property']) return { type, timeout, propCount, hasTransform } } function getTimeout(delays: string[], durations: string[]): number { while (delays.length < durations.length) { delays = delays.concat(delays) } return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i]))) } // Old versions of Chromium (below 61.0.3163.100) formats floating pointer // numbers in a locale-dependent way, using a comma instead of a dot. // If comma is not replaced with a dot, the input will be rounded down // (i.e. acting as a floor function) causing unexpected behaviors function toMs(s: string): number { return Number(s.slice(0, -1).replace(',', '.')) * 1000 }
packages/runtime-dom/src/components/Transition.ts
1
https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02
[ 0.003262834157794714, 0.0006196936592459679, 0.00016551998851355165, 0.0001729013747535646, 0.0008764248923398554 ]
{ "id": 10, "code_window": [ " 'test-enter-active',\n", " 'test-enter-from'\n", " ])\n", " // fixme\n", " expect(onLeaveCancelledSpy).not.toBeCalled()\n", " await nextFrame()\n", " expect(await classList('.test')).toStrictEqual([\n", " 'test',\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " expect(onLeaveCancelledSpy).toBeCalled()\n" ], "file_path": "packages/vue/__tests__/Transition.spec.ts", "type": "replace", "edit_start_line_idx": 1292 }
import { toRaw, shallowReactive, trigger, TriggerOpTypes } from '@vue/reactivity' import { EMPTY_OBJ, camelize, hyphenate, capitalize, isString, isFunction, isArray, isObject, hasOwn, toRawType, PatchFlags, makeMap, isReservedProp, EMPTY_ARR, def, extend } from '@vue/shared' import { warn } from './warning' import { Data, ComponentInternalInstance, ComponentOptions, Component } from './component' import { isEmitListener } from './componentEmits' import { InternalObjectKey } from './vnode' export type ComponentPropsOptions<P = Data> = | ComponentObjectPropsOptions<P> | string[] export type ComponentObjectPropsOptions<P = Data> = { [K in keyof P]: Prop<P[K]> | null } export type Prop<T> = PropOptions<T> | PropType<T> type DefaultFactory<T> = () => T | null | undefined interface PropOptions<T = any> { type?: PropType<T> | true | null required?: boolean default?: T | DefaultFactory<T> | null | undefined validator?(value: unknown): boolean } export type PropType<T> = PropConstructor<T> | PropConstructor<T>[] type PropConstructor<T = any> = | { new (...args: any[]): T & object } | { (): T } | PropMethod<T> type PropMethod<T, TConstructor = any> = T extends (...args: any) => any // if is function with args ? { new (): TConstructor; (): T; readonly prototype: TConstructor } // Create Function like constructor : never type RequiredKeys<T, MakeDefaultRequired> = { [K in keyof T]: T[K] extends | { required: true } | (MakeDefaultRequired extends true ? { default: any } : never) ? K : never }[keyof T] type OptionalKeys<T, MakeDefaultRequired> = Exclude< keyof T, RequiredKeys<T, MakeDefaultRequired> > 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 } ? { [key: string]: any } : T extends BooleanConstructor | { type: BooleanConstructor } ? boolean : T extends Prop<infer V> ? V : T export type ExtractPropTypes< O, MakeDefaultRequired extends boolean = true > = O extends object ? { [K in RequiredKeys<O, MakeDefaultRequired>]: InferPropType<O[K]> } & { [K in OptionalKeys<O, MakeDefaultRequired>]?: InferPropType<O[K]> } : { [K in string]: any } const enum BooleanFlags { shouldCast, shouldCastTrue } type NormalizedProp = | null | (PropOptions & { [BooleanFlags.shouldCast]?: boolean [BooleanFlags.shouldCastTrue]?: boolean }) // normalized value is a tuple of the actual normalized options // and an array of prop keys that need value casting (booleans and defaults) export type NormalizedPropsOptions = [Record<string, NormalizedProp>, string[]] export function initProps( instance: ComponentInternalInstance, rawProps: Data | null, isStateful: number, // result of bitwise flag comparison isSSR = false ) { const props: Data = {} const attrs: Data = {} def(attrs, InternalObjectKey, 1) setFullProps(instance, rawProps, props, attrs) // validation if (__DEV__) { validateProps(props, instance.type) } if (isStateful) { // stateful instance.props = isSSR ? props : shallowReactive(props) } else { if (!instance.type.props) { // functional w/ optional props, props === attrs instance.props = attrs } else { // functional w/ declared props instance.props = props } } instance.attrs = attrs } export function updateProps( instance: ComponentInternalInstance, rawProps: Data | null, rawPrevProps: Data | null, optimized: boolean ) { const { props, attrs, vnode: { patchFlag } } = instance const rawCurrentProps = toRaw(props) const [options] = normalizePropsOptions(instance.type) if ((optimized || patchFlag > 0) && !(patchFlag & PatchFlags.FULL_PROPS)) { if (patchFlag & PatchFlags.PROPS) { // Compiler-generated props & no keys change, just set the updated // the props. const propsToUpdate = instance.vnode.dynamicProps! for (let i = 0; i < propsToUpdate.length; i++) { const key = propsToUpdate[i] // PROPS flag guarantees rawProps to be non-null const value = rawProps![key] if (options) { // attr / props separation was done on init and will be consistent // in this code path, so just check if attrs have it. if (hasOwn(attrs, key)) { attrs[key] = value } else { const camelizedKey = camelize(key) props[camelizedKey] = resolvePropValue( options, rawCurrentProps, camelizedKey, value ) } } else { attrs[key] = value } } } } else { // full props update. setFullProps(instance, rawProps, props, attrs) // in case of dynamic props, check if we need to delete keys from // the props object let kebabKey: string for (const key in rawCurrentProps) { if ( !rawProps || (!hasOwn(rawProps, key) && // it's possible the original props was passed in as kebab-case // and converted to camelCase (#955) ((kebabKey = hyphenate(key)) === key || !hasOwn(rawProps, kebabKey))) ) { if (options) { if (rawPrevProps && rawPrevProps[kebabKey!] !== undefined) { props[key] = resolvePropValue( options, rawProps || EMPTY_OBJ, key, undefined ) } } else { delete props[key] } } } // in the case of functional component w/o props declaration, props and // attrs point to the same object so it should already have been updated. if (attrs !== rawCurrentProps) { for (const key in attrs) { if (!rawProps || !hasOwn(rawProps, key)) { delete attrs[key] } } } } // trigger updates for $attrs in case it's used in component slots trigger(instance, TriggerOpTypes.SET, '$attrs') if (__DEV__ && rawProps) { validateProps(props, instance.type) } } function setFullProps( instance: ComponentInternalInstance, rawProps: Data | null, props: Data, attrs: Data ) { const [options, needCastKeys] = normalizePropsOptions(instance.type) const emits = instance.type.emits if (rawProps) { for (const key in rawProps) { const value = rawProps[key] // key, ref are reserved and never passed down if (isReservedProp(key)) { continue } // prop option names are camelized during normalization, so to support // kebab -> camel conversion here we need to camelize the key. let camelKey if (options && hasOwn(options, (camelKey = camelize(key)))) { props[camelKey] = value } else if (!emits || !isEmitListener(emits, key)) { // Any non-declared (either as a prop or an emitted event) props are put // into a separate `attrs` object for spreading. Make sure to preserve // original key casing attrs[key] = value } } } if (needCastKeys) { const rawCurrentProps = toRaw(props) for (let i = 0; i < needCastKeys.length; i++) { const key = needCastKeys[i] props[key] = resolvePropValue( options!, rawCurrentProps, key, rawCurrentProps[key] ) } } } function resolvePropValue( options: NormalizedPropsOptions[0], props: Data, key: string, value: unknown ) { const opt = options[key] if (opt != null) { const hasDefault = hasOwn(opt, 'default') // default values if (hasDefault && value === undefined) { const defaultValue = opt.default value = opt.type !== Function && isFunction(defaultValue) ? defaultValue() : defaultValue } // boolean casting if (opt[BooleanFlags.shouldCast]) { if (!hasOwn(props, key) && !hasDefault) { value = false } else if ( opt[BooleanFlags.shouldCastTrue] && (value === '' || value === hyphenate(key)) ) { value = true } } } return value } export function normalizePropsOptions( comp: Component ): NormalizedPropsOptions | [] { if (comp.__props) { return comp.__props } const raw = comp.props const normalized: NormalizedPropsOptions[0] = {} const needCastKeys: NormalizedPropsOptions[1] = [] // apply mixin/extends props let hasExtends = false if (__FEATURE_OPTIONS__ && !isFunction(comp)) { const extendProps = (raw: ComponentOptions) => { const [props, keys] = normalizePropsOptions(raw) extend(normalized, props) if (keys) needCastKeys.push(...keys) } if (comp.extends) { hasExtends = true extendProps(comp.extends) } if (comp.mixins) { hasExtends = true comp.mixins.forEach(extendProps) } } if (!raw && !hasExtends) { return (comp.__props = EMPTY_ARR) } if (isArray(raw)) { for (let i = 0; i < raw.length; i++) { if (__DEV__ && !isString(raw[i])) { warn(`props must be strings when using array syntax.`, raw[i]) } const normalizedKey = camelize(raw[i]) if (validatePropName(normalizedKey)) { normalized[normalizedKey] = EMPTY_OBJ } } } else if (raw) { if (__DEV__ && !isObject(raw)) { warn(`invalid props options`, raw) } for (const key in raw) { const normalizedKey = camelize(key) if (validatePropName(normalizedKey)) { const opt = raw[key] const prop: NormalizedProp = (normalized[normalizedKey] = isArray(opt) || isFunction(opt) ? { type: opt } : opt) if (prop) { const booleanIndex = getTypeIndex(Boolean, prop.type) const stringIndex = getTypeIndex(String, prop.type) prop[BooleanFlags.shouldCast] = booleanIndex > -1 prop[BooleanFlags.shouldCastTrue] = stringIndex < 0 || booleanIndex < stringIndex // if the prop needs boolean casting or default value if (booleanIndex > -1 || hasOwn(prop, 'default')) { needCastKeys.push(normalizedKey) } } } } } const normalizedEntry: NormalizedPropsOptions = [normalized, needCastKeys] comp.__props = normalizedEntry return normalizedEntry } // use function string name to check type constructors // so that it works across vms / iframes. function getType(ctor: Prop<any>): string { const match = ctor && ctor.toString().match(/^\s*function (\w+)/) return match ? match[1] : '' } function isSameType(a: Prop<any>, b: Prop<any>): boolean { return getType(a) === getType(b) } function getTypeIndex( type: Prop<any>, expectedTypes: PropType<any> | void | null | true ): number { if (isArray(expectedTypes)) { for (let i = 0, len = expectedTypes.length; i < len; i++) { if (isSameType(expectedTypes[i], type)) { return i } } } else if (isFunction(expectedTypes)) { return isSameType(expectedTypes, type) ? 0 : -1 } return -1 } /** * dev only */ function validateProps(props: Data, comp: Component) { const rawValues = toRaw(props) const options = normalizePropsOptions(comp)[0] for (const key in options) { let opt = options[key] if (opt == null) continue validateProp(key, rawValues[key], opt, !hasOwn(rawValues, key)) } } /** * dev only */ function validatePropName(key: string) { if (key[0] !== '$') { return true } else if (__DEV__) { warn(`Invalid prop name: "${key}" is a reserved property.`) } return false } /** * dev only */ function validateProp( name: string, value: unknown, prop: PropOptions, isAbsent: boolean ) { const { type, required, validator } = prop // required! if (required && isAbsent) { warn('Missing required prop: "' + name + '"') return } // missing but optional if (value == null && !prop.required) { return } // type check if (type != null && type !== true) { 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)) { warn('Invalid prop: custom validator check failed for prop "' + name + '".') } } const isSimpleType = /*#__PURE__*/ makeMap( 'String,Number,Boolean,Function,Symbol' ) type AssertionResult = { valid: boolean expectedType: string } /** * dev only */ function assertType(value: unknown, type: PropConstructor): AssertionResult { let valid const expectedType = getType(type) if (isSimpleType(expectedType)) { const t = typeof value valid = t === expectedType.toLowerCase() // for primitive wrapper objects if (!valid && t === 'object') { valid = value instanceof type } } else if (expectedType === 'Object') { valid = toRawType(value) === 'Object' } else if (expectedType === 'Array') { valid = isArray(value) } else { valid = value instanceof type } return { valid, expectedType } } /** * dev only */ function getInvalidTypeMessage( name: string, value: unknown, expectedTypes: string[] ): string { 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 */ function styleValue(value: unknown, type: string): string { if (type === 'String') { return `"${value}"` } else if (type === 'Number') { return `${Number(value)}` } else { return `${value}` } } /** * dev only */ function isExplicable(type: string): boolean { const explicitTypes = ['string', 'number', 'boolean'] return explicitTypes.some(elem => type.toLowerCase() === elem) } /** * dev only */ function isBoolean(...args: string[]): boolean { return args.some(elem => elem.toLowerCase() === 'boolean') }
packages/runtime-core/src/componentProps.ts
0
https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02
[ 0.00017468052101321518, 0.00017097831005230546, 0.00016472063725814223, 0.00017142911383416504, 0.000002382274487899849 ]
{ "id": 10, "code_window": [ " 'test-enter-active',\n", " 'test-enter-from'\n", " ])\n", " // fixme\n", " expect(onLeaveCancelledSpy).not.toBeCalled()\n", " await nextFrame()\n", " expect(await classList('.test')).toStrictEqual([\n", " 'test',\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " expect(onLeaveCancelledSpy).toBeCalled()\n" ], "file_path": "packages/vue/__tests__/Transition.spec.ts", "type": "replace", "edit_start_line_idx": 1292 }
# @vue/reactivity ## Usage Note This package is inlined into Global & Browser ESM builds of user-facing renderers (e.g. `@vue/runtime-dom`), but also published as a package that can be used standalone. The standalone build should not be used alongside a pre-bundled build of a user-facing renderer, as they will have different internal storage for reactivity connections. A user-facing renderer should re-export all APIs from this package. For full exposed APIs, see `src/index.ts`. You can also run `yarn build reactivity --types` from repo root, which will generate an API report at `temp/reactivity.api.md`. ## Credits The implementation of this module is inspired by the following prior art in the JavaScript ecosystem: - [Meteor Tracker](https://docs.meteor.com/api/tracker.html) - [nx-js/observer-util](https://github.com/nx-js/observer-util) - [salesforce/observable-membrane](https://github.com/salesforce/observable-membrane) ## Caveats - Built-in objects are not observed except for `Array`, `Map`, `WeakMap`, `Set` and `WeakSet`.
packages/reactivity/README.md
0
https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02
[ 0.00016435836732853204, 0.0001631582126719877, 0.00016195805801544338, 0.0001631582126719877, 0.0000012001546565443277 ]
{ "id": 10, "code_window": [ " 'test-enter-active',\n", " 'test-enter-from'\n", " ])\n", " // fixme\n", " expect(onLeaveCancelledSpy).not.toBeCalled()\n", " await nextFrame()\n", " expect(await classList('.test')).toStrictEqual([\n", " 'test',\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " expect(onLeaveCancelledSpy).toBeCalled()\n" ], "file_path": "packages/vue/__tests__/Transition.spec.ts", "type": "replace", "edit_start_line_idx": 1292 }
{ "extends": "../tsconfig.json", "compilerOptions": { "noEmit": true, "declaration": true }, "exclude": ["../packages/*/__tests__"] }
test-dts/tsconfig.json
0
https://github.com/vuejs/core/commit/acd3156d2c45609ab04cb54734258fe340c4ca02
[ 0.00017301707703154534, 0.00017301707703154534, 0.00017301707703154534, 0.00017301707703154534, 0 ]
{ "id": 0, "code_window": [ " typeof thisItem.value === \"object\"\n", " ) {\n", " e.message +=\n", " `\\n- Maybe you meant to use\\n` +\n", " `\"${type}\": [\\n [\"${lastItem.file.request}\", ${JSON.stringify(\n", " thisItem.value,\n", " undefined,\n", " 2,\n", " )}]\\n]\\n` +\n", " `To be a valid ${type}, its name and options should be wrapped in a pair of brackets`;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " `\"${type}s\": [\\n [\"${lastItem.file.request}\", ${JSON.stringify(\n" ], "file_path": "packages/babel-core/src/config/validation/options.ts", "type": "replace", "edit_start_line_idx": 457 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`option-manager config plugin/preset flattening and overriding should throw when an option is following a preset 1`] = ` "[BABEL] unknown: Unknown option: .useSpread. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options. - Maybe you meant to use \\"preset\\": [ [\\"./fixtures/option-manager/babel-preset-bar\\", { \\"useSpread\\": true }] ] To be a valid preset, its name and options should be wrapped in a pair of brackets" `; exports[`option-manager config plugin/preset flattening and overriding should throw when an option is provided as a plugin 1`] = ` "[BABEL] unknown: .useSpread is not a valid Plugin property - Maybe you meant to use \\"plugin\\": [ [\\"./fixtures/option-manager/babel-plugin-foo\\", { \\"useSpread\\": true }] ] To be a valid plugin, its name and options should be wrapped in a pair of brackets" `; exports[`option-manager config plugin/preset flattening and overriding should throw when an option is provided as a preset 1`] = ` "[BABEL] unknown: Unknown option: .useBuiltIns. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options. - Maybe you meant to use \\"preset\\": [ [\\"./fixtures/option-manager/babel-preset-bar\\", { \\"useBuiltIns\\": \\"entry\\" }] ] To be a valid preset, its name and options should be wrapped in a pair of brackets" `;
packages/babel-core/test/__snapshots__/option-manager.js.snap
1
https://github.com/babel/babel/commit/6df0b7c25f9e1b34cbf41229a784ade38bebde6a
[ 0.0006344141438603401, 0.0004112677415832877, 0.0001673786318860948, 0.0004216391243971884, 0.00017921246762853116 ]
{ "id": 0, "code_window": [ " typeof thisItem.value === \"object\"\n", " ) {\n", " e.message +=\n", " `\\n- Maybe you meant to use\\n` +\n", " `\"${type}\": [\\n [\"${lastItem.file.request}\", ${JSON.stringify(\n", " thisItem.value,\n", " undefined,\n", " 2,\n", " )}]\\n]\\n` +\n", " `To be a valid ${type}, its name and options should be wrapped in a pair of brackets`;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " `\"${type}s\": [\\n [\"${lastItem.file.request}\", ${JSON.stringify(\n" ], "file_path": "packages/babel-core/src/config/validation/options.ts", "type": "replace", "edit_start_line_idx": 457 }
class A {;;}
packages/babel-parser/test/fixtures/esprima/es2015-class/migrated_0003/input.js
0
https://github.com/babel/babel/commit/6df0b7c25f9e1b34cbf41229a784ade38bebde6a
[ 0.00016877034795470536, 0.00016877034795470536, 0.00016877034795470536, 0.00016877034795470536, 0 ]
{ "id": 0, "code_window": [ " typeof thisItem.value === \"object\"\n", " ) {\n", " e.message +=\n", " `\\n- Maybe you meant to use\\n` +\n", " `\"${type}\": [\\n [\"${lastItem.file.request}\", ${JSON.stringify(\n", " thisItem.value,\n", " undefined,\n", " 2,\n", " )}]\\n]\\n` +\n", " `To be a valid ${type}, its name and options should be wrapped in a pair of brackets`;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " `\"${type}s\": [\\n [\"${lastItem.file.request}\", ${JSON.stringify(\n" ], "file_path": "packages/babel-core/src/config/validation/options.ts", "type": "replace", "edit_start_line_idx": 457 }
{ "validateLogs": true, "ignoreOutput": true, "presets": [ [ "env", { "debug": true, "targets": { "electron": 0.36 }, "useBuiltIns": "entry", "corejs": 3 } ] ] }
packages/babel-preset-env/test/fixtures/debug/entry-corejs3-electron/options.json
0
https://github.com/babel/babel/commit/6df0b7c25f9e1b34cbf41229a784ade38bebde6a
[ 0.00016974902246147394, 0.00016815547132864594, 0.00016656190564390272, 0.00016815547132864594, 0.0000015935584087856114 ]
{ "id": 0, "code_window": [ " typeof thisItem.value === \"object\"\n", " ) {\n", " e.message +=\n", " `\\n- Maybe you meant to use\\n` +\n", " `\"${type}\": [\\n [\"${lastItem.file.request}\", ${JSON.stringify(\n", " thisItem.value,\n", " undefined,\n", " 2,\n", " )}]\\n]\\n` +\n", " `To be a valid ${type}, its name and options should be wrapped in a pair of brackets`;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " `\"${type}s\": [\\n [\"${lastItem.file.request}\", ${JSON.stringify(\n" ], "file_path": "packages/babel-core/src/config/validation/options.ts", "type": "replace", "edit_start_line_idx": 457 }
{ "type": "File", "start":0,"end":12,"loc":{"start":{"line":1,"column":0},"end":{"line":1,"column":12}}, "program": { "type": "Program", "start":0,"end":12,"loc":{"start":{"line":1,"column":0},"end":{"line":1,"column":12}}, "sourceType": "script", "interpreter": null, "body": [ { "type": "VariableDeclaration", "start":0,"end":12,"loc":{"start":{"line":1,"column":0},"end":{"line":1,"column":12}}, "declarations": [ { "type": "VariableDeclarator", "start":6,"end":12,"loc":{"start":{"line":1,"column":6},"end":{"line":1,"column":12}}, "id": { "type": "Identifier", "start":6,"end":7,"loc":{"start":{"line":1,"column":6},"end":{"line":1,"column":7},"identifierName":"x"}, "name": "x" }, "init": { "type": "NumericLiteral", "start":10,"end":12,"loc":{"start":{"line":1,"column":10},"end":{"line":1,"column":12}}, "extra": { "rawValue": 42, "raw": "42" }, "value": 42 } } ], "kind": "const" } ], "directives": [] } }
packages/babel-parser/test/fixtures/esprima/declaration-const/migrated_0000/output.json
0
https://github.com/babel/babel/commit/6df0b7c25f9e1b34cbf41229a784ade38bebde6a
[ 0.00017167626356240362, 0.00017085796571336687, 0.00016997447528410703, 0.00017089054745156318, 6.792633371333068e-7 ]
{ "id": 1, "code_window": [ "exports[`option-manager config plugin/preset flattening and overriding should throw when an option is following a preset 1`] = `\n", "\"[BABEL] unknown: Unknown option: .useSpread. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.\n", "- Maybe you meant to use\n", "\\\\\"preset\\\\\": [\n", " [\\\\\"./fixtures/option-manager/babel-preset-bar\\\\\", {\n", " \\\\\"useSpread\\\\\": true\n", "}]\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\\\\\"presets\\\\\": [\n" ], "file_path": "packages/babel-core/test/__snapshots__/option-manager.js.snap", "type": "replace", "edit_start_line_idx": 5 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`option-manager config plugin/preset flattening and overriding should throw when an option is following a preset 1`] = ` "[BABEL] unknown: Unknown option: .useSpread. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options. - Maybe you meant to use \\"preset\\": [ [\\"./fixtures/option-manager/babel-preset-bar\\", { \\"useSpread\\": true }] ] To be a valid preset, its name and options should be wrapped in a pair of brackets" `; exports[`option-manager config plugin/preset flattening and overriding should throw when an option is provided as a plugin 1`] = ` "[BABEL] unknown: .useSpread is not a valid Plugin property - Maybe you meant to use \\"plugin\\": [ [\\"./fixtures/option-manager/babel-plugin-foo\\", { \\"useSpread\\": true }] ] To be a valid plugin, its name and options should be wrapped in a pair of brackets" `; exports[`option-manager config plugin/preset flattening and overriding should throw when an option is provided as a preset 1`] = ` "[BABEL] unknown: Unknown option: .useBuiltIns. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options. - Maybe you meant to use \\"preset\\": [ [\\"./fixtures/option-manager/babel-preset-bar\\", { \\"useBuiltIns\\": \\"entry\\" }] ] To be a valid preset, its name and options should be wrapped in a pair of brackets" `;
packages/babel-core/test/__snapshots__/option-manager.js.snap
1
https://github.com/babel/babel/commit/6df0b7c25f9e1b34cbf41229a784ade38bebde6a
[ 0.9930029511451721, 0.33024224638938904, 0.0012906078482046723, 0.16333775222301483, 0.3936578333377838 ]
{ "id": 1, "code_window": [ "exports[`option-manager config plugin/preset flattening and overriding should throw when an option is following a preset 1`] = `\n", "\"[BABEL] unknown: Unknown option: .useSpread. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.\n", "- Maybe you meant to use\n", "\\\\\"preset\\\\\": [\n", " [\\\\\"./fixtures/option-manager/babel-preset-bar\\\\\", {\n", " \\\\\"useSpread\\\\\": true\n", "}]\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\\\\\"presets\\\\\": [\n" ], "file_path": "packages/babel-core/test/__snapshots__/option-manager.js.snap", "type": "replace", "edit_start_line_idx": 5 }
{ "type": "File", "start":0,"end":70,"loc":{"start":{"line":1,"column":0},"end":{"line":7,"column":1}}, "program": { "type": "Program", "start":0,"end":70,"loc":{"start":{"line":1,"column":0},"end":{"line":7,"column":1}}, "sourceType": "module", "interpreter": null, "body": [ { "type": "ClassDeclaration", "start":0,"end":70,"loc":{"start":{"line":1,"column":0},"end":{"line":7,"column":1}}, "id": { "type": "Identifier", "start":6,"end":7,"loc":{"start":{"line":1,"column":6},"end":{"line":1,"column":7},"identifierName":"A"}, "name": "A" }, "superClass": null, "body": { "type": "ClassBody", "start":8,"end":70,"loc":{"start":{"line":1,"column":8},"end":{"line":7,"column":1}}, "body": [ { "type": "ClassPrivateProperty", "start":12,"end":23,"loc":{"start":{"line":2,"column":2},"end":{"line":2,"column":13}}, "static": false, "key": { "type": "PrivateName", "start":12,"end":14,"loc":{"start":{"line":2,"column":2},"end":{"line":2,"column":4}}, "id": { "type": "Identifier", "start":13,"end":14,"loc":{"start":{"line":2,"column":3},"end":{"line":2,"column":4},"identifierName":"a"}, "name": "a" } }, "typeAnnotation": { "type": "TSTypeAnnotation", "start":14,"end":22,"loc":{"start":{"line":2,"column":4},"end":{"line":2,"column":12}}, "typeAnnotation": { "type": "TSStringKeyword", "start":16,"end":22,"loc":{"start":{"line":2,"column":6},"end":{"line":2,"column":12}} } }, "value": null }, { "type": "ClassPrivateProperty", "start":26,"end":30,"loc":{"start":{"line":3,"column":2},"end":{"line":3,"column":6}}, "static": false, "key": { "type": "PrivateName", "start":26,"end":28,"loc":{"start":{"line":3,"column":2},"end":{"line":3,"column":4}}, "id": { "type": "Identifier", "start":27,"end":28,"loc":{"start":{"line":3,"column":3},"end":{"line":3,"column":4},"identifierName":"b"}, "name": "b" } }, "optional": true, "value": null }, { "type": "ClassPrivateProperty", "start":33,"end":45,"loc":{"start":{"line":4,"column":2},"end":{"line":4,"column":14}}, "static": false, "key": { "type": "PrivateName", "start":33,"end":35,"loc":{"start":{"line":4,"column":2},"end":{"line":4,"column":4}}, "id": { "type": "Identifier", "start":34,"end":35,"loc":{"start":{"line":4,"column":3},"end":{"line":4,"column":4},"identifierName":"c"}, "name": "c" } }, "optional": true, "typeAnnotation": { "type": "TSTypeAnnotation", "start":36,"end":44,"loc":{"start":{"line":4,"column":5},"end":{"line":4,"column":13}}, "typeAnnotation": { "type": "TSNumberKeyword", "start":38,"end":44,"loc":{"start":{"line":4,"column":7},"end":{"line":4,"column":13}} } }, "value": null }, { "type": "ClassPrivateProperty", "start":48,"end":52,"loc":{"start":{"line":5,"column":2},"end":{"line":5,"column":6}}, "static": false, "key": { "type": "PrivateName", "start":48,"end":50,"loc":{"start":{"line":5,"column":2},"end":{"line":5,"column":4}}, "id": { "type": "Identifier", "start":49,"end":50,"loc":{"start":{"line":5,"column":3},"end":{"line":5,"column":4},"identifierName":"d"}, "name": "d" } }, "definite": true, "value": null }, { "type": "ClassPrivateProperty", "start":55,"end":68,"loc":{"start":{"line":6,"column":2},"end":{"line":6,"column":15}}, "static": false, "key": { "type": "PrivateName", "start":55,"end":57,"loc":{"start":{"line":6,"column":2},"end":{"line":6,"column":4}}, "id": { "type": "Identifier", "start":56,"end":57,"loc":{"start":{"line":6,"column":3},"end":{"line":6,"column":4},"identifierName":"e"}, "name": "e" } }, "definite": true, "typeAnnotation": { "type": "TSTypeAnnotation", "start":58,"end":67,"loc":{"start":{"line":6,"column":5},"end":{"line":6,"column":14}}, "typeAnnotation": { "type": "TSBooleanKeyword", "start":60,"end":67,"loc":{"start":{"line":6,"column":7},"end":{"line":6,"column":14}} } }, "value": null } ] } } ], "directives": [] } }
packages/babel-parser/test/fixtures/typescript/class/private-fields/output.json
0
https://github.com/babel/babel/commit/6df0b7c25f9e1b34cbf41229a784ade38bebde6a
[ 0.0001743010216159746, 0.00017157559341285378, 0.0001677936379564926, 0.00017173605738207698, 0.0000016024970364014735 ]
{ "id": 1, "code_window": [ "exports[`option-manager config plugin/preset flattening and overriding should throw when an option is following a preset 1`] = `\n", "\"[BABEL] unknown: Unknown option: .useSpread. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.\n", "- Maybe you meant to use\n", "\\\\\"preset\\\\\": [\n", " [\\\\\"./fixtures/option-manager/babel-preset-bar\\\\\", {\n", " \\\\\"useSpread\\\\\": true\n", "}]\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\\\\\"presets\\\\\": [\n" ], "file_path": "packages/babel-core/test/__snapshots__/option-manager.js.snap", "type": "replace", "edit_start_line_idx": 5 }
import runner from "@babel/helper-plugin-test-runner"; runner(import.meta.url);
packages/babel-plugin-transform-dotall-regex/test/index.js
0
https://github.com/babel/babel/commit/6df0b7c25f9e1b34cbf41229a784ade38bebde6a
[ 0.00016719137784093618, 0.00016719137784093618, 0.00016719137784093618, 0.00016719137784093618, 0 ]
{ "id": 1, "code_window": [ "exports[`option-manager config plugin/preset flattening and overriding should throw when an option is following a preset 1`] = `\n", "\"[BABEL] unknown: Unknown option: .useSpread. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.\n", "- Maybe you meant to use\n", "\\\\\"preset\\\\\": [\n", " [\\\\\"./fixtures/option-manager/babel-preset-bar\\\\\", {\n", " \\\\\"useSpread\\\\\": true\n", "}]\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\\\\\"presets\\\\\": [\n" ], "file_path": "packages/babel-core/test/__snapshots__/option-manager.js.snap", "type": "replace", "edit_start_line_idx": 5 }
{ "plugins": ["./plugin"] }
packages/babel-traverse/test/fixtures/rename/catch-clause/options.json
0
https://github.com/babel/babel/commit/6df0b7c25f9e1b34cbf41229a784ade38bebde6a
[ 0.00018152085249312222, 0.00018152085249312222, 0.00018152085249312222, 0.00018152085249312222, 0 ]
{ "id": 2, "code_window": [ "exports[`option-manager config plugin/preset flattening and overriding should throw when an option is provided as a plugin 1`] = `\n", "\"[BABEL] unknown: .useSpread is not a valid Plugin property\n", "- Maybe you meant to use\n", "\\\\\"plugin\\\\\": [\n", " [\\\\\"./fixtures/option-manager/babel-plugin-foo\\\\\", {\n", " \\\\\"useSpread\\\\\": true\n", "}]\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\\\\\"plugins\\\\\": [\n" ], "file_path": "packages/babel-core/test/__snapshots__/option-manager.js.snap", "type": "replace", "edit_start_line_idx": 16 }
import type { InputTargets, Targets } from "@babel/helper-compilation-targets"; import type { ConfigItem } from "../item"; import Plugin from "../plugin"; import removed from "./removed"; import { msg, access, assertString, assertBoolean, assertObject, assertArray, assertCallerMetadata, assertInputSourceMap, assertIgnoreList, assertPluginList, assertConfigApplicableTest, assertConfigFileSearch, assertBabelrcSearch, assertFunction, assertRootMode, assertSourceMaps, assertCompact, assertSourceType, assertTargets, assertAssumptions, } from "./option-assertions"; import type { ValidatorSet, Validator, OptionPath } from "./option-assertions"; import type { UnloadedDescriptor } from "../config-descriptors"; const ROOT_VALIDATORS: ValidatorSet = { cwd: assertString as Validator<ValidatedOptions["cwd"]>, root: assertString as Validator<ValidatedOptions["root"]>, rootMode: assertRootMode as Validator<ValidatedOptions["rootMode"]>, configFile: assertConfigFileSearch as Validator< ValidatedOptions["configFile"] >, caller: assertCallerMetadata as Validator<ValidatedOptions["caller"]>, filename: assertString as Validator<ValidatedOptions["filename"]>, filenameRelative: assertString as Validator< ValidatedOptions["filenameRelative"] >, code: assertBoolean as Validator<ValidatedOptions["code"]>, ast: assertBoolean as Validator<ValidatedOptions["ast"]>, cloneInputAst: assertBoolean as Validator<ValidatedOptions["cloneInputAst"]>, envName: assertString as Validator<ValidatedOptions["envName"]>, }; const BABELRC_VALIDATORS: ValidatorSet = { babelrc: assertBoolean as Validator<ValidatedOptions["babelrc"]>, babelrcRoots: assertBabelrcSearch as Validator< ValidatedOptions["babelrcRoots"] >, }; const NONPRESET_VALIDATORS: ValidatorSet = { extends: assertString as Validator<ValidatedOptions["extends"]>, ignore: assertIgnoreList as Validator<ValidatedOptions["ignore"]>, only: assertIgnoreList as Validator<ValidatedOptions["only"]>, targets: assertTargets as Validator<ValidatedOptions["targets"]>, browserslistConfigFile: assertConfigFileSearch as Validator< ValidatedOptions["browserslistConfigFile"] >, browserslistEnv: assertString as Validator< ValidatedOptions["browserslistEnv"] >, }; const COMMON_VALIDATORS: ValidatorSet = { // TODO: Should 'inputSourceMap' be moved to be a root-only option? // We may want a boolean-only version to be a common option, with the // object only allowed as a root config argument. inputSourceMap: assertInputSourceMap as Validator< ValidatedOptions["inputSourceMap"] >, presets: assertPluginList as Validator<ValidatedOptions["presets"]>, plugins: assertPluginList as Validator<ValidatedOptions["plugins"]>, passPerPreset: assertBoolean as Validator<ValidatedOptions["passPerPreset"]>, assumptions: assertAssumptions as Validator<ValidatedOptions["assumptions"]>, env: assertEnvSet as Validator<ValidatedOptions["env"]>, overrides: assertOverridesList as Validator<ValidatedOptions["overrides"]>, // We could limit these to 'overrides' blocks, but it's not clear why we'd // bother, when the ability to limit a config to a specific set of files // is a fairly general useful feature. test: assertConfigApplicableTest as Validator<ValidatedOptions["test"]>, include: assertConfigApplicableTest as Validator<ValidatedOptions["include"]>, exclude: assertConfigApplicableTest as Validator<ValidatedOptions["exclude"]>, retainLines: assertBoolean as Validator<ValidatedOptions["retainLines"]>, comments: assertBoolean as Validator<ValidatedOptions["comments"]>, shouldPrintComment: assertFunction as Validator< ValidatedOptions["shouldPrintComment"] >, compact: assertCompact as Validator<ValidatedOptions["compact"]>, minified: assertBoolean as Validator<ValidatedOptions["minified"]>, auxiliaryCommentBefore: assertString as Validator< ValidatedOptions["auxiliaryCommentBefore"] >, auxiliaryCommentAfter: assertString as Validator< ValidatedOptions["auxiliaryCommentAfter"] >, sourceType: assertSourceType as Validator<ValidatedOptions["sourceType"]>, wrapPluginVisitorMethod: assertFunction as Validator< ValidatedOptions["wrapPluginVisitorMethod"] >, highlightCode: assertBoolean as Validator<ValidatedOptions["highlightCode"]>, sourceMaps: assertSourceMaps as Validator<ValidatedOptions["sourceMaps"]>, sourceMap: assertSourceMaps as Validator<ValidatedOptions["sourceMap"]>, sourceFileName: assertString as Validator<ValidatedOptions["sourceFileName"]>, sourceRoot: assertString as Validator<ValidatedOptions["sourceRoot"]>, parserOpts: assertObject as Validator<ValidatedOptions["parserOpts"]>, generatorOpts: assertObject as Validator<ValidatedOptions["generatorOpts"]>, }; if (!process.env.BABEL_8_BREAKING) { Object.assign(COMMON_VALIDATORS, { getModuleId: assertFunction, moduleRoot: assertString, moduleIds: assertBoolean, moduleId: assertString, }); } export type InputOptions = ValidatedOptions; export type ValidatedOptions = { cwd?: string; filename?: string; filenameRelative?: string; babelrc?: boolean; babelrcRoots?: BabelrcSearch; configFile?: ConfigFileSearch; root?: string; rootMode?: RootMode; code?: boolean; ast?: boolean; cloneInputAst?: boolean; inputSourceMap?: RootInputSourceMapOption; envName?: string; caller?: CallerMetadata; extends?: string; env?: EnvSet<ValidatedOptions>; ignore?: IgnoreList; only?: IgnoreList; overrides?: OverridesList; // Generally verify if a given config object should be applied to the given file. test?: ConfigApplicableTest; include?: ConfigApplicableTest; exclude?: ConfigApplicableTest; presets?: PluginList; plugins?: PluginList; passPerPreset?: boolean; assumptions?: { [name: string]: boolean; }; // browserslists-related options targets?: TargetsListOrObject; browserslistConfigFile?: ConfigFileSearch; browserslistEnv?: string; // Options for @babel/generator retainLines?: boolean; comments?: boolean; shouldPrintComment?: Function; compact?: CompactOption; minified?: boolean; auxiliaryCommentBefore?: string; auxiliaryCommentAfter?: string; // Parser sourceType?: SourceTypeOption; wrapPluginVisitorMethod?: Function; highlightCode?: boolean; // Sourcemap generation options. sourceMaps?: SourceMapsOption; sourceMap?: SourceMapsOption; sourceFileName?: string; sourceRoot?: string; // Deprecate top level parserOpts parserOpts?: {}; // Deprecate top level generatorOpts generatorOpts?: {}; }; export type NormalizedOptions = { readonly targets: Targets; } & Omit<ValidatedOptions, "targets">; export type CallerMetadata = { // If 'caller' is specified, require that the name is given for debugging // messages. name: string; }; export type EnvSet<T> = { [x: string]: T; }; export type IgnoreItem = string | Function | RegExp; export type IgnoreList = ReadonlyArray<IgnoreItem>; export type PluginOptions = object | void | false; export type PluginTarget = string | object | Function; export type PluginItem = | ConfigItem | Plugin | PluginTarget | [PluginTarget, PluginOptions] | [PluginTarget, PluginOptions, string | void]; export type PluginList = ReadonlyArray<PluginItem>; export type OverridesList = Array<ValidatedOptions>; export type ConfigApplicableTest = IgnoreItem | Array<IgnoreItem>; export type ConfigFileSearch = string | boolean; export type BabelrcSearch = boolean | IgnoreItem | IgnoreList; export type SourceMapsOption = boolean | "inline" | "both"; export type SourceTypeOption = "module" | "script" | "unambiguous"; export type CompactOption = boolean | "auto"; export type RootInputSourceMapOption = {} | boolean; export type RootMode = "root" | "upward" | "upward-optional"; export type TargetsListOrObject = | Targets | InputTargets | InputTargets["browsers"]; export type OptionsSource = | "arguments" | "configfile" | "babelrcfile" | "extendsfile" | "preset" | "plugin"; export type RootPath = Readonly<{ type: "root"; source: OptionsSource; }>; type OverridesPath = Readonly<{ type: "overrides"; index: number; parent: RootPath; }>; type EnvPath = Readonly<{ type: "env"; name: string; parent: RootPath | OverridesPath; }>; export type NestingPath = RootPath | OverridesPath | EnvPath; export const assumptionsNames = new Set<string>([ "arrayLikeIsIterable", "constantReexports", "constantSuper", "enumerableModuleMeta", "ignoreFunctionLength", "ignoreToPrimitiveHint", "iterableIsArray", "mutableTemplateObject", "noClassCalls", "noDocumentAll", "noNewArrows", "objectRestNoSymbols", "privateFieldsAsProperties", "pureGetters", "setClassMethods", "setComputedProperties", "setPublicClassFields", "setSpreadProperties", "skipForOfIteratorClosing", "superIsCallableConstructor", ]); function getSource(loc: NestingPath): OptionsSource { return loc.type === "root" ? loc.source : getSource(loc.parent); } export function validate(type: OptionsSource, opts: {}): ValidatedOptions { return validateNested( { type: "root", source: type, }, opts, ); } function validateNested(loc: NestingPath, opts: {}) { const type = getSource(loc); assertNoDuplicateSourcemap(opts); Object.keys(opts).forEach((key: string) => { const optLoc = { type: "option", name: key, parent: loc, } as const; if (type === "preset" && NONPRESET_VALIDATORS[key]) { throw new Error(`${msg(optLoc)} is not allowed in preset options`); } if (type !== "arguments" && ROOT_VALIDATORS[key]) { throw new Error( `${msg(optLoc)} is only allowed in root programmatic options`, ); } if ( type !== "arguments" && type !== "configfile" && BABELRC_VALIDATORS[key] ) { if (type === "babelrcfile" || type === "extendsfile") { throw new Error( `${msg( optLoc, )} is not allowed in .babelrc or "extends"ed files, only in root programmatic options, ` + `or babel.config.js/config file options`, ); } throw new Error( `${msg( optLoc, )} is only allowed in root programmatic options, or babel.config.js/config file options`, ); } const validator = COMMON_VALIDATORS[key] || NONPRESET_VALIDATORS[key] || BABELRC_VALIDATORS[key] || ROOT_VALIDATORS[key] || (throwUnknownError as Validator<void>); validator(optLoc, opts[key]); }); return opts; } function throwUnknownError(loc: OptionPath) { const key = loc.name; if (removed[key]) { const { message, version = 5 } = removed[key]; throw new Error( `Using removed Babel ${version} option: ${msg(loc)} - ${message}`, ); } else { // eslint-disable-next-line max-len const unknownOptErr = new Error( `Unknown option: ${msg( loc, )}. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.`, ); // @ts-expect-error todo(flow->ts): consider creating something like BabelConfigError with code field in it unknownOptErr.code = "BABEL_UNKNOWN_OPTION"; throw unknownOptErr; } } function has(obj: {}, key: string) { return Object.prototype.hasOwnProperty.call(obj, key); } function assertNoDuplicateSourcemap(opts: {}): void { if (has(opts, "sourceMap") && has(opts, "sourceMaps")) { throw new Error(".sourceMap is an alias for .sourceMaps, cannot use both"); } } function assertEnvSet( loc: OptionPath, value: unknown, ): void | EnvSet<ValidatedOptions> { if (loc.parent.type === "env") { throw new Error(`${msg(loc)} is not allowed inside of another .env block`); } const parent: RootPath | OverridesPath = loc.parent; const obj = assertObject(loc, value); if (obj) { // Validate but don't copy the .env object in order to preserve // object identity for use during config chain processing. for (const envName of Object.keys(obj)) { const env = assertObject(access(loc, envName), obj[envName]); if (!env) continue; const envLoc = { type: "env", name: envName, parent, } as const; validateNested(envLoc, env); } } return obj; } function assertOverridesList( loc: OptionPath, value: unknown[], ): undefined | OverridesList { if (loc.parent.type === "env") { throw new Error(`${msg(loc)} is not allowed inside an .env block`); } if (loc.parent.type === "overrides") { throw new Error(`${msg(loc)} is not allowed inside an .overrides block`); } const parent: RootPath = loc.parent; const arr = assertArray(loc, value); if (arr) { for (const [index, item] of arr.entries()) { const objLoc = access(loc, index); const env = assertObject(objLoc, item); if (!env) throw new Error(`${msg(objLoc)} must be an object`); const overridesLoc = { type: "overrides", index, parent, } as const; validateNested(overridesLoc, env); } } // @ts-expect-error return arr; } export function checkNoUnwrappedItemOptionPairs( items: Array<UnloadedDescriptor>, index: number, type: "plugin" | "preset", e: Error, ): void { if (index === 0) return; const lastItem = items[index - 1]; const thisItem = items[index]; if ( lastItem.file && lastItem.options === undefined && typeof thisItem.value === "object" ) { e.message += `\n- Maybe you meant to use\n` + `"${type}": [\n ["${lastItem.file.request}", ${JSON.stringify( thisItem.value, undefined, 2, )}]\n]\n` + `To be a valid ${type}, its name and options should be wrapped in a pair of brackets`; } }
packages/babel-core/src/config/validation/options.ts
1
https://github.com/babel/babel/commit/6df0b7c25f9e1b34cbf41229a784ade38bebde6a
[ 0.09020579606294632, 0.002341899089515209, 0.00016255168884526938, 0.0001753532123984769, 0.012991541065275669 ]
{ "id": 2, "code_window": [ "exports[`option-manager config plugin/preset flattening and overriding should throw when an option is provided as a plugin 1`] = `\n", "\"[BABEL] unknown: .useSpread is not a valid Plugin property\n", "- Maybe you meant to use\n", "\\\\\"plugin\\\\\": [\n", " [\\\\\"./fixtures/option-manager/babel-plugin-foo\\\\\", {\n", " \\\\\"useSpread\\\\\": true\n", "}]\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\\\\\"plugins\\\\\": [\n" ], "file_path": "packages/babel-core/test/__snapshots__/option-manager.js.snap", "type": "replace", "edit_start_line_idx": 16 }
module.exports = require("./plugin")("fourteen");
packages/babel-core/test/fixtures/config/complex-plugin-config/fourteen.js
0
https://github.com/babel/babel/commit/6df0b7c25f9e1b34cbf41229a784ade38bebde6a
[ 0.0002785969409160316, 0.0002785969409160316, 0.0002785969409160316, 0.0002785969409160316, 0 ]
{ "id": 2, "code_window": [ "exports[`option-manager config plugin/preset flattening and overriding should throw when an option is provided as a plugin 1`] = `\n", "\"[BABEL] unknown: .useSpread is not a valid Plugin property\n", "- Maybe you meant to use\n", "\\\\\"plugin\\\\\": [\n", " [\\\\\"./fixtures/option-manager/babel-plugin-foo\\\\\", {\n", " \\\\\"useSpread\\\\\": true\n", "}]\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\\\\\"plugins\\\\\": [\n" ], "file_path": "packages/babel-core/test/__snapshots__/option-manager.js.snap", "type": "replace", "edit_start_line_idx": 16 }
let x: typeof import('./x'); let Y: import('./y').Y; let z: import("/z").foo.bar<string>;
packages/babel-parser/test/fixtures/estree/typescript/import/input.js
0
https://github.com/babel/babel/commit/6df0b7c25f9e1b34cbf41229a784ade38bebde6a
[ 0.00016479904297739267, 0.00016479904297739267, 0.00016479904297739267, 0.00016479904297739267, 0 ]
{ "id": 2, "code_window": [ "exports[`option-manager config plugin/preset flattening and overriding should throw when an option is provided as a plugin 1`] = `\n", "\"[BABEL] unknown: .useSpread is not a valid Plugin property\n", "- Maybe you meant to use\n", "\\\\\"plugin\\\\\": [\n", " [\\\\\"./fixtures/option-manager/babel-plugin-foo\\\\\", {\n", " \\\\\"useSpread\\\\\": true\n", "}]\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\\\\\"plugins\\\\\": [\n" ], "file_path": "packages/babel-core/test/__snapshots__/option-manager.js.snap", "type": "replace", "edit_start_line_idx": 16 }
var _client = /*#__PURE__*/babelHelpers.classPrivateFieldLooseKey("client"); var Foo = function Foo(props) { "use strict"; babelHelpers.classCallCheck(this, Foo); Object.defineProperty(this, _client, { writable: true, value: void 0 }); [x, ...babelHelpers.classPrivateFieldLooseBase(this, _client)[_client]] = props; };
packages/babel-plugin-proposal-class-properties/test/fixtures/private-loose/destructuring-array-pattern-2/output.js
0
https://github.com/babel/babel/commit/6df0b7c25f9e1b34cbf41229a784ade38bebde6a
[ 0.000627613568212837, 0.0004118441720493138, 0.00019607474678196013, 0.0004118441720493138, 0.00021576941071543843 ]
{ "id": 3, "code_window": [ "\n", "exports[`option-manager config plugin/preset flattening and overriding should throw when an option is provided as a preset 1`] = `\n", "\"[BABEL] unknown: Unknown option: .useBuiltIns. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.\n", "- Maybe you meant to use\n", "\\\\\"preset\\\\\": [\n", " [\\\\\"./fixtures/option-manager/babel-preset-bar\\\\\", {\n", " \\\\\"useBuiltIns\\\\\": \\\\\"entry\\\\\"\n", "}]\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\\\\\"presets\\\\\": [\n" ], "file_path": "packages/babel-core/test/__snapshots__/option-manager.js.snap", "type": "replace", "edit_start_line_idx": 27 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`option-manager config plugin/preset flattening and overriding should throw when an option is following a preset 1`] = ` "[BABEL] unknown: Unknown option: .useSpread. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options. - Maybe you meant to use \\"preset\\": [ [\\"./fixtures/option-manager/babel-preset-bar\\", { \\"useSpread\\": true }] ] To be a valid preset, its name and options should be wrapped in a pair of brackets" `; exports[`option-manager config plugin/preset flattening and overriding should throw when an option is provided as a plugin 1`] = ` "[BABEL] unknown: .useSpread is not a valid Plugin property - Maybe you meant to use \\"plugin\\": [ [\\"./fixtures/option-manager/babel-plugin-foo\\", { \\"useSpread\\": true }] ] To be a valid plugin, its name and options should be wrapped in a pair of brackets" `; exports[`option-manager config plugin/preset flattening and overriding should throw when an option is provided as a preset 1`] = ` "[BABEL] unknown: Unknown option: .useBuiltIns. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options. - Maybe you meant to use \\"preset\\": [ [\\"./fixtures/option-manager/babel-preset-bar\\", { \\"useBuiltIns\\": \\"entry\\" }] ] To be a valid preset, its name and options should be wrapped in a pair of brackets" `;
packages/babel-core/test/__snapshots__/option-manager.js.snap
1
https://github.com/babel/babel/commit/6df0b7c25f9e1b34cbf41229a784ade38bebde6a
[ 0.9947370886802673, 0.32854339480400085, 0.0006469556828960776, 0.15939480066299438, 0.3901951014995575 ]
{ "id": 3, "code_window": [ "\n", "exports[`option-manager config plugin/preset flattening and overriding should throw when an option is provided as a preset 1`] = `\n", "\"[BABEL] unknown: Unknown option: .useBuiltIns. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.\n", "- Maybe you meant to use\n", "\\\\\"preset\\\\\": [\n", " [\\\\\"./fixtures/option-manager/babel-preset-bar\\\\\", {\n", " \\\\\"useBuiltIns\\\\\": \\\\\"entry\\\\\"\n", "}]\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\\\\\"presets\\\\\": [\n" ], "file_path": "packages/babel-core/test/__snapshots__/option-manager.js.snap", "type": "replace", "edit_start_line_idx": 27 }
{ "validateLogs": true, "ignoreOutput": true, "presets": [ [ "env", { "debug": true, "targets": { "chrome": 52, "firefox": 50, "ie": 11 }, "useBuiltIns": "usage", "corejs": { "version": 3, "proposals": true } } ] ] }
packages/babel-preset-env/test/fixtures/debug-babel-7/usage-corejs3-proposals-1/options.json
0
https://github.com/babel/babel/commit/6df0b7c25f9e1b34cbf41229a784ade38bebde6a
[ 0.00016710819909349084, 0.00016562663950026035, 0.00016414506535511464, 0.00016562663950026035, 0.0000014815668691881 ]
{ "id": 3, "code_window": [ "\n", "exports[`option-manager config plugin/preset flattening and overriding should throw when an option is provided as a preset 1`] = `\n", "\"[BABEL] unknown: Unknown option: .useBuiltIns. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.\n", "- Maybe you meant to use\n", "\\\\\"preset\\\\\": [\n", " [\\\\\"./fixtures/option-manager/babel-preset-bar\\\\\", {\n", " \\\\\"useBuiltIns\\\\\": \\\\\"entry\\\\\"\n", "}]\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\\\\\"presets\\\\\": [\n" ], "file_path": "packages/babel-core/test/__snapshots__/option-manager.js.snap", "type": "replace", "edit_start_line_idx": 27 }
{ "type": "File", "start":0,"end":15,"loc":{"start":{"line":1,"column":0},"end":{"line":1,"column":15}}, "program": { "type": "Program", "start":0,"end":15,"loc":{"start":{"line":1,"column":0},"end":{"line":1,"column":15}}, "sourceType": "module", "interpreter": null, "body": [ { "type": "ExpressionStatement", "start":0,"end":15,"loc":{"start":{"line":1,"column":0},"end":{"line":1,"column":15}}, "expression": { "type": "BinaryExpression", "start":0,"end":14,"loc":{"start":{"line":1,"column":0},"end":{"line":1,"column":14}}, "left": { "type": "TSTypeAssertion", "start":0,"end":10,"loc":{"start":{"line":1,"column":0},"end":{"line":1,"column":10}}, "typeAnnotation": { "type": "TSNumberKeyword", "start":1,"end":7,"loc":{"start":{"line":1,"column":1},"end":{"line":1,"column":7}} }, "expression": { "type": "NumericLiteral", "start":9,"end":10,"loc":{"start":{"line":1,"column":9},"end":{"line":1,"column":10}}, "extra": { "rawValue": 1, "raw": "1" }, "value": 1 } }, "operator": "+", "right": { "type": "NumericLiteral", "start":13,"end":14,"loc":{"start":{"line":1,"column":13},"end":{"line":1,"column":14}}, "extra": { "rawValue": 1, "raw": "1" }, "value": 1 } } } ], "directives": [] } }
packages/babel-parser/test/fixtures/typescript/cast/type-assertion-before-operator/output.json
0
https://github.com/babel/babel/commit/6df0b7c25f9e1b34cbf41229a784ade38bebde6a
[ 0.00017098654643632472, 0.00016976914776023477, 0.00016741041326895356, 0.00016984794638119638, 0.0000012809665577151463 ]
{ "id": 3, "code_window": [ "\n", "exports[`option-manager config plugin/preset flattening and overriding should throw when an option is provided as a preset 1`] = `\n", "\"[BABEL] unknown: Unknown option: .useBuiltIns. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.\n", "- Maybe you meant to use\n", "\\\\\"preset\\\\\": [\n", " [\\\\\"./fixtures/option-manager/babel-preset-bar\\\\\", {\n", " \\\\\"useBuiltIns\\\\\": \\\\\"entry\\\\\"\n", "}]\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\\\\\"presets\\\\\": [\n" ], "file_path": "packages/babel-core/test/__snapshots__/option-manager.js.snap", "type": "replace", "edit_start_line_idx": 27 }
import {bar, baz} from "foo";
packages/babel-parser/test/fixtures/esprima/es2015-import-declaration/import-named-specifiers/input.js
0
https://github.com/babel/babel/commit/6df0b7c25f9e1b34cbf41229a784ade38bebde6a
[ 0.00016607044381089509, 0.00016607044381089509, 0.00016607044381089509, 0.00016607044381089509, 0 ]
{ "id": 0, "code_window": [ "\n", "export async function warmupViteServer (\n", " server: ViteDevServer,\n", " entries: string[]\n", ") {\n", " const warmedUrls = new Set<String>()\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " entries: string[],\n", " isServer: boolean\n" ], "file_path": "packages/vite/src/utils/warmup.ts", "type": "replace", "edit_start_line_idx": 5 }
import * as vite from 'vite' import { join } from 'pathe' import type { Nuxt } from '@nuxt/schema' import type { InlineConfig, SSROptions } from 'vite' import { logger, isIgnored } from '@nuxt/kit' import type { Options } from '@vitejs/plugin-vue' import replace from '@rollup/plugin-replace' import { sanitizeFilePath } from 'mlly' import { buildClient } from './client' import { buildServer } from './server' import virtual from './plugins/virtual' import { warmupViteServer } from './utils/warmup' import { resolveCSSOptions } from './css' import { composableKeysPlugin } from './plugins/composable-keys' export interface ViteOptions extends InlineConfig { vue?: Options ssr?: SSROptions devBundler?: 'vite-node' | 'legacy' } export interface ViteBuildContext { nuxt: Nuxt config: ViteOptions entry: string clientServer?: vite.ViteDevServer ssrServer?: vite.ViteDevServer } export async function bundle (nuxt: Nuxt) { const ctx: ViteBuildContext = { nuxt, entry: null!, config: vite.mergeConfig( { resolve: { alias: { ...nuxt.options.alias, '#app': nuxt.options.appDir, // We need this resolution to be present before the following entry, but it // will be filled in client/server configs '#build/plugins': '', '#build': nuxt.options.buildDir, 'web-streams-polyfill/ponyfill/es2018': 'unenv/runtime/mock/empty', // Cannot destructure property 'AbortController' of .. 'abort-controller': 'unenv/runtime/mock/empty' } }, optimizeDeps: { include: ['vue'] }, css: resolveCSSOptions(nuxt), build: { rollupOptions: { output: { sanitizeFileName: sanitizeFilePath } }, watch: { exclude: nuxt.options.ignore } }, plugins: [ composableKeysPlugin.vite({ sourcemap: nuxt.options.sourcemap, rootDir: nuxt.options.rootDir }), replace({ ...Object.fromEntries([';', '(', '{', '}', ' ', '\t', '\n'].map(d => [`${d}global.`, `${d}globalThis.`])), preventAssignment: true }), virtual(nuxt.vfs) ], vue: { reactivityTransform: nuxt.options.experimental.reactivityTransform }, server: { watch: { ignored: isIgnored }, fs: { allow: [ nuxt.options.appDir ] } } } as ViteOptions, nuxt.options.vite ) } // In build mode we explicitly override any vite options that vite is relying on // to detect whether to inject production or development code (such as HMR code) if (!nuxt.options.dev) { ctx.config.server!.watch = undefined ctx.config.build!.watch = undefined } await nuxt.callHook('vite:extend', ctx) nuxt.hook('vite:serverCreated', (server: vite.ViteDevServer, env) => { // Invalidate virtual modules when templates are re-generated ctx.nuxt.hook('app:templatesGenerated', () => { for (const [id, mod] of server.moduleGraph.idToModuleMap) { if (id.startsWith('virtual:')) { server.moduleGraph.invalidateModule(mod) } } }) if (nuxt.options.vite.warmupEntry !== false) { const start = Date.now() warmupViteServer(server, [join('/@fs/', ctx.entry)]) .then(() => logger.info(`Vite ${env.isClient ? 'client' : 'server'} warmed up in ${Date.now() - start}ms`)) .catch(logger.error) } }) await buildClient(ctx) await buildServer(ctx) }
packages/vite/src/vite.ts
1
https://github.com/nuxt/nuxt/commit/58c4753ed46ce96bc90f0c6b22431388b9c5ec02
[ 0.9992368221282959, 0.19856077432632446, 0.00016833737026900053, 0.002397787757217884, 0.36954644322395325 ]
{ "id": 0, "code_window": [ "\n", "export async function warmupViteServer (\n", " server: ViteDevServer,\n", " entries: string[]\n", ") {\n", " const warmedUrls = new Set<String>()\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " entries: string[],\n", " isServer: boolean\n" ], "file_path": "packages/vite/src/utils/warmup.ts", "type": "replace", "edit_start_line_idx": 5 }
<template> <div> <img src="~/assets/logo.svg" class="h-20 mb-4"> <img src="/public.svg" class="h-20 mb-4"> <img :src="logo" class="h-20 mb-4"> </div> </template> <script setup> import logo from '~/assets/logo.svg' </script> <style> #__nuxt { background-image: url('~/assets/logo.svg'); @font-face { src: url("/public.svg") format("woff2"); } } body { background-image: url('/public.svg'); @font-face { src: url('/public.svg') format('woff2'); } } </style>
test/fixtures/basic/pages/assets.vue
0
https://github.com/nuxt/nuxt/commit/58c4753ed46ce96bc90f0c6b22431388b9c5ec02
[ 0.00017672390094958246, 0.00017398658383172005, 0.00017083708371501416, 0.00017439876683056355, 0.000002420891860310803 ]
{ "id": 0, "code_window": [ "\n", "export async function warmupViteServer (\n", " server: ViteDevServer,\n", " entries: string[]\n", ") {\n", " const warmedUrls = new Set<String>()\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " entries: string[],\n", " isServer: boolean\n" ], "file_path": "packages/vite/src/utils/warmup.ts", "type": "replace", "edit_start_line_idx": 5 }
import { resolve } from 'pathe' import consola from 'consola' import { writeTypes } from '../utils/prepare' import { loadKit } from '../utils/kit' import { clearDir } from '../utils/fs' import { overrideEnv } from '../utils/env' import { defineNuxtCommand } from './index' export default defineNuxtCommand({ meta: { name: 'build', usage: 'npx nuxi build [--prerender] [rootDir]', description: 'Build nuxt for production deployment' }, async invoke (args) { overrideEnv('production') const rootDir = resolve(args._[0] || '.') const { loadNuxt, buildNuxt } = await loadKit(rootDir) const nuxt = await loadNuxt({ rootDir, overrides: { _generate: args.prerender } }) await clearDir(nuxt.options.buildDir) await writeTypes(nuxt) nuxt.hook('build:error', (err) => { consola.error('Nuxt Build Error:', err) process.exit(1) }) await buildNuxt(nuxt) } })
packages/nuxi/src/commands/build.ts
0
https://github.com/nuxt/nuxt/commit/58c4753ed46ce96bc90f0c6b22431388b9c5ec02
[ 0.00017594158998690546, 0.00017179129645228386, 0.00016651760961394757, 0.0001710993965389207, 0.0000032679085961717647 ]
{ "id": 0, "code_window": [ "\n", "export async function warmupViteServer (\n", " server: ViteDevServer,\n", " entries: string[]\n", ") {\n", " const warmedUrls = new Set<String>()\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " entries: string[],\n", " isServer: boolean\n" ], "file_path": "packages/vite/src/utils/warmup.ts", "type": "replace", "edit_start_line_idx": 5 }
export default defineNuxtPlugin(() => { addRouteMiddleware('global-test', () => { console.log('this global middleware was added in a plugin') }, { global: true }) addRouteMiddleware('named-test', () => { console.log('this named middleware was added in a plugin') }) })
examples/routing/middleware/plugins/add.ts
0
https://github.com/nuxt/nuxt/commit/58c4753ed46ce96bc90f0c6b22431388b9c5ec02
[ 0.0001701612927718088, 0.0001701612927718088, 0.0001701612927718088, 0.0001701612927718088, 0 ]
{ "id": 1, "code_window": [ " if (warmedUrls.has(url)) {\n", " return\n", " }\n", " warmedUrls.add(url)\n", " try {\n", " await server.transformRequest(url)\n", " } catch (e) {\n", " logger.debug('Warmup for %s failed with: %s', url, e)\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " await server.transformRequest(url, { ssr: isServer })\n" ], "file_path": "packages/vite/src/utils/warmup.ts", "type": "replace", "edit_start_line_idx": 15 }
import { logger } from '@nuxt/kit' import type { ViteDevServer } from 'vite' export async function warmupViteServer ( server: ViteDevServer, entries: string[] ) { const warmedUrls = new Set<String>() const warmup = async (url: string) => { if (warmedUrls.has(url)) { return } warmedUrls.add(url) try { await server.transformRequest(url) } catch (e) { logger.debug('Warmup for %s failed with: %s', url, e) } const mod = await server.moduleGraph.getModuleByUrl(url) const deps = Array.from(mod?.importedModules || []) await Promise.all(deps.map(m => warmup(m.url.replace('/@id/__x00__', '\0')))) } await Promise.all(entries.map(entry => warmup(entry))) }
packages/vite/src/utils/warmup.ts
1
https://github.com/nuxt/nuxt/commit/58c4753ed46ce96bc90f0c6b22431388b9c5ec02
[ 0.9978362917900085, 0.34292319416999817, 0.0025189907755702734, 0.02841431275010109, 0.46321412920951843 ]
{ "id": 1, "code_window": [ " if (warmedUrls.has(url)) {\n", " return\n", " }\n", " warmedUrls.add(url)\n", " try {\n", " await server.transformRequest(url)\n", " } catch (e) {\n", " logger.debug('Warmup for %s failed with: %s', url, e)\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " await server.transformRequest(url, { ssr: isServer })\n" ], "file_path": "packages/vite/src/utils/warmup.ts", "type": "replace", "edit_start_line_idx": 15 }
import { defineNuxtConfig } from 'nuxt' export default defineNuxtConfig({ modules: [ '@nuxt/ui' ] })
examples/routing/layouts/nuxt.config.ts
0
https://github.com/nuxt/nuxt/commit/58c4753ed46ce96bc90f0c6b22431388b9c5ec02
[ 0.00017290130199398845, 0.00017290130199398845, 0.00017290130199398845, 0.00017290130199398845, 0 ]
{ "id": 1, "code_window": [ " if (warmedUrls.has(url)) {\n", " return\n", " }\n", " warmedUrls.add(url)\n", " try {\n", " await server.transformRequest(url)\n", " } catch (e) {\n", " logger.debug('Warmup for %s failed with: %s', url, e)\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " await server.transformRequest(url, { ssr: isServer })\n" ], "file_path": "packages/vite/src/utils/warmup.ts", "type": "replace", "edit_start_line_idx": 15 }
import consola from 'consola' import buildCommand from './build' import { defineNuxtCommand } from './index' export default defineNuxtCommand({ meta: { name: 'generate', usage: 'npx nuxi generate [rootDir]', description: 'Build Nuxt and prerender static routes' }, async invoke (args) { args.prerender = true await buildCommand.invoke(args) consola.success('You can now deploy `.output/public` to any static hosting!') } })
packages/nuxi/src/commands/generate.ts
0
https://github.com/nuxt/nuxt/commit/58c4753ed46ce96bc90f0c6b22431388b9c5ec02
[ 0.00017490102618467063, 0.00017344126536045223, 0.00017198150453623384, 0.00017344126536045223, 0.0000014597608242183924 ]
{ "id": 1, "code_window": [ " if (warmedUrls.has(url)) {\n", " return\n", " }\n", " warmedUrls.add(url)\n", " try {\n", " await server.transformRequest(url)\n", " } catch (e) {\n", " logger.debug('Warmup for %s failed with: %s', url, e)\n", " }\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " await server.transformRequest(url, { ssr: isServer })\n" ], "file_path": "packages/vite/src/utils/warmup.ts", "type": "replace", "edit_start_line_idx": 15 }
<template> <div class="overflow-hidden relative mx-auto max-w-8xl"> <HeroParallax /> <div class="flex flex-wrap justify-center py-0 section"> <section class="flex flex-col justify-start w-full px-4 pt-36 pb-52 md:pt-40 lg:pb-56 lg:pt-48 text-center"> <div> <span class="nuxt-text-highlight">Currently in public beta</span> </div> <h1 class="font-normal font-serif text-display-5 xs:text-display-4 md:text-display-3 2xl:text-display-2 my-8"> <Markdown use="title" unwrap="p" /> </h1> <h2 class=" font-normal text-body-base xs:text-body-lg md:text-body-xl 2xl:text-body-2xl px-8 sm:px-0 text-secondary-dark dark:text-cloud-lighter " > <Markdown use="description" unwrap="p" /> </h2> <p class="text-center mt-2 text-secondary-dark dark:text-cloud-lighter"> <Markdown use="body" unwrap="p" /> </p> </section> </div> </div> </template>
docs/components/molecules/HeroSection.vue
0
https://github.com/nuxt/nuxt/commit/58c4753ed46ce96bc90f0c6b22431388b9c5ec02
[ 0.00017509792814962566, 0.00017314477008767426, 0.00017124219448305666, 0.0001731194934109226, 0.0000017297003296334879 ]
{ "id": 2, "code_window": [ " }\n", " })\n", "\n", " if (nuxt.options.vite.warmupEntry !== false) {\n", " const start = Date.now()\n", " warmupViteServer(server, [join('/@fs/', ctx.entry)])\n", " .then(() => logger.info(`Vite ${env.isClient ? 'client' : 'server'} warmed up in ${Date.now() - start}ms`))\n", " .catch(logger.error)\n", " }\n", " })\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " warmupViteServer(server, [join('/@fs/', ctx.entry)], env.isServer)\n" ], "file_path": "packages/vite/src/vite.ts", "type": "replace", "edit_start_line_idx": 105 }
import { logger } from '@nuxt/kit' import type { ViteDevServer } from 'vite' export async function warmupViteServer ( server: ViteDevServer, entries: string[] ) { const warmedUrls = new Set<String>() const warmup = async (url: string) => { if (warmedUrls.has(url)) { return } warmedUrls.add(url) try { await server.transformRequest(url) } catch (e) { logger.debug('Warmup for %s failed with: %s', url, e) } const mod = await server.moduleGraph.getModuleByUrl(url) const deps = Array.from(mod?.importedModules || []) await Promise.all(deps.map(m => warmup(m.url.replace('/@id/__x00__', '\0')))) } await Promise.all(entries.map(entry => warmup(entry))) }
packages/vite/src/utils/warmup.ts
1
https://github.com/nuxt/nuxt/commit/58c4753ed46ce96bc90f0c6b22431388b9c5ec02
[ 0.0015652665169909596, 0.000804184062872082, 0.0003089651290792972, 0.0005383205716498196, 0.0005462513654492795 ]
{ "id": 2, "code_window": [ " }\n", " })\n", "\n", " if (nuxt.options.vite.warmupEntry !== false) {\n", " const start = Date.now()\n", " warmupViteServer(server, [join('/@fs/', ctx.entry)])\n", " .then(() => logger.info(`Vite ${env.isClient ? 'client' : 'server'} warmed up in ${Date.now() - start}ms`))\n", " .catch(logger.error)\n", " }\n", " })\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " warmupViteServer(server, [join('/@fs/', ctx.entry)], env.isServer)\n" ], "file_path": "packages/vite/src/vite.ts", "type": "replace", "edit_start_line_idx": 105 }
import { CreateOptions } from '#app' const entry = process.server ? (ctx?: CreateOptions['ssrContext']) => import('#app/entry').then(m => m.default(ctx)) : () => import('#app/entry').then(m => m.default) if (process.client) { entry() } export default entry
packages/nuxt/src/app/entry.async.ts
0
https://github.com/nuxt/nuxt/commit/58c4753ed46ce96bc90f0c6b22431388b9c5ec02
[ 0.00028368178755044937, 0.00022584194084629416, 0.00016800207959022373, 0.00022584194084629416, 0.00005783985398011282 ]
{ "id": 2, "code_window": [ " }\n", " })\n", "\n", " if (nuxt.options.vite.warmupEntry !== false) {\n", " const start = Date.now()\n", " warmupViteServer(server, [join('/@fs/', ctx.entry)])\n", " .then(() => logger.info(`Vite ${env.isClient ? 'client' : 'server'} warmed up in ${Date.now() - start}ms`))\n", " .catch(logger.error)\n", " }\n", " })\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " warmupViteServer(server, [join('/@fs/', ctx.entry)], env.isServer)\n" ], "file_path": "packages/vite/src/vite.ts", "type": "replace", "edit_start_line_idx": 105 }
<template> <NuxtLayout> <NuxtPage /> </NuxtLayout> </template>
packages/nuxt/src/pages/runtime/app.vue
0
https://github.com/nuxt/nuxt/commit/58c4753ed46ce96bc90f0c6b22431388b9c5ec02
[ 0.00017474847845733166, 0.00017474847845733166, 0.00017474847845733166, 0.00017474847845733166, 0 ]
{ "id": 2, "code_window": [ " }\n", " })\n", "\n", " if (nuxt.options.vite.warmupEntry !== false) {\n", " const start = Date.now()\n", " warmupViteServer(server, [join('/@fs/', ctx.entry)])\n", " .then(() => logger.info(`Vite ${env.isClient ? 'client' : 'server'} warmed up in ${Date.now() - start}ms`))\n", " .catch(logger.error)\n", " }\n", " })\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " warmupViteServer(server, [join('/@fs/', ctx.entry)], env.isServer)\n" ], "file_path": "packages/vite/src/vite.ts", "type": "replace", "edit_start_line_idx": 105 }
# `setResponseStatus` Nuxt provides composables and utilities for first-class server-side-rendering support. You can use `setResponseStatus` to set the statusCode (and optionally the statusMessage) of the response. `setResponseStatus` can only be called within component setup functions, plugins, and route middleware. ```js // Set the status code to 404 for a custom 404 page setResponseStatus(404) // Set the status message as well setResponseStatus(404, 'Page Not Found') ``` ::alert{icon=👉} In the browser, `setResponseStatus` will have no effect. ::
docs/content/3.api/1.composables/set-response-status.md
0
https://github.com/nuxt/nuxt/commit/58c4753ed46ce96bc90f0c6b22431388b9c5ec02
[ 0.00016997447528410703, 0.0001674336672294885, 0.00016489287372678518, 0.0001674336672294885, 0.0000025408007786609232 ]
{ "id": 0, "code_window": [ " annotationPermissionUpdate?: boolean;\n", " extractFieldsNameDeduplication?: boolean;\n", " dashboardSceneForViewers?: boolean;\n", " panelFilterVariable?: boolean;\n", "}" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " pdfTables?: boolean;\n" ], "file_path": "packages/grafana-data/src/types/featureToggles.gen.ts", "type": "add", "edit_start_line_idx": 161 }
// NOTE: This file was auto generated. DO NOT EDIT DIRECTLY! // To change feature flags, edit: // pkg/services/featuremgmt/registry.go // Then run tests in: // pkg/services/featuremgmt/toggles_gen_test.go package featuremgmt const ( // FlagDisableEnvelopeEncryption // Disable envelope encryption (emergency only) FlagDisableEnvelopeEncryption = "disableEnvelopeEncryption" // FlagLiveServiceWebWorker // This will use a webworker thread to processes events rather than the main thread FlagLiveServiceWebWorker = "live-service-web-worker" // FlagQueryOverLive // Use Grafana Live WebSocket to execute backend queries FlagQueryOverLive = "queryOverLive" // FlagPanelTitleSearch // Search for dashboards using panel title FlagPanelTitleSearch = "panelTitleSearch" // FlagPublicDashboards // Enables public access to dashboards FlagPublicDashboards = "publicDashboards" // FlagPublicDashboardsEmailSharing // Enables public dashboard sharing to be restricted to only allowed emails FlagPublicDashboardsEmailSharing = "publicDashboardsEmailSharing" // FlagLokiExperimentalStreaming // Support new streaming approach for loki (prototype, needs special loki build) FlagLokiExperimentalStreaming = "lokiExperimentalStreaming" // FlagFeatureHighlights // Highlight Grafana Enterprise features FlagFeatureHighlights = "featureHighlights" // FlagMigrationLocking // Lock database during migrations FlagMigrationLocking = "migrationLocking" // FlagStorage // Configurable storage for dashboards, datasources, and resources FlagStorage = "storage" // FlagCorrelations // Correlations page FlagCorrelations = "correlations" // FlagExploreContentOutline // Content outline sidebar FlagExploreContentOutline = "exploreContentOutline" // FlagDatasourceQueryMultiStatus // Introduce HTTP 207 Multi Status for api/ds/query FlagDatasourceQueryMultiStatus = "datasourceQueryMultiStatus" // FlagTraceToMetrics // Enable trace to metrics links FlagTraceToMetrics = "traceToMetrics" // FlagNewDBLibrary // Use jmoiron/sqlx rather than xorm for a few backend services FlagNewDBLibrary = "newDBLibrary" // FlagAutoMigrateOldPanels // Migrate old angular panels to supported versions (graph, table-old, worldmap, etc) FlagAutoMigrateOldPanels = "autoMigrateOldPanels" // FlagDisableAngular // Dynamic flag to disable angular at runtime. The preferred method is to set `angular_support_enabled` to `false` in the [security] settings, which allows you to change the state at runtime. FlagDisableAngular = "disableAngular" // FlagCanvasPanelNesting // Allow elements nesting FlagCanvasPanelNesting = "canvasPanelNesting" // FlagScenes // Experimental framework to build interactive dashboards FlagScenes = "scenes" // FlagDisableSecretsCompatibility // Disable duplicated secret storage in legacy tables FlagDisableSecretsCompatibility = "disableSecretsCompatibility" // FlagLogRequestsInstrumentedAsUnknown // Logs the path for requests that are instrumented as unknown FlagLogRequestsInstrumentedAsUnknown = "logRequestsInstrumentedAsUnknown" // FlagDataConnectionsConsole // Enables a new top-level page called Connections. This page is an experiment that provides a better experience when you install and configure data sources and other plugins. FlagDataConnectionsConsole = "dataConnectionsConsole" // FlagTopnav // Enables topnav support in external plugins. The new Grafana navigation cannot be disabled. FlagTopnav = "topnav" // FlagDockedMegaMenu // Enable support for a persistent (docked) navigation menu FlagDockedMegaMenu = "dockedMegaMenu" // FlagGrpcServer // Run the GRPC server FlagGrpcServer = "grpcServer" // FlagEntityStore // SQL-based entity store (requires storage flag also) FlagEntityStore = "entityStore" // FlagCloudWatchCrossAccountQuerying // Enables cross-account querying in CloudWatch datasources FlagCloudWatchCrossAccountQuerying = "cloudWatchCrossAccountQuerying" // FlagRedshiftAsyncQueryDataSupport // Enable async query data support for Redshift FlagRedshiftAsyncQueryDataSupport = "redshiftAsyncQueryDataSupport" // FlagAthenaAsyncQueryDataSupport // Enable async query data support for Athena FlagAthenaAsyncQueryDataSupport = "athenaAsyncQueryDataSupport" // FlagCloudwatchNewRegionsHandler // Refactor of /regions endpoint, no user-facing changes FlagCloudwatchNewRegionsHandler = "cloudwatchNewRegionsHandler" // FlagShowDashboardValidationWarnings // Show warnings when dashboards do not validate against the schema FlagShowDashboardValidationWarnings = "showDashboardValidationWarnings" // FlagMysqlAnsiQuotes // Use double quotes to escape keyword in a MySQL query FlagMysqlAnsiQuotes = "mysqlAnsiQuotes" // FlagAccessControlOnCall // Access control primitives for OnCall FlagAccessControlOnCall = "accessControlOnCall" // FlagNestedFolders // Enable folder nesting FlagNestedFolders = "nestedFolders" // FlagNestedFolderPicker // Enables the new folder picker to work with nested folders. Requires the nestedFolders feature toggle FlagNestedFolderPicker = "nestedFolderPicker" // FlagAccessTokenExpirationCheck // Enable OAuth access_token expiration check and token refresh using the refresh_token FlagAccessTokenExpirationCheck = "accessTokenExpirationCheck" // FlagEmptyDashboardPage // Enable the redesigned user interface of a dashboard page that includes no panels FlagEmptyDashboardPage = "emptyDashboardPage" // FlagDisablePrometheusExemplarSampling // Disable Prometheus exemplar sampling FlagDisablePrometheusExemplarSampling = "disablePrometheusExemplarSampling" // FlagAlertingBacktesting // Rule backtesting API for alerting FlagAlertingBacktesting = "alertingBacktesting" // FlagEditPanelCSVDragAndDrop // Enables drag and drop for CSV and Excel files FlagEditPanelCSVDragAndDrop = "editPanelCSVDragAndDrop" // FlagAlertingNoNormalState // Stop maintaining state of alerts that are not firing FlagAlertingNoNormalState = "alertingNoNormalState" // FlagLogsContextDatasourceUi // Allow datasource to provide custom UI for context view FlagLogsContextDatasourceUi = "logsContextDatasourceUi" // FlagLokiQuerySplitting // Split large interval queries into subqueries with smaller time intervals FlagLokiQuerySplitting = "lokiQuerySplitting" // FlagLokiQuerySplittingConfig // Give users the option to configure split durations for Loki queries FlagLokiQuerySplittingConfig = "lokiQuerySplittingConfig" // FlagIndividualCookiePreferences // Support overriding cookie preferences per user FlagIndividualCookiePreferences = "individualCookiePreferences" // FlagGcomOnlyExternalOrgRoleSync // Prohibits a user from changing organization roles synced with Grafana Cloud auth provider FlagGcomOnlyExternalOrgRoleSync = "gcomOnlyExternalOrgRoleSync" // FlagPrometheusMetricEncyclopedia // Adds the metrics explorer component to the Prometheus query builder as an option in metric select FlagPrometheusMetricEncyclopedia = "prometheusMetricEncyclopedia" // FlagInfluxdbBackendMigration // Query InfluxDB InfluxQL without the proxy FlagInfluxdbBackendMigration = "influxdbBackendMigration" // FlagClientTokenRotation // Replaces the current in-request token rotation so that the client initiates the rotation FlagClientTokenRotation = "clientTokenRotation" // FlagPrometheusDataplane // Changes responses to from Prometheus to be compliant with the dataplane specification. In particular, when this feature toggle is active, the numeric `Field.Name` is set from &#39;Value&#39; to the value of the `__name__` label. FlagPrometheusDataplane = "prometheusDataplane" // FlagLokiMetricDataplane // Changes metric responses from Loki to be compliant with the dataplane specification. FlagLokiMetricDataplane = "lokiMetricDataplane" // FlagLokiLogsDataplane // Changes logs responses from Loki to be compliant with the dataplane specification. FlagLokiLogsDataplane = "lokiLogsDataplane" // FlagDataplaneFrontendFallback // Support dataplane contract field name change for transformations and field name matchers where the name is different FlagDataplaneFrontendFallback = "dataplaneFrontendFallback" // FlagDisableSSEDataplane // Disables dataplane specific processing in server side expressions. FlagDisableSSEDataplane = "disableSSEDataplane" // FlagAlertStateHistoryLokiSecondary // Enable Grafana to write alert state history to an external Loki instance in addition to Grafana annotations. FlagAlertStateHistoryLokiSecondary = "alertStateHistoryLokiSecondary" // FlagAlertingNotificationsPoliciesMatchingInstances // Enables the preview of matching instances for notification policies FlagAlertingNotificationsPoliciesMatchingInstances = "alertingNotificationsPoliciesMatchingInstances" // FlagAlertStateHistoryLokiPrimary // Enable a remote Loki instance as the primary source for state history reads. FlagAlertStateHistoryLokiPrimary = "alertStateHistoryLokiPrimary" // FlagAlertStateHistoryLokiOnly // Disable Grafana alerts from emitting annotations when a remote Loki instance is available. FlagAlertStateHistoryLokiOnly = "alertStateHistoryLokiOnly" // FlagUnifiedRequestLog // Writes error logs to the request logger FlagUnifiedRequestLog = "unifiedRequestLog" // FlagRenderAuthJWT // Uses JWT-based auth for rendering instead of relying on remote cache FlagRenderAuthJWT = "renderAuthJWT" // FlagExternalServiceAuth // Starts an OAuth2 authentication provider for external services FlagExternalServiceAuth = "externalServiceAuth" // FlagRefactorVariablesTimeRange // Refactor time range variables flow to reduce number of API calls made when query variables are chained FlagRefactorVariablesTimeRange = "refactorVariablesTimeRange" // FlagUseCachingService // When active, the new query and resource caching implementation using a wire service inject replaces the previous middleware implementation. FlagUseCachingService = "useCachingService" // FlagEnableElasticsearchBackendQuerying // Enable the processing of queries and responses in the Elasticsearch data source through backend FlagEnableElasticsearchBackendQuerying = "enableElasticsearchBackendQuerying" // FlagAdvancedDataSourcePicker // Enable a new data source picker with contextual information, recently used order and advanced mode FlagAdvancedDataSourcePicker = "advancedDataSourcePicker" // FlagFaroDatasourceSelector // Enable the data source selector within the Frontend Apps section of the Frontend Observability FlagFaroDatasourceSelector = "faroDatasourceSelector" // FlagEnableDatagridEditing // Enables the edit functionality in the datagrid panel FlagEnableDatagridEditing = "enableDatagridEditing" // FlagDataSourcePageHeader // Apply new pageHeader UI in data source edit page FlagDataSourcePageHeader = "dataSourcePageHeader" // FlagExtraThemes // Enables extra themes FlagExtraThemes = "extraThemes" // FlagLokiPredefinedOperations // Adds predefined query operations to Loki query editor FlagLokiPredefinedOperations = "lokiPredefinedOperations" // FlagPluginsFrontendSandbox // Enables the plugins frontend sandbox FlagPluginsFrontendSandbox = "pluginsFrontendSandbox" // FlagDashboardEmbed // Allow embedding dashboard for external use in Code editors FlagDashboardEmbed = "dashboardEmbed" // FlagFrontendSandboxMonitorOnly // Enables monitor only in the plugin frontend sandbox (if enabled) FlagFrontendSandboxMonitorOnly = "frontendSandboxMonitorOnly" // FlagSqlDatasourceDatabaseSelection // Enables previous SQL data source dataset dropdown behavior FlagSqlDatasourceDatabaseSelection = "sqlDatasourceDatabaseSelection" // FlagLokiFormatQuery // Enables the ability to format Loki queries FlagLokiFormatQuery = "lokiFormatQuery" // FlagCloudWatchLogsMonacoEditor // Enables the Monaco editor for CloudWatch Logs queries FlagCloudWatchLogsMonacoEditor = "cloudWatchLogsMonacoEditor" // FlagExploreScrollableLogsContainer // Improves the scrolling behavior of logs in Explore FlagExploreScrollableLogsContainer = "exploreScrollableLogsContainer" // FlagRecordedQueriesMulti // Enables writing multiple items from a single query within Recorded Queries FlagRecordedQueriesMulti = "recordedQueriesMulti" // FlagPluginsDynamicAngularDetectionPatterns // Enables fetching Angular detection patterns for plugins from GCOM and fallback to hardcoded ones FlagPluginsDynamicAngularDetectionPatterns = "pluginsDynamicAngularDetectionPatterns" // FlagVizAndWidgetSplit // Split panels between visualizations and widgets FlagVizAndWidgetSplit = "vizAndWidgetSplit" // FlagPrometheusIncrementalQueryInstrumentation // Adds RudderStack events to incremental queries FlagPrometheusIncrementalQueryInstrumentation = "prometheusIncrementalQueryInstrumentation" // FlagLogsExploreTableVisualisation // A table visualisation for logs in Explore FlagLogsExploreTableVisualisation = "logsExploreTableVisualisation" // FlagAwsDatasourcesTempCredentials // Support temporary security credentials in AWS plugins for Grafana Cloud customers FlagAwsDatasourcesTempCredentials = "awsDatasourcesTempCredentials" // FlagTransformationsRedesign // Enables the transformations redesign FlagTransformationsRedesign = "transformationsRedesign" // FlagMlExpressions // Enable support for Machine Learning in server-side expressions FlagMlExpressions = "mlExpressions" // FlagTraceQLStreaming // Enables response streaming of TraceQL queries of the Tempo data source FlagTraceQLStreaming = "traceQLStreaming" // FlagMetricsSummary // Enables metrics summary queries in the Tempo data source FlagMetricsSummary = "metricsSummary" // FlagGrafanaAPIServer // Enable Kubernetes API Server for Grafana resources FlagGrafanaAPIServer = "grafanaAPIServer" // FlagGrafanaAPIServerWithExperimentalAPIs // Register experimental APIs with the k8s API server FlagGrafanaAPIServerWithExperimentalAPIs = "grafanaAPIServerWithExperimentalAPIs" // FlagFeatureToggleAdminPage // Enable admin page for managing feature toggles from the Grafana front-end FlagFeatureToggleAdminPage = "featureToggleAdminPage" // FlagAwsAsyncQueryCaching // Enable caching for async queries for Redshift and Athena. Requires that the `useCachingService` feature toggle is enabled and the datasource has caching and async query support enabled FlagAwsAsyncQueryCaching = "awsAsyncQueryCaching" // FlagSplitScopes // Support faster dashboard and folder search by splitting permission scopes into parts FlagSplitScopes = "splitScopes" // FlagAzureMonitorDataplane // Adds dataplane compliant frame metadata in the Azure Monitor datasource FlagAzureMonitorDataplane = "azureMonitorDataplane" // FlagTraceToProfiles // Enables linking between traces and profiles FlagTraceToProfiles = "traceToProfiles" // FlagPermissionsFilterRemoveSubquery // Alternative permission filter implementation that does not use subqueries for fetching the dashboard folder FlagPermissionsFilterRemoveSubquery = "permissionsFilterRemoveSubquery" // FlagPrometheusConfigOverhaulAuth // Update the Prometheus configuration page with the new auth component FlagPrometheusConfigOverhaulAuth = "prometheusConfigOverhaulAuth" // FlagConfigurableSchedulerTick // Enable changing the scheduler base interval via configuration option unified_alerting.scheduler_tick_interval FlagConfigurableSchedulerTick = "configurableSchedulerTick" // FlagInfluxdbSqlSupport // Enable InfluxDB SQL query language support with new querying UI FlagInfluxdbSqlSupport = "influxdbSqlSupport" // FlagAlertingNoDataErrorExecution // Changes how Alerting state manager handles execution of NoData/Error FlagAlertingNoDataErrorExecution = "alertingNoDataErrorExecution" // FlagAngularDeprecationUI // Display new Angular deprecation-related UI features FlagAngularDeprecationUI = "angularDeprecationUI" // FlagDashgpt // Enable AI powered features in dashboards FlagDashgpt = "dashgpt" // FlagReportingRetries // Enables rendering retries for the reporting feature FlagReportingRetries = "reportingRetries" // FlagNewBrowseDashboards // New browse/manage dashboards UI FlagNewBrowseDashboards = "newBrowseDashboards" // FlagSseGroupByDatasource // Send query to the same datasource in a single request when using server side expressions FlagSseGroupByDatasource = "sseGroupByDatasource" // FlagRequestInstrumentationStatusSource // Include a status source label for request metrics and logs FlagRequestInstrumentationStatusSource = "requestInstrumentationStatusSource" // FlagLibraryPanelRBAC // Enables RBAC support for library panels FlagLibraryPanelRBAC = "libraryPanelRBAC" // FlagLokiRunQueriesInParallel // Enables running Loki queries in parallel FlagLokiRunQueriesInParallel = "lokiRunQueriesInParallel" // FlagWargamesTesting // Placeholder feature flag for internal testing FlagWargamesTesting = "wargamesTesting" // FlagAlertingInsights // Show the new alerting insights landing page FlagAlertingInsights = "alertingInsights" // FlagAlertingContactPointsV2 // Show the new contacpoints list view FlagAlertingContactPointsV2 = "alertingContactPointsV2" // FlagExternalCorePlugins // Allow core plugins to be loaded as external FlagExternalCorePlugins = "externalCorePlugins" // FlagPluginsAPIMetrics // Sends metrics of public grafana packages usage by plugins FlagPluginsAPIMetrics = "pluginsAPIMetrics" // FlagHttpSLOLevels // Adds SLO level to http request metrics FlagHttpSLOLevels = "httpSLOLevels" // FlagIdForwarding // Generate signed id token for identity that can be forwarded to plugins and external services FlagIdForwarding = "idForwarding" // FlagCloudWatchWildCardDimensionValues // Fetches dimension values from CloudWatch to correctly label wildcard dimensions FlagCloudWatchWildCardDimensionValues = "cloudWatchWildCardDimensionValues" // FlagExternalServiceAccounts // Automatic service account and token setup for plugins FlagExternalServiceAccounts = "externalServiceAccounts" // FlagPanelMonitoring // Enables panel monitoring through logs and measurements FlagPanelMonitoring = "panelMonitoring" // FlagEnableNativeHTTPHistogram // Enables native HTTP Histograms FlagEnableNativeHTTPHistogram = "enableNativeHTTPHistogram" // FlagFormatString // Enable format string transformer FlagFormatString = "formatString" // FlagTransformationsVariableSupport // Allows using variables in transformations FlagTransformationsVariableSupport = "transformationsVariableSupport" // FlagKubernetesPlaylists // Use the kubernetes API in the frontend for playlists FlagKubernetesPlaylists = "kubernetesPlaylists" // FlagKubernetesPlaylistsAPI // Route /api/playlist API to k8s handlers FlagKubernetesPlaylistsAPI = "kubernetesPlaylistsAPI" // FlagCloudWatchBatchQueries // Runs CloudWatch metrics queries as separate batches FlagCloudWatchBatchQueries = "cloudWatchBatchQueries" // FlagNavAdminSubsections // Splits the administration section of the nav tree into subsections FlagNavAdminSubsections = "navAdminSubsections" // FlagRecoveryThreshold // Enables feature recovery threshold (aka hysteresis) for threshold server-side expression FlagRecoveryThreshold = "recoveryThreshold" // FlagTeamHttpHeaders // Enables datasources to apply team headers to the client requests FlagTeamHttpHeaders = "teamHttpHeaders" // FlagAwsDatasourcesNewFormStyling // Applies new form styling for configuration and query editors in AWS plugins FlagAwsDatasourcesNewFormStyling = "awsDatasourcesNewFormStyling" // FlagCachingOptimizeSerializationMemoryUsage // If enabled, the caching backend gradually serializes query responses for the cache, comparing against the configured `[caching]max_value_mb` value as it goes. This can can help prevent Grafana from running out of memory while attempting to cache very large query responses. FlagCachingOptimizeSerializationMemoryUsage = "cachingOptimizeSerializationMemoryUsage" // FlagPanelTitleSearchInV1 // Enable searching for dashboards using panel title in search v1 FlagPanelTitleSearchInV1 = "panelTitleSearchInV1" // FlagPluginsInstrumentationStatusSource // Include a status source label for plugin request metrics and logs FlagPluginsInstrumentationStatusSource = "pluginsInstrumentationStatusSource" // FlagCostManagementUi // Toggles the display of the cost management ui plugin FlagCostManagementUi = "costManagementUi" // FlagManagedPluginsInstall // Install managed plugins directly from plugins catalog FlagManagedPluginsInstall = "managedPluginsInstall" // FlagPrometheusPromQAIL // Prometheus and AI/ML to assist users in creating a query FlagPrometheusPromQAIL = "prometheusPromQAIL" // FlagAddFieldFromCalculationStatFunctions // Add cumulative and window functions to the add field from calculation transformation FlagAddFieldFromCalculationStatFunctions = "addFieldFromCalculationStatFunctions" // FlagAlertmanagerRemoteSecondary // Enable Grafana to sync configuration and state with a remote Alertmanager. FlagAlertmanagerRemoteSecondary = "alertmanagerRemoteSecondary" // FlagAlertmanagerRemotePrimary // Enable Grafana to have a remote Alertmanager instance as the primary Alertmanager. FlagAlertmanagerRemotePrimary = "alertmanagerRemotePrimary" // FlagAlertmanagerRemoteOnly // Disable the internal Alertmanager and only use the external one defined. FlagAlertmanagerRemoteOnly = "alertmanagerRemoteOnly" // FlagAnnotationPermissionUpdate // Separate annotation permissions from dashboard permissions to allow for more granular control. FlagAnnotationPermissionUpdate = "annotationPermissionUpdate" // FlagExtractFieldsNameDeduplication // Make sure extracted field names are unique in the dataframe FlagExtractFieldsNameDeduplication = "extractFieldsNameDeduplication" // FlagDashboardSceneForViewers // Enables dashboard rendering using Scenes for viewer roles FlagDashboardSceneForViewers = "dashboardSceneForViewers" // FlagPanelFilterVariable // Enables use of the `systemPanelFilterVar` variable to filter panels in a dashboard FlagPanelFilterVariable = "panelFilterVariable" )
pkg/services/featuremgmt/toggles_gen.go
1
https://github.com/grafana/grafana/commit/95b48339f89c7d267bce7d894404d26ccd75d0e3
[ 0.9990211725234985, 0.04881160706281662, 0.0001661572459852323, 0.00017053267220035195, 0.20860496163368225 ]
{ "id": 0, "code_window": [ " annotationPermissionUpdate?: boolean;\n", " extractFieldsNameDeduplication?: boolean;\n", " dashboardSceneForViewers?: boolean;\n", " panelFilterVariable?: boolean;\n", "}" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " pdfTables?: boolean;\n" ], "file_path": "packages/grafana-data/src/types/featureToggles.gen.ts", "type": "add", "edit_start_line_idx": 161 }
package frontend import ( "encoding/json" "flag" "os" "testing" "github.com/grafana/grafana/pkg/build/config" "github.com/stretchr/testify/require" "github.com/urfave/cli/v2" ) const ( jobs = "jobs" githubToken = "github-token" buildID = "build-id" ) type packageJson struct { Version string `json:"version"` } type flagObj struct { name string value string } var app = cli.NewApp() func TestGetConfig(t *testing.T) { tests := []struct { ctx *cli.Context name string packageJsonVersion string metadata config.Metadata wantErr bool }{ { ctx: cli.NewContext(app, setFlags(t, flag.NewFlagSet("flagSet", flag.ContinueOnError), flagObj{name: jobs, value: "2"}, flagObj{name: githubToken, value: "token"}), nil), name: "package.json matches tag", packageJsonVersion: "10.0.0", metadata: config.Metadata{GrafanaVersion: "10.0.0", ReleaseMode: config.ReleaseMode{Mode: config.TagMode}}, wantErr: false, }, { ctx: cli.NewContext(app, setFlags(t, flag.NewFlagSet("flagSet", flag.ContinueOnError), flagObj{name: jobs, value: "2"}, flagObj{name: githubToken, value: "token"}), nil), name: "custom tag, package.json doesn't match", packageJsonVersion: "10.0.0", metadata: config.Metadata{GrafanaVersion: "10.0.0-abcd123pre", ReleaseMode: config.ReleaseMode{Mode: config.TagMode}}, wantErr: false, }, { ctx: cli.NewContext(app, setFlags(t, flag.NewFlagSet("flagSet", flag.ContinueOnError), flagObj{name: jobs, value: "2"}, flagObj{name: githubToken, value: "token"}), nil), name: "package.json doesn't match tag", packageJsonVersion: "10.1.0", metadata: config.Metadata{GrafanaVersion: "10.0.0", ReleaseMode: config.ReleaseMode{Mode: config.TagMode}}, wantErr: true, }, { ctx: cli.NewContext(app, setFlags(t, flag.NewFlagSet("flagSet", flag.ContinueOnError), flagObj{name: jobs, value: "2"}, flagObj{name: githubToken, value: "token"}), nil), name: "test tag event, check should be skipped", packageJsonVersion: "10.1.0", metadata: config.Metadata{GrafanaVersion: "10.1.0-test", ReleaseMode: config.ReleaseMode{Mode: config.TagMode, IsTest: true}}, wantErr: false, }, { ctx: cli.NewContext(app, setFlags(t, flag.NewFlagSet("flagSet", flag.ContinueOnError), flagObj{name: jobs, value: "2"}, flagObj{name: githubToken, value: "token"}, flagObj{name: buildID, value: "12345"}), nil), name: "non-tag event", packageJsonVersion: "10.1.0-pre", metadata: config.Metadata{GrafanaVersion: "10.1.0-12345pre", ReleaseMode: config.ReleaseMode{Mode: config.PullRequestMode}}, wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := createTempPackageJson(t, tt.packageJsonVersion) require.NoError(t, err) got, _, err := GetConfig(tt.ctx, tt.metadata) if !tt.wantErr { require.Equal(t, got.PackageVersion, tt.metadata.GrafanaVersion) } if tt.wantErr { require.Equal(t, got.PackageVersion, "") require.Error(t, err) } }) } } func setFlags(t *testing.T, flagSet *flag.FlagSet, flags ...flagObj) *flag.FlagSet { t.Helper() for _, f := range flags { if f.name != "" { flagSet.StringVar(&f.name, f.name, f.value, "") } } return flagSet } func createTempPackageJson(t *testing.T, version string) error { t.Helper() data := packageJson{Version: version} file, _ := json.MarshalIndent(data, "", " ") err := os.WriteFile("package.json", file, 0644) require.NoError(t, err) t.Cleanup(func() { err := os.RemoveAll("package.json") require.NoError(t, err) }) return nil }
pkg/build/frontend/config_test.go
0
https://github.com/grafana/grafana/commit/95b48339f89c7d267bce7d894404d26ccd75d0e3
[ 0.0001769090158632025, 0.00017353023577015847, 0.00016909846453927457, 0.00017322473286185414, 0.0000026528666694503045 ]
{ "id": 0, "code_window": [ " annotationPermissionUpdate?: boolean;\n", " extractFieldsNameDeduplication?: boolean;\n", " dashboardSceneForViewers?: boolean;\n", " panelFilterVariable?: boolean;\n", "}" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " pdfTables?: boolean;\n" ], "file_path": "packages/grafana-data/src/types/featureToggles.gen.ts", "type": "add", "edit_start_line_idx": 161 }
import React, { useMemo } from 'react'; import { SelectableValue } from '@grafana/data'; import { Annotation, annotationLabels } from '../../utils/constants'; import { SelectWithAdd } from './SelectWIthAdd'; interface Props { onChange: (value: string) => void; existingKeys: string[]; value?: string; width?: number; className?: string; 'aria-label'?: string; } export const AnnotationKeyInput = ({ value, existingKeys, 'aria-label': ariaLabel, ...rest }: Props) => { const annotationOptions = useMemo( (): SelectableValue[] => Object.values(Annotation) .filter((key) => !existingKeys.includes(key)) // remove keys already taken in other annotations .map((key) => ({ value: key, label: annotationLabels[key] })), [existingKeys] ); return ( <SelectWithAdd aria-label={ariaLabel} value={value} options={annotationOptions} custom={!!value && !(Object.values(Annotation) as string[]).includes(value)} {...rest} /> ); };
public/app/features/alerting/unified/components/rule-editor/AnnotationKeyInput.tsx
0
https://github.com/grafana/grafana/commit/95b48339f89c7d267bce7d894404d26ccd75d0e3
[ 0.0001869732077466324, 0.0001749662187648937, 0.00016922346549108624, 0.00017183410818688571, 0.000007101912615326 ]
{ "id": 0, "code_window": [ " annotationPermissionUpdate?: boolean;\n", " extractFieldsNameDeduplication?: boolean;\n", " dashboardSceneForViewers?: boolean;\n", " panelFilterVariable?: boolean;\n", "}" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " pdfTables?: boolean;\n" ], "file_path": "packages/grafana-data/src/types/featureToggles.gen.ts", "type": "add", "edit_start_line_idx": 161 }
<svg xmlns="http://www.w3.org/2000/svg" data-name="Layer 1" viewBox="0 0 24 24"><path d="M7.75781,10.75781a3,3,0,1,0-3-3A3.00328,3.00328,0,0,0,7.75781,10.75781Zm0-4a1,1,0,1,1-1,1A1.00067,1.00067,0,0,1,7.75781,6.75781Zm8.48438,6.48438a3,3,0,1,0,3,3A3.00328,3.00328,0,0,0,16.24219,13.24219Zm0,4a1,1,0,1,1,1-1A1.00067,1.00067,0,0,1,16.24219,17.24219ZM19.707,4.293a.99962.99962,0,0,0-1.41406,0l-14,14A.99989.99989,0,1,0,5.707,19.707l14-14A.99962.99962,0,0,0,19.707,4.293Z"/></svg>
public/img/icons/unicons/percentage.svg
0
https://github.com/grafana/grafana/commit/95b48339f89c7d267bce7d894404d26ccd75d0e3
[ 0.00016879737086128443, 0.00016879737086128443, 0.00016879737086128443, 0.00016879737086128443, 0 ]
{ "id": 1, "code_window": [ "\t\t\tStage: FeatureStageExperimental,\n", "\t\t\tFrontendOnly: true,\n", "\t\t\tOwner: grafanaDashboardsSquad,\n", "\t\t\tHideFromDocs: true,\n", "\t\t},\n", "\t}\n", ")\n", "\n", "func boolPtr(b bool) *bool {\n", "\treturn &b\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t{\n", "\t\t\tName: \"pdfTables\",\n", "\t\t\tDescription: \"Enables generating table data as PDF in reporting\",\n", "\t\t\tStage: FeatureStagePrivatePreview,\n", "\t\t\tFrontendOnly: false,\n", "\t\t\tOwner: grafanaSharingSquad,\n", "\t\t},\n" ], "file_path": "pkg/services/featuremgmt/registry.go", "type": "add", "edit_start_line_idx": 1000 }
// To change feature flags, edit: // pkg/services/featuremgmt/registry.go // Then run tests in: // pkg/services/featuremgmt/toggles_gen_test.go // twice to generate and validate the feature flag files package featuremgmt var ( falsePtr = boolPtr(false) truePtr = boolPtr(true) // Register each toggle here standardFeatureFlags = []FeatureFlag{ { Name: "disableEnvelopeEncryption", Description: "Disable envelope encryption (emergency only)", Stage: FeatureStageGeneralAvailability, Owner: grafanaAsCodeSquad, AllowSelfServe: falsePtr, }, { Name: "live-service-web-worker", Description: "This will use a webworker thread to processes events rather than the main thread", Stage: FeatureStageExperimental, FrontendOnly: true, Owner: grafanaAppPlatformSquad, }, { Name: "queryOverLive", Description: "Use Grafana Live WebSocket to execute backend queries", Stage: FeatureStageExperimental, FrontendOnly: true, Owner: grafanaAppPlatformSquad, }, { Name: "panelTitleSearch", Description: "Search for dashboards using panel title", Stage: FeatureStagePublicPreview, Owner: grafanaAppPlatformSquad, }, { Name: "publicDashboards", Description: "Enables public access to dashboards", Stage: FeatureStageGeneralAvailability, Owner: grafanaSharingSquad, Expression: "true", // enabled by default AllowSelfServe: truePtr, }, { Name: "publicDashboardsEmailSharing", Description: "Enables public dashboard sharing to be restricted to only allowed emails", Stage: FeatureStagePublicPreview, RequiresLicense: true, Owner: grafanaSharingSquad, HideFromDocs: true, }, { Name: "lokiExperimentalStreaming", Description: "Support new streaming approach for loki (prototype, needs special loki build)", Stage: FeatureStageExperimental, Owner: grafanaObservabilityLogsSquad, }, { Name: "featureHighlights", Description: "Highlight Grafana Enterprise features", Stage: FeatureStageGeneralAvailability, Owner: grafanaAsCodeSquad, AllowSelfServe: falsePtr, }, { Name: "migrationLocking", Description: "Lock database during migrations", Stage: FeatureStagePublicPreview, Owner: grafanaBackendPlatformSquad, }, { Name: "storage", Description: "Configurable storage for dashboards, datasources, and resources", Stage: FeatureStageExperimental, Owner: grafanaAppPlatformSquad, }, { Name: "correlations", Description: "Correlations page", Stage: FeatureStagePublicPreview, Owner: grafanaExploreSquad, }, { Name: "exploreContentOutline", Description: "Content outline sidebar", Stage: FeatureStageGeneralAvailability, Owner: grafanaExploreSquad, Expression: "true", // enabled by default FrontendOnly: true, AllowSelfServe: falsePtr, }, { Name: "datasourceQueryMultiStatus", Description: "Introduce HTTP 207 Multi Status for api/ds/query", Stage: FeatureStageExperimental, Owner: grafanaPluginsPlatformSquad, }, { Name: "traceToMetrics", Description: "Enable trace to metrics links", Stage: FeatureStageExperimental, FrontendOnly: true, Owner: grafanaObservabilityTracesAndProfilingSquad, }, { Name: "newDBLibrary", Description: "Use jmoiron/sqlx rather than xorm for a few backend services", Stage: FeatureStagePublicPreview, Owner: grafanaBackendPlatformSquad, }, { Name: "autoMigrateOldPanels", Description: "Migrate old angular panels to supported versions (graph, table-old, worldmap, etc)", Stage: FeatureStagePublicPreview, FrontendOnly: true, Owner: grafanaDatavizSquad, }, { Name: "disableAngular", Description: "Dynamic flag to disable angular at runtime. The preferred method is to set `angular_support_enabled` to `false` in the [security] settings, which allows you to change the state at runtime.", Stage: FeatureStagePublicPreview, FrontendOnly: true, Owner: grafanaDatavizSquad, }, { Name: "canvasPanelNesting", Description: "Allow elements nesting", Stage: FeatureStageExperimental, FrontendOnly: true, Owner: grafanaDatavizSquad, }, { Name: "scenes", Description: "Experimental framework to build interactive dashboards", Stage: FeatureStageExperimental, FrontendOnly: true, Owner: grafanaDashboardsSquad, }, { Name: "disableSecretsCompatibility", Description: "Disable duplicated secret storage in legacy tables", Stage: FeatureStageExperimental, RequiresRestart: true, Owner: hostedGrafanaTeam, }, { Name: "logRequestsInstrumentedAsUnknown", Description: "Logs the path for requests that are instrumented as unknown", Stage: FeatureStageExperimental, Owner: hostedGrafanaTeam, }, { Name: "dataConnectionsConsole", Description: "Enables a new top-level page called Connections. This page is an experiment that provides a better experience when you install and configure data sources and other plugins.", Stage: FeatureStageGeneralAvailability, Expression: "true", // turned on by default Owner: grafanaPluginsPlatformSquad, AllowSelfServe: falsePtr, }, { // Some plugins rely on topnav feature flag being enabled, so we cannot remove this until we // can afford the breaking change, or we've detemined no one else is relying on it Name: "topnav", Description: "Enables topnav support in external plugins. The new Grafana navigation cannot be disabled.", Stage: FeatureStageDeprecated, Expression: "true", // enabled by default Owner: grafanaFrontendPlatformSquad, }, { Name: "dockedMegaMenu", Description: "Enable support for a persistent (docked) navigation menu", Stage: FeatureStageExperimental, FrontendOnly: true, Owner: grafanaFrontendPlatformSquad, }, { Name: "grpcServer", Description: "Run the GRPC server", Stage: FeatureStagePublicPreview, Owner: grafanaAppPlatformSquad, }, { Name: "entityStore", Description: "SQL-based entity store (requires storage flag also)", Stage: FeatureStageExperimental, RequiresDevMode: true, Owner: grafanaAppPlatformSquad, }, { Name: "cloudWatchCrossAccountQuerying", Description: "Enables cross-account querying in CloudWatch datasources", Stage: FeatureStageGeneralAvailability, Expression: "true", // enabled by default Owner: awsDatasourcesSquad, AllowSelfServe: falsePtr, }, { Name: "redshiftAsyncQueryDataSupport", Description: "Enable async query data support for Redshift", Stage: FeatureStageGeneralAvailability, Expression: "true", // enabled by default Owner: awsDatasourcesSquad, AllowSelfServe: falsePtr, }, { Name: "athenaAsyncQueryDataSupport", Description: "Enable async query data support for Athena", Stage: FeatureStageGeneralAvailability, Expression: "true", // enabled by default FrontendOnly: true, Owner: awsDatasourcesSquad, AllowSelfServe: falsePtr, }, { Name: "cloudwatchNewRegionsHandler", Description: "Refactor of /regions endpoint, no user-facing changes", Stage: FeatureStageExperimental, Owner: awsDatasourcesSquad, }, { Name: "showDashboardValidationWarnings", Description: "Show warnings when dashboards do not validate against the schema", Stage: FeatureStageExperimental, Owner: grafanaDashboardsSquad, }, { Name: "mysqlAnsiQuotes", Description: "Use double quotes to escape keyword in a MySQL query", Stage: FeatureStageExperimental, Owner: grafanaBackendPlatformSquad, }, { Name: "accessControlOnCall", Description: "Access control primitives for OnCall", Stage: FeatureStagePublicPreview, Owner: identityAccessTeam, }, { Name: "nestedFolders", Description: "Enable folder nesting", Stage: FeatureStagePublicPreview, Owner: grafanaBackendPlatformSquad, }, { Name: "nestedFolderPicker", Description: "Enables the new folder picker to work with nested folders. Requires the nestedFolders feature toggle", Stage: FeatureStageGeneralAvailability, Owner: grafanaFrontendPlatformSquad, FrontendOnly: true, Expression: "true", // enabled by default AllowSelfServe: falsePtr, }, { Name: "accessTokenExpirationCheck", Description: "Enable OAuth access_token expiration check and token refresh using the refresh_token", Stage: FeatureStageGeneralAvailability, Owner: identityAccessTeam, AllowSelfServe: falsePtr, }, { Name: "emptyDashboardPage", Description: "Enable the redesigned user interface of a dashboard page that includes no panels", Stage: FeatureStageGeneralAvailability, FrontendOnly: true, Expression: "true", // enabled by default Owner: grafanaDashboardsSquad, AllowSelfServe: falsePtr, }, { Name: "disablePrometheusExemplarSampling", Description: "Disable Prometheus exemplar sampling", Stage: FeatureStageGeneralAvailability, Owner: grafanaObservabilityMetricsSquad, AllowSelfServe: falsePtr, }, { Name: "alertingBacktesting", Description: "Rule backtesting API for alerting", Stage: FeatureStageExperimental, Owner: grafanaAlertingSquad, }, { Name: "editPanelCSVDragAndDrop", Description: "Enables drag and drop for CSV and Excel files", FrontendOnly: true, Stage: FeatureStageExperimental, Owner: grafanaBiSquad, }, { Name: "alertingNoNormalState", Description: "Stop maintaining state of alerts that are not firing", Stage: FeatureStagePublicPreview, RequiresRestart: false, Owner: grafanaAlertingSquad, }, { Name: "logsContextDatasourceUi", Description: "Allow datasource to provide custom UI for context view", Stage: FeatureStageGeneralAvailability, FrontendOnly: true, Owner: grafanaObservabilityLogsSquad, Expression: "true", // turned on by default AllowSelfServe: falsePtr, }, { Name: "lokiQuerySplitting", Description: "Split large interval queries into subqueries with smaller time intervals", Stage: FeatureStageGeneralAvailability, FrontendOnly: true, Owner: grafanaObservabilityLogsSquad, Expression: "true", // turned on by default AllowSelfServe: falsePtr, }, { Name: "lokiQuerySplittingConfig", Description: "Give users the option to configure split durations for Loki queries", Stage: FeatureStageExperimental, FrontendOnly: true, Owner: grafanaObservabilityLogsSquad, }, { Name: "individualCookiePreferences", Description: "Support overriding cookie preferences per user", Stage: FeatureStageExperimental, Owner: grafanaBackendPlatformSquad, }, { Name: "gcomOnlyExternalOrgRoleSync", Description: "Prohibits a user from changing organization roles synced with Grafana Cloud auth provider", Stage: FeatureStageGeneralAvailability, Owner: identityAccessTeam, AllowSelfServe: falsePtr, }, { Name: "prometheusMetricEncyclopedia", Description: "Adds the metrics explorer component to the Prometheus query builder as an option in metric select", Expression: "true", Stage: FeatureStageGeneralAvailability, FrontendOnly: true, Owner: grafanaObservabilityMetricsSquad, AllowSelfServe: falsePtr, }, { Name: "influxdbBackendMigration", Description: "Query InfluxDB InfluxQL without the proxy", Stage: FeatureStageGeneralAvailability, FrontendOnly: true, Owner: grafanaObservabilityMetricsSquad, Expression: "true", // enabled by default AllowSelfServe: falsePtr, }, { Name: "clientTokenRotation", Description: "Replaces the current in-request token rotation so that the client initiates the rotation", Stage: FeatureStageExperimental, Owner: identityAccessTeam, }, { Name: "prometheusDataplane", Description: "Changes responses to from Prometheus to be compliant with the dataplane specification. In particular, when this feature toggle is active, the numeric `Field.Name` is set from 'Value' to the value of the `__name__` label.", Expression: "true", Stage: FeatureStageGeneralAvailability, Owner: grafanaObservabilityMetricsSquad, AllowSelfServe: falsePtr, }, { Name: "lokiMetricDataplane", Description: "Changes metric responses from Loki to be compliant with the dataplane specification.", Stage: FeatureStageGeneralAvailability, Expression: "true", Owner: grafanaObservabilityLogsSquad, AllowSelfServe: falsePtr, }, { Name: "lokiLogsDataplane", Description: "Changes logs responses from Loki to be compliant with the dataplane specification.", Stage: FeatureStageExperimental, Owner: grafanaObservabilityLogsSquad, }, { Name: "dataplaneFrontendFallback", Description: "Support dataplane contract field name change for transformations and field name matchers where the name is different", Stage: FeatureStageGeneralAvailability, FrontendOnly: true, Expression: "true", Owner: grafanaObservabilityMetricsSquad, AllowSelfServe: falsePtr, }, { Name: "disableSSEDataplane", Description: "Disables dataplane specific processing in server side expressions.", Stage: FeatureStageExperimental, Owner: grafanaObservabilityMetricsSquad, }, { Name: "alertStateHistoryLokiSecondary", Description: "Enable Grafana to write alert state history to an external Loki instance in addition to Grafana annotations.", Stage: FeatureStageExperimental, Owner: grafanaAlertingSquad, }, { Name: "alertingNotificationsPoliciesMatchingInstances", Description: "Enables the preview of matching instances for notification policies", Stage: FeatureStageGeneralAvailability, FrontendOnly: true, Expression: "true", // enabled by default Owner: grafanaAlertingSquad, AllowSelfServe: falsePtr, }, { Name: "alertStateHistoryLokiPrimary", Description: "Enable a remote Loki instance as the primary source for state history reads.", Stage: FeatureStageExperimental, Owner: grafanaAlertingSquad, }, { Name: "alertStateHistoryLokiOnly", Description: "Disable Grafana alerts from emitting annotations when a remote Loki instance is available.", Stage: FeatureStageExperimental, Owner: grafanaAlertingSquad, }, { Name: "unifiedRequestLog", Description: "Writes error logs to the request logger", Stage: FeatureStageExperimental, Owner: grafanaBackendPlatformSquad, }, { Name: "renderAuthJWT", Description: "Uses JWT-based auth for rendering instead of relying on remote cache", Stage: FeatureStagePublicPreview, Owner: grafanaAsCodeSquad, }, { Name: "externalServiceAuth", Description: "Starts an OAuth2 authentication provider for external services", Stage: FeatureStageExperimental, RequiresDevMode: true, Owner: identityAccessTeam, }, { Name: "refactorVariablesTimeRange", Description: "Refactor time range variables flow to reduce number of API calls made when query variables are chained", Stage: FeatureStagePublicPreview, Owner: grafanaDashboardsSquad, }, { Name: "useCachingService", Description: "When active, the new query and resource caching implementation using a wire service inject replaces the previous middleware implementation.", Stage: FeatureStageGeneralAvailability, Owner: grafanaOperatorExperienceSquad, RequiresRestart: true, Expression: "true", // enabled by default AllowSelfServe: falsePtr, }, { Name: "enableElasticsearchBackendQuerying", Description: "Enable the processing of queries and responses in the Elasticsearch data source through backend", Stage: FeatureStageGeneralAvailability, Owner: grafanaObservabilityLogsSquad, Expression: "true", // enabled by default AllowSelfServe: falsePtr, }, { Name: "advancedDataSourcePicker", Description: "Enable a new data source picker with contextual information, recently used order and advanced mode", Stage: FeatureStageGeneralAvailability, FrontendOnly: true, Expression: "true", // enabled by default Owner: grafanaDashboardsSquad, AllowSelfServe: falsePtr, }, { Name: "faroDatasourceSelector", Description: "Enable the data source selector within the Frontend Apps section of the Frontend Observability", Stage: FeatureStagePublicPreview, FrontendOnly: true, Owner: appO11ySquad, }, { Name: "enableDatagridEditing", Description: "Enables the edit functionality in the datagrid panel", FrontendOnly: true, Stage: FeatureStagePublicPreview, Owner: grafanaBiSquad, }, { Name: "dataSourcePageHeader", Description: "Apply new pageHeader UI in data source edit page", FrontendOnly: true, Stage: FeatureStagePublicPreview, Owner: enterpriseDatasourcesSquad, }, { Name: "extraThemes", Description: "Enables extra themes", FrontendOnly: true, Stage: FeatureStageExperimental, Owner: grafanaFrontendPlatformSquad, }, { Name: "lokiPredefinedOperations", Description: "Adds predefined query operations to Loki query editor", FrontendOnly: true, Stage: FeatureStageExperimental, Owner: grafanaObservabilityLogsSquad, }, { Name: "pluginsFrontendSandbox", Description: "Enables the plugins frontend sandbox", Stage: FeatureStageExperimental, FrontendOnly: true, Owner: grafanaPluginsPlatformSquad, }, { Name: "dashboardEmbed", Description: "Allow embedding dashboard for external use in Code editors", FrontendOnly: true, Stage: FeatureStageExperimental, Owner: grafanaAsCodeSquad, }, { Name: "frontendSandboxMonitorOnly", Description: "Enables monitor only in the plugin frontend sandbox (if enabled)", Stage: FeatureStageExperimental, FrontendOnly: true, Owner: grafanaPluginsPlatformSquad, }, { Name: "sqlDatasourceDatabaseSelection", Description: "Enables previous SQL data source dataset dropdown behavior", FrontendOnly: true, Stage: FeatureStagePublicPreview, Owner: grafanaBiSquad, }, { Name: "lokiFormatQuery", Description: "Enables the ability to format Loki queries", FrontendOnly: true, Stage: FeatureStageExperimental, Owner: grafanaObservabilityLogsSquad, }, { Name: "cloudWatchLogsMonacoEditor", Description: "Enables the Monaco editor for CloudWatch Logs queries", Stage: FeatureStageGeneralAvailability, FrontendOnly: true, Expression: "true", // enabled by default Owner: awsDatasourcesSquad, AllowSelfServe: falsePtr, }, { Name: "exploreScrollableLogsContainer", Description: "Improves the scrolling behavior of logs in Explore", Stage: FeatureStageExperimental, FrontendOnly: true, Owner: grafanaObservabilityLogsSquad, }, { Name: "recordedQueriesMulti", Description: "Enables writing multiple items from a single query within Recorded Queries", Stage: FeatureStageGeneralAvailability, Expression: "true", Owner: grafanaObservabilityMetricsSquad, AllowSelfServe: falsePtr, }, { Name: "pluginsDynamicAngularDetectionPatterns", Description: "Enables fetching Angular detection patterns for plugins from GCOM and fallback to hardcoded ones", Stage: FeatureStageExperimental, FrontendOnly: false, Owner: grafanaPluginsPlatformSquad, }, { Name: "vizAndWidgetSplit", Description: "Split panels between visualizations and widgets", Stage: FeatureStageExperimental, FrontendOnly: true, Owner: grafanaDashboardsSquad, }, { Name: "prometheusIncrementalQueryInstrumentation", Description: "Adds RudderStack events to incremental queries", FrontendOnly: true, Stage: FeatureStageExperimental, Owner: grafanaObservabilityMetricsSquad, }, { Name: "logsExploreTableVisualisation", Description: "A table visualisation for logs in Explore", Stage: FeatureStageExperimental, FrontendOnly: true, Owner: grafanaObservabilityLogsSquad, }, { Name: "awsDatasourcesTempCredentials", Description: "Support temporary security credentials in AWS plugins for Grafana Cloud customers", Stage: FeatureStageExperimental, Owner: awsDatasourcesSquad, }, { Name: "transformationsRedesign", Description: "Enables the transformations redesign", Stage: FeatureStageGeneralAvailability, FrontendOnly: true, Expression: "true", // enabled by default Owner: grafanaObservabilityMetricsSquad, AllowSelfServe: falsePtr, }, { Name: "mlExpressions", Description: "Enable support for Machine Learning in server-side expressions", Stage: FeatureStageExperimental, FrontendOnly: false, Owner: grafanaAlertingSquad, }, { Name: "traceQLStreaming", Description: "Enables response streaming of TraceQL queries of the Tempo data source", Stage: FeatureStageExperimental, FrontendOnly: true, Owner: grafanaObservabilityTracesAndProfilingSquad, }, { Name: "metricsSummary", Description: "Enables metrics summary queries in the Tempo data source", Stage: FeatureStageExperimental, FrontendOnly: true, Owner: grafanaObservabilityTracesAndProfilingSquad, }, { Name: "grafanaAPIServer", Description: "Enable Kubernetes API Server for Grafana resources", Stage: FeatureStageExperimental, FrontendOnly: false, Owner: grafanaAppPlatformSquad, }, { Name: "grafanaAPIServerWithExperimentalAPIs", Description: "Register experimental APIs with the k8s API server", Stage: FeatureStageExperimental, FrontendOnly: false, Owner: grafanaAppPlatformSquad, }, { Name: "featureToggleAdminPage", Description: "Enable admin page for managing feature toggles from the Grafana front-end", Stage: FeatureStageExperimental, FrontendOnly: false, Owner: grafanaOperatorExperienceSquad, RequiresRestart: true, }, { Name: "awsAsyncQueryCaching", Description: "Enable caching for async queries for Redshift and Athena. Requires that the `useCachingService` feature toggle is enabled and the datasource has caching and async query support enabled", Stage: FeatureStagePublicPreview, Owner: awsDatasourcesSquad, }, { Name: "splitScopes", Description: "Support faster dashboard and folder search by splitting permission scopes into parts", Stage: FeatureStagePublicPreview, FrontendOnly: false, Owner: identityAccessTeam, RequiresRestart: true, }, { Name: "azureMonitorDataplane", Description: "Adds dataplane compliant frame metadata in the Azure Monitor datasource", Stage: FeatureStageGeneralAvailability, Owner: grafanaPartnerPluginsSquad, Expression: "true", // on by default AllowSelfServe: falsePtr, }, { Name: "traceToProfiles", Description: "Enables linking between traces and profiles", Stage: FeatureStageExperimental, FrontendOnly: true, Owner: grafanaObservabilityTracesAndProfilingSquad, }, { Name: "permissionsFilterRemoveSubquery", Description: "Alternative permission filter implementation that does not use subqueries for fetching the dashboard folder", Stage: FeatureStageExperimental, Owner: grafanaBackendPlatformSquad, }, { Name: "prometheusConfigOverhaulAuth", Description: "Update the Prometheus configuration page with the new auth component", Owner: grafanaObservabilityMetricsSquad, Stage: FeatureStageGeneralAvailability, Expression: "true", // on by default AllowSelfServe: falsePtr, }, { Name: "configurableSchedulerTick", Description: "Enable changing the scheduler base interval via configuration option unified_alerting.scheduler_tick_interval", Stage: FeatureStageExperimental, FrontendOnly: false, Owner: grafanaAlertingSquad, RequiresRestart: true, HideFromDocs: true, }, { Name: "influxdbSqlSupport", Description: "Enable InfluxDB SQL query language support with new querying UI", Stage: FeatureStageExperimental, FrontendOnly: false, Owner: grafanaObservabilityMetricsSquad, RequiresRestart: false, }, { Name: "alertingNoDataErrorExecution", Description: "Changes how Alerting state manager handles execution of NoData/Error", Stage: FeatureStagePrivatePreview, FrontendOnly: false, Owner: grafanaAlertingSquad, RequiresRestart: true, Enabled: true, }, { Name: "angularDeprecationUI", Description: "Display new Angular deprecation-related UI features", Stage: FeatureStageExperimental, FrontendOnly: true, Owner: grafanaPluginsPlatformSquad, }, { Name: "dashgpt", Description: "Enable AI powered features in dashboards", Stage: FeatureStageGeneralAvailability, FrontendOnly: true, Owner: grafanaDashboardsSquad, Expression: "true", // on by default AllowSelfServe: falsePtr, }, { Name: "reportingRetries", Description: "Enables rendering retries for the reporting feature", Stage: FeatureStagePublicPreview, FrontendOnly: false, Owner: grafanaSharingSquad, RequiresRestart: true, }, { Name: "newBrowseDashboards", Description: "New browse/manage dashboards UI", Stage: FeatureStageGeneralAvailability, Owner: grafanaFrontendPlatformSquad, FrontendOnly: true, Expression: "true", // on by default AllowSelfServe: falsePtr, }, { Name: "sseGroupByDatasource", Description: "Send query to the same datasource in a single request when using server side expressions", Stage: FeatureStageExperimental, Owner: grafanaObservabilityMetricsSquad, }, { Name: "requestInstrumentationStatusSource", Description: "Include a status source label for request metrics and logs", Stage: FeatureStageExperimental, FrontendOnly: false, Owner: grafanaPluginsPlatformSquad, }, { Name: "libraryPanelRBAC", Description: "Enables RBAC support for library panels", Stage: FeatureStageExperimental, FrontendOnly: false, Owner: grafanaDashboardsSquad, RequiresRestart: true, }, { Name: "lokiRunQueriesInParallel", Description: "Enables running Loki queries in parallel", Stage: FeatureStagePrivatePreview, FrontendOnly: false, Owner: grafanaObservabilityLogsSquad, }, { Name: "wargamesTesting", Description: "Placeholder feature flag for internal testing", Stage: FeatureStageExperimental, FrontendOnly: false, Owner: hostedGrafanaTeam, }, { Name: "alertingInsights", Description: "Show the new alerting insights landing page", FrontendOnly: true, Stage: FeatureStageGeneralAvailability, Owner: grafanaAlertingSquad, Expression: "true", // enabled by default AllowSelfServe: falsePtr, }, { Name: "alertingContactPointsV2", Description: "Show the new contacpoints list view", FrontendOnly: true, Stage: FeatureStagePublicPreview, Owner: grafanaAlertingSquad, }, { Name: "externalCorePlugins", Description: "Allow core plugins to be loaded as external", Stage: FeatureStageExperimental, Owner: grafanaPluginsPlatformSquad, }, { Name: "pluginsAPIMetrics", Description: "Sends metrics of public grafana packages usage by plugins", FrontendOnly: true, Stage: FeatureStageExperimental, Owner: grafanaPluginsPlatformSquad, }, { Name: "httpSLOLevels", Description: "Adds SLO level to http request metrics", Stage: FeatureStageExperimental, FrontendOnly: false, Owner: hostedGrafanaTeam, RequiresRestart: true, }, { Name: "idForwarding", Description: "Generate signed id token for identity that can be forwarded to plugins and external services", Stage: FeatureStageExperimental, Owner: identityAccessTeam, RequiresDevMode: true, }, { Name: "cloudWatchWildCardDimensionValues", Description: "Fetches dimension values from CloudWatch to correctly label wildcard dimensions", Stage: FeatureStageGeneralAvailability, Expression: "true", // enabled by default Owner: awsDatasourcesSquad, AllowSelfServe: falsePtr, }, { Name: "externalServiceAccounts", Description: "Automatic service account and token setup for plugins", Stage: FeatureStageExperimental, RequiresDevMode: true, Owner: identityAccessTeam, }, { Name: "panelMonitoring", Description: "Enables panel monitoring through logs and measurements", Stage: FeatureStageExperimental, Owner: grafanaDatavizSquad, FrontendOnly: true, }, { Name: "enableNativeHTTPHistogram", Description: "Enables native HTTP Histograms", Stage: FeatureStageExperimental, FrontendOnly: false, Owner: hostedGrafanaTeam, }, { Name: "formatString", Description: "Enable format string transformer", Stage: FeatureStageExperimental, FrontendOnly: true, Owner: grafanaBiSquad, }, { Name: "transformationsVariableSupport", Description: "Allows using variables in transformations", FrontendOnly: true, Stage: FeatureStageExperimental, Owner: grafanaBiSquad, }, { Name: "kubernetesPlaylists", Description: "Use the kubernetes API in the frontend for playlists", FrontendOnly: true, Stage: FeatureStageExperimental, Owner: grafanaAppPlatformSquad, }, { Name: "kubernetesPlaylistsAPI", Description: "Route /api/playlist API to k8s handlers", Stage: FeatureStageExperimental, Owner: grafanaAppPlatformSquad, RequiresRestart: true, // changes the API routing }, { Name: "cloudWatchBatchQueries", Description: "Runs CloudWatch metrics queries as separate batches", Stage: FeatureStagePublicPreview, Owner: awsDatasourcesSquad, }, { Name: "navAdminSubsections", Description: "Splits the administration section of the nav tree into subsections", Stage: FeatureStageExperimental, FrontendOnly: false, Owner: grafanaFrontendPlatformSquad, }, { Name: "recoveryThreshold", Description: "Enables feature recovery threshold (aka hysteresis) for threshold server-side expression", Stage: FeatureStageExperimental, FrontendOnly: false, Owner: grafanaAlertingSquad, RequiresRestart: true, }, { Name: "teamHttpHeaders", Description: "Enables datasources to apply team headers to the client requests", Stage: FeatureStageExperimental, FrontendOnly: false, Owner: identityAccessTeam, }, { Name: "awsDatasourcesNewFormStyling", Description: "Applies new form styling for configuration and query editors in AWS plugins", Stage: FeatureStageExperimental, FrontendOnly: true, Owner: awsDatasourcesSquad, }, { Name: "cachingOptimizeSerializationMemoryUsage", Description: "If enabled, the caching backend gradually serializes query responses for the cache, comparing against the configured `[caching]max_value_mb` value as it goes. This can can help prevent Grafana from running out of memory while attempting to cache very large query responses.", Stage: FeatureStageExperimental, Owner: grafanaOperatorExperienceSquad, FrontendOnly: false, }, { Name: "panelTitleSearchInV1", Description: "Enable searching for dashboards using panel title in search v1", RequiresDevMode: true, Stage: FeatureStageExperimental, Owner: grafanaBackendPlatformSquad, }, { Name: "pluginsInstrumentationStatusSource", Description: "Include a status source label for plugin request metrics and logs", FrontendOnly: false, Stage: FeatureStageExperimental, Owner: grafanaPluginsPlatformSquad, }, { Name: "costManagementUi", Description: "Toggles the display of the cost management ui plugin", Stage: FeatureStageExperimental, FrontendOnly: false, Owner: grafanaDatabasesFrontend, }, { Name: "managedPluginsInstall", Description: "Install managed plugins directly from plugins catalog", Stage: FeatureStageExperimental, RequiresDevMode: false, Owner: grafanaPluginsPlatformSquad, }, { Name: "prometheusPromQAIL", Description: "Prometheus and AI/ML to assist users in creating a query", Stage: FeatureStageExperimental, FrontendOnly: true, Owner: grafanaObservabilityMetricsSquad, }, { Name: "addFieldFromCalculationStatFunctions", Description: "Add cumulative and window functions to the add field from calculation transformation", Stage: FeatureStageExperimental, FrontendOnly: true, Owner: grafanaBiSquad, }, { Name: "alertmanagerRemoteSecondary", Description: "Enable Grafana to sync configuration and state with a remote Alertmanager.", Stage: FeatureStageExperimental, Owner: grafanaAlertingSquad, }, { Name: "alertmanagerRemotePrimary", Description: "Enable Grafana to have a remote Alertmanager instance as the primary Alertmanager.", Stage: FeatureStageExperimental, Owner: grafanaAlertingSquad, }, { Name: "alertmanagerRemoteOnly", Description: "Disable the internal Alertmanager and only use the external one defined.", Stage: FeatureStageExperimental, Owner: grafanaAlertingSquad, }, { Name: "annotationPermissionUpdate", Description: "Separate annotation permissions from dashboard permissions to allow for more granular control.", Stage: FeatureStageExperimental, RequiresDevMode: false, Owner: identityAccessTeam, }, { Name: "extractFieldsNameDeduplication", Description: "Make sure extracted field names are unique in the dataframe", Stage: FeatureStageExperimental, FrontendOnly: true, Owner: grafanaBiSquad, }, { Name: "dashboardSceneForViewers", Description: "Enables dashboard rendering using Scenes for viewer roles", Stage: FeatureStageExperimental, FrontendOnly: true, Owner: grafanaDashboardsSquad, }, { Name: "panelFilterVariable", Description: "Enables use of the `systemPanelFilterVar` variable to filter panels in a dashboard", Stage: FeatureStageExperimental, FrontendOnly: true, Owner: grafanaDashboardsSquad, HideFromDocs: true, }, } ) func boolPtr(b bool) *bool { return &b }
pkg/services/featuremgmt/registry.go
1
https://github.com/grafana/grafana/commit/95b48339f89c7d267bce7d894404d26ccd75d0e3
[ 0.9990978240966797, 0.03016160987317562, 0.00016391795361414552, 0.0005116149550303817, 0.16672742366790771 ]
{ "id": 1, "code_window": [ "\t\t\tStage: FeatureStageExperimental,\n", "\t\t\tFrontendOnly: true,\n", "\t\t\tOwner: grafanaDashboardsSquad,\n", "\t\t\tHideFromDocs: true,\n", "\t\t},\n", "\t}\n", ")\n", "\n", "func boolPtr(b bool) *bool {\n", "\treturn &b\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t{\n", "\t\t\tName: \"pdfTables\",\n", "\t\t\tDescription: \"Enables generating table data as PDF in reporting\",\n", "\t\t\tStage: FeatureStagePrivatePreview,\n", "\t\t\tFrontendOnly: false,\n", "\t\t\tOwner: grafanaSharingSquad,\n", "\t\t},\n" ], "file_path": "pkg/services/featuremgmt/registry.go", "type": "add", "edit_start_line_idx": 1000 }
--- aliases: - ../data-sources/alertmanager/ - ../features/datasources/alertmanager/ description: Guide for using Alertmanager as a data source in Grafana keywords: - grafana - prometheus - alertmanager - guide - queries labels: products: - cloud - enterprise - oss menuTitle: Alertmanager title: Alertmanager data source weight: 150 --- # Alertmanager data source Grafana includes built-in support for Alertmanager implementations in Prometheus and Mimir. Once you add it as a data source, you can use the [Grafana Alerting UI][alerting] to manage silences, contact points, and notification policies. To switch between Grafana and any configured Alertmanager data sources, you can select your preference from a drop-down option in those databases' data source settings pages. ## Alertmanager implementations The data source supports [Prometheus](https://prometheus.io/) and [Grafana Mimir](/docs/mimir/latest/) (default) implementations of Alertmanager. You can specify the implementation in the data source's Settings page. When using Prometheus, contact points and notification policies are read-only in the Grafana Alerting UI, because it doesn't support updates to the configuration using HTTP API. ## Configure the data source To configure basic settings for the data source, complete the following steps: 1. Click **Connections** in the left-side menu. 1. Under Your connections, click **Data sources**. 1. Enter `Alertmanager` in the search bar. 1. Click **Alertmanager**. The **Settings** tab of the data source is displayed. 1. Set the data source's basic configuration options: | Name | Description | | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Name** | Sets the name you use to refer to the data source | | **Default** | Sets whether the data source is pre-selected for new panels and queries | | **Alertmanager Implementation** | Alertmanager implementation. **Mimir**, **Cortex,** and **Prometheus** are supported | | **Receive Grafana Alerts** | When enabled the Alertmanager receives alert instances from Grafana-managed alert rules. **Important:** It works only if Grafana alerting is configured to send its alert instances to external Alertmanagers | | **HTTP URL** | Sets the HTTP protocol, IP, and port of your Alertmanager instance, such as `https://alertmanager.example.org:9093` | | **Access** | Only **Server** access mode is functional | ## Provision the Alertmanager data source You can provision Alertmanager data sources by updating Grafana's configuration files. For more information on provisioning, and common settings available, refer to the [provisioning docs page][data-sources]. Here is an example for provisioning the Alertmanager data source: ```yaml apiVersion: 1 datasources: - name: Alertmanager type: alertmanager url: http://localhost:9093 access: proxy jsonData: # Valid options for implementation include mimir, cortex and prometheus implementation: prometheus # Whether or not Grafana should send alert instances to this Alertmanager handleGrafanaManagedAlerts: false # optionally basicAuth: true basicAuthUser: my_user secureJsonData: basicAuthPassword: test_password ``` {{% docs/reference %}} [alerting]: "/docs/grafana/ -> /docs/grafana/<GRAFANA VERSION>/alerting" [alerting]: "/docs/grafana-cloud/ -> /docs/grafana-cloud/alerting-and-irm/alerting" [data-sources]: "/docs/grafana/ -> /docs/grafana/<GRAFANA VERSION>/administration/provisioning#datasources" [data-sources]: "/docs/grafana-cloud/ -> /docs/grafana/<GRAFANA VERSION>/administration/provisioning#datasources" {{% /docs/reference %}}
docs/sources/datasources/alertmanager/_index.md
0
https://github.com/grafana/grafana/commit/95b48339f89c7d267bce7d894404d26ccd75d0e3
[ 0.00017774529987946153, 0.00016730261268094182, 0.0001615770743228495, 0.00016712889191694558, 0.000004768903636431787 ]
{ "id": 1, "code_window": [ "\t\t\tStage: FeatureStageExperimental,\n", "\t\t\tFrontendOnly: true,\n", "\t\t\tOwner: grafanaDashboardsSquad,\n", "\t\t\tHideFromDocs: true,\n", "\t\t},\n", "\t}\n", ")\n", "\n", "func boolPtr(b bool) *bool {\n", "\treturn &b\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t{\n", "\t\t\tName: \"pdfTables\",\n", "\t\t\tDescription: \"Enables generating table data as PDF in reporting\",\n", "\t\t\tStage: FeatureStagePrivatePreview,\n", "\t\t\tFrontendOnly: false,\n", "\t\t\tOwner: grafanaSharingSquad,\n", "\t\t},\n" ], "file_path": "pkg/services/featuremgmt/registry.go", "type": "add", "edit_start_line_idx": 1000 }
// 🌟 This was machine generated. Do not edit. 🌟 // // Frame[0] { // "custom": { // "resultType": "exemplar" // } // } // Name: // Dimensions: 4 Fields by 1 Rows // +-----------------------------------+---------------------------------------------------------------------------------------------------+------------------+----------------+ // | Name: Time | Name: Value | Name: traceID | Name: a | // | Labels: | Labels: __name__=test_exemplar_metric_total, instance=localhost:8090, job=prometheus, service=bar | Labels: | Labels: | // | Type: []time.Time | Type: []float64 | Type: []string | Type: []string | // +-----------------------------------+---------------------------------------------------------------------------------------------------+------------------+----------------+ // | 2020-09-14 15:22:25.479 +0000 UTC | 6 | EpTxMJ40fUus7aGY | not in next | // +-----------------------------------+---------------------------------------------------------------------------------------------------+------------------+----------------+ // // // // Frame[1] { // "custom": { // "resultType": "exemplar" // } // } // Name: // Dimensions: 3 Fields by 2 Rows // +-----------------------------------+---------------------------------------------------------------------------------------------------+------------------+ // | Name: Time | Name: Value | Name: traceID | // | Labels: | Labels: __name__=test_exemplar_metric_total, instance=localhost:8090, job=prometheus, service=foo | Labels: | // | Type: []time.Time | Type: []float64 | Type: []string | // +-----------------------------------+---------------------------------------------------------------------------------------------------+------------------+ // | 2020-09-14 15:22:35.479 +0000 UTC | 19 | Olp9XHlq763ccsfa | // | 2020-09-14 15:22:45.489 +0000 UTC | 20 | hCtjygkIHwAN9vs4 | // +-----------------------------------+---------------------------------------------------------------------------------------------------+------------------+ // // // 🌟 This was machine generated. Do not edit. 🌟 { "frames": [ { "schema": { "meta": { "custom": { "resultType": "exemplar" } }, "fields": [ { "name": "Time", "type": "time", "typeInfo": { "frame": "time.Time" } }, { "name": "Value", "type": "number", "typeInfo": { "frame": "float64" }, "labels": { "__name__": "test_exemplar_metric_total", "instance": "localhost:8090", "job": "prometheus", "service": "bar" } }, { "name": "traceID", "type": "string", "typeInfo": { "frame": "string" } }, { "name": "a", "type": "string", "typeInfo": { "frame": "string" } } ] }, "data": { "values": [ [ 1600096945479 ], [ 6 ], [ "EpTxMJ40fUus7aGY" ], [ "not in next" ] ] } }, { "schema": { "meta": { "custom": { "resultType": "exemplar" } }, "fields": [ { "name": "Time", "type": "time", "typeInfo": { "frame": "time.Time" } }, { "name": "Value", "type": "number", "typeInfo": { "frame": "float64" }, "labels": { "__name__": "test_exemplar_metric_total", "instance": "localhost:8090", "job": "prometheus", "service": "foo" } }, { "name": "traceID", "type": "string", "typeInfo": { "frame": "string" } } ] }, "data": { "values": [ [ 1600096955479, 1600096965489 ], [ 19, 20 ], [ "Olp9XHlq763ccsfa", "hCtjygkIHwAN9vs4" ] ] } } ] }
pkg/util/converter/testdata/prom-exemplars-frame.jsonc
0
https://github.com/grafana/grafana/commit/95b48339f89c7d267bce7d894404d26ccd75d0e3
[ 0.00017911333998199552, 0.00017421231314074248, 0.0001710375800030306, 0.0001738496357575059, 0.0000018494122286938364 ]
{ "id": 1, "code_window": [ "\t\t\tStage: FeatureStageExperimental,\n", "\t\t\tFrontendOnly: true,\n", "\t\t\tOwner: grafanaDashboardsSquad,\n", "\t\t\tHideFromDocs: true,\n", "\t\t},\n", "\t}\n", ")\n", "\n", "func boolPtr(b bool) *bool {\n", "\treturn &b\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t{\n", "\t\t\tName: \"pdfTables\",\n", "\t\t\tDescription: \"Enables generating table data as PDF in reporting\",\n", "\t\t\tStage: FeatureStagePrivatePreview,\n", "\t\t\tFrontendOnly: false,\n", "\t\t\tOwner: grafanaSharingSquad,\n", "\t\t},\n" ], "file_path": "pkg/services/featuremgmt/registry.go", "type": "add", "edit_start_line_idx": 1000 }
import { isString, get } from 'lodash'; import { map } from 'rxjs/operators'; import { DataFrame, DataTransformerID, Field, FieldType, getFieldTypeFromValue, getUniqueFieldName, SynchronousDataTransformerInfo, } from '@grafana/data'; import { config } from '@grafana/runtime'; import { findField } from 'app/features/dimensions'; import { fieldExtractors } from './fieldExtractors'; import { ExtractFieldsOptions, FieldExtractorID, JSONPath } from './types'; export const extractFieldsTransformer: SynchronousDataTransformerInfo<ExtractFieldsOptions> = { id: DataTransformerID.extractFields, name: 'Extract fields', description: 'Parse fields from the contends of another', defaultOptions: {}, operator: (options, ctx) => (source) => source.pipe(map((data) => extractFieldsTransformer.transformer(options, ctx)(data))), transformer: (options: ExtractFieldsOptions) => { return (data: DataFrame[]) => { return data.map((v) => addExtractedFields(v, options)); }; }, }; export function addExtractedFields(frame: DataFrame, options: ExtractFieldsOptions): DataFrame { if (!options.source) { return frame; } const source = findField(frame, options.source); if (!source) { // this case can happen when there are multiple queries return frame; } const ext = fieldExtractors.getIfExists(options.format ?? FieldExtractorID.Auto); if (!ext) { throw new Error('unkonwn extractor'); } const count = frame.length; const names: string[] = []; // keep order const values = new Map<string, any[]>(); for (let i = 0; i < count; i++) { let obj = source.values[i]; if (isString(obj)) { try { obj = ext.parse(obj); } catch { obj = {}; // empty } } if (obj == null) { continue; } if (options.format === FieldExtractorID.JSON && options.jsonPaths && options.jsonPaths?.length > 0) { const newObj: { [k: string]: unknown } = {}; // filter out empty paths const filteredPaths = options.jsonPaths.filter((path: JSONPath) => path.path); if (filteredPaths.length > 0) { filteredPaths.forEach((path: JSONPath) => { const key = path.alias && path.alias.length > 0 ? path.alias : path.path; newObj[key] = get(obj, path.path) ?? 'Not Found'; }); obj = newObj; } } for (const [key, val] of Object.entries(obj)) { let buffer = values.get(key); if (buffer == null) { buffer = new Array(count); values.set(key, buffer); names.push(key); } buffer[i] = val; } } const fields = names.map((name) => { const buffer = values.get(name); const field = { name, values: buffer, type: buffer ? getFieldTypeFromValue(buffer.find((v) => v != null)) : FieldType.other, config: {}, } as Field; if (config.featureToggles.extractFieldsNameDeduplication) { field.name = getUniqueFieldName(field, frame); } return field; }); if (options.keepTime) { const sourceTime = findField(frame, 'Time') || findField(frame, 'time'); if (sourceTime) { fields.unshift(sourceTime); } } if (!options.replace) { fields.unshift(...frame.fields); } return { ...frame, fields, }; }
public/app/features/transformers/extractFields/extractFields.ts
0
https://github.com/grafana/grafana/commit/95b48339f89c7d267bce7d894404d26ccd75d0e3
[ 0.00017812398436944932, 0.0001741838059388101, 0.00016648154996801168, 0.00017464788106735796, 0.000003310462261651992 ]
{ "id": 2, "code_window": [ "extractFieldsNameDeduplication,experimental,@grafana/grafana-bi-squad,false,false,false,true\n", "dashboardSceneForViewers,experimental,@grafana/dashboards-squad,false,false,false,true\n", "panelFilterVariable,experimental,@grafana/dashboards-squad,false,false,false,true\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "pdfTables,privatePreview,@grafana/sharing-squad,false,false,false,false" ], "file_path": "pkg/services/featuremgmt/toggles_gen.csv", "type": "add", "edit_start_line_idx": 142 }
// NOTE: This file was auto generated. DO NOT EDIT DIRECTLY! // To change feature flags, edit: // pkg/services/featuremgmt/registry.go // Then run tests in: // pkg/services/featuremgmt/toggles_gen_test.go /** * Describes available feature toggles in Grafana. These can be configured via * conf/custom.ini to enable features under development or not yet available in * stable version. * * Only enabled values will be returned in this interface. * * NOTE: the possible values may change between versions without notice, although * this may cause compilation issues when depending on removed feature keys, the * runtime state will continue to work. * * @public */ export interface FeatureToggles { disableEnvelopeEncryption?: boolean; ['live-service-web-worker']?: boolean; queryOverLive?: boolean; panelTitleSearch?: boolean; publicDashboards?: boolean; publicDashboardsEmailSharing?: boolean; lokiExperimentalStreaming?: boolean; featureHighlights?: boolean; migrationLocking?: boolean; storage?: boolean; correlations?: boolean; exploreContentOutline?: boolean; datasourceQueryMultiStatus?: boolean; traceToMetrics?: boolean; newDBLibrary?: boolean; autoMigrateOldPanels?: boolean; disableAngular?: boolean; canvasPanelNesting?: boolean; scenes?: boolean; disableSecretsCompatibility?: boolean; logRequestsInstrumentedAsUnknown?: boolean; dataConnectionsConsole?: boolean; topnav?: boolean; dockedMegaMenu?: boolean; grpcServer?: boolean; entityStore?: boolean; cloudWatchCrossAccountQuerying?: boolean; redshiftAsyncQueryDataSupport?: boolean; athenaAsyncQueryDataSupport?: boolean; cloudwatchNewRegionsHandler?: boolean; showDashboardValidationWarnings?: boolean; mysqlAnsiQuotes?: boolean; accessControlOnCall?: boolean; nestedFolders?: boolean; nestedFolderPicker?: boolean; accessTokenExpirationCheck?: boolean; emptyDashboardPage?: boolean; disablePrometheusExemplarSampling?: boolean; alertingBacktesting?: boolean; editPanelCSVDragAndDrop?: boolean; alertingNoNormalState?: boolean; logsContextDatasourceUi?: boolean; lokiQuerySplitting?: boolean; lokiQuerySplittingConfig?: boolean; individualCookiePreferences?: boolean; gcomOnlyExternalOrgRoleSync?: boolean; prometheusMetricEncyclopedia?: boolean; influxdbBackendMigration?: boolean; clientTokenRotation?: boolean; prometheusDataplane?: boolean; lokiMetricDataplane?: boolean; lokiLogsDataplane?: boolean; dataplaneFrontendFallback?: boolean; disableSSEDataplane?: boolean; alertStateHistoryLokiSecondary?: boolean; alertingNotificationsPoliciesMatchingInstances?: boolean; alertStateHistoryLokiPrimary?: boolean; alertStateHistoryLokiOnly?: boolean; unifiedRequestLog?: boolean; renderAuthJWT?: boolean; externalServiceAuth?: boolean; refactorVariablesTimeRange?: boolean; useCachingService?: boolean; enableElasticsearchBackendQuerying?: boolean; advancedDataSourcePicker?: boolean; faroDatasourceSelector?: boolean; enableDatagridEditing?: boolean; dataSourcePageHeader?: boolean; extraThemes?: boolean; lokiPredefinedOperations?: boolean; pluginsFrontendSandbox?: boolean; dashboardEmbed?: boolean; frontendSandboxMonitorOnly?: boolean; sqlDatasourceDatabaseSelection?: boolean; lokiFormatQuery?: boolean; cloudWatchLogsMonacoEditor?: boolean; exploreScrollableLogsContainer?: boolean; recordedQueriesMulti?: boolean; pluginsDynamicAngularDetectionPatterns?: boolean; vizAndWidgetSplit?: boolean; prometheusIncrementalQueryInstrumentation?: boolean; logsExploreTableVisualisation?: boolean; awsDatasourcesTempCredentials?: boolean; transformationsRedesign?: boolean; mlExpressions?: boolean; traceQLStreaming?: boolean; metricsSummary?: boolean; grafanaAPIServer?: boolean; grafanaAPIServerWithExperimentalAPIs?: boolean; featureToggleAdminPage?: boolean; awsAsyncQueryCaching?: boolean; splitScopes?: boolean; azureMonitorDataplane?: boolean; traceToProfiles?: boolean; permissionsFilterRemoveSubquery?: boolean; prometheusConfigOverhaulAuth?: boolean; configurableSchedulerTick?: boolean; influxdbSqlSupport?: boolean; alertingNoDataErrorExecution?: boolean; angularDeprecationUI?: boolean; dashgpt?: boolean; reportingRetries?: boolean; newBrowseDashboards?: boolean; sseGroupByDatasource?: boolean; requestInstrumentationStatusSource?: boolean; libraryPanelRBAC?: boolean; lokiRunQueriesInParallel?: boolean; wargamesTesting?: boolean; alertingInsights?: boolean; alertingContactPointsV2?: boolean; externalCorePlugins?: boolean; pluginsAPIMetrics?: boolean; httpSLOLevels?: boolean; idForwarding?: boolean; cloudWatchWildCardDimensionValues?: boolean; externalServiceAccounts?: boolean; panelMonitoring?: boolean; enableNativeHTTPHistogram?: boolean; formatString?: boolean; transformationsVariableSupport?: boolean; kubernetesPlaylists?: boolean; kubernetesPlaylistsAPI?: boolean; cloudWatchBatchQueries?: boolean; navAdminSubsections?: boolean; recoveryThreshold?: boolean; teamHttpHeaders?: boolean; awsDatasourcesNewFormStyling?: boolean; cachingOptimizeSerializationMemoryUsage?: boolean; panelTitleSearchInV1?: boolean; pluginsInstrumentationStatusSource?: boolean; costManagementUi?: boolean; managedPluginsInstall?: boolean; prometheusPromQAIL?: boolean; addFieldFromCalculationStatFunctions?: boolean; alertmanagerRemoteSecondary?: boolean; alertmanagerRemotePrimary?: boolean; alertmanagerRemoteOnly?: boolean; annotationPermissionUpdate?: boolean; extractFieldsNameDeduplication?: boolean; dashboardSceneForViewers?: boolean; panelFilterVariable?: boolean; }
packages/grafana-data/src/types/featureToggles.gen.ts
1
https://github.com/grafana/grafana/commit/95b48339f89c7d267bce7d894404d26ccd75d0e3
[ 0.9872933626174927, 0.058681800961494446, 0.00016495671297889203, 0.0001697035477263853, 0.2321547120809555 ]
{ "id": 2, "code_window": [ "extractFieldsNameDeduplication,experimental,@grafana/grafana-bi-squad,false,false,false,true\n", "dashboardSceneForViewers,experimental,@grafana/dashboards-squad,false,false,false,true\n", "panelFilterVariable,experimental,@grafana/dashboards-squad,false,false,false,true\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "pdfTables,privatePreview,@grafana/sharing-squad,false,false,false,false" ], "file_path": "pkg/services/featuremgmt/toggles_gen.csv", "type": "add", "edit_start_line_idx": 142 }
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" viewBox="0 0 24 24"><path d="M12,2C6.5,2,2,6.5,2,12s4.5,10,10,10s10-4.5,10-10S17.5,2,12,2z M15.1,11.4l-2.6,1.5c-0.5,0.3-1.1,0.1-1.4-0.4C11,12.3,11,12.2,11,12V7c0-0.6,0.4-1,1-1s1,0.4,1,1v3.3l1.1-0.6c0.5-0.3,1.1-0.1,1.4,0.4S15.6,11.1,15.1,11.4z"/></svg>
public/img/icons/solid/clock-two.svg
0
https://github.com/grafana/grafana/commit/95b48339f89c7d267bce7d894404d26ccd75d0e3
[ 0.00017251446843147278, 0.00017251446843147278, 0.00017251446843147278, 0.00017251446843147278, 0 ]
{ "id": 2, "code_window": [ "extractFieldsNameDeduplication,experimental,@grafana/grafana-bi-squad,false,false,false,true\n", "dashboardSceneForViewers,experimental,@grafana/dashboards-squad,false,false,false,true\n", "panelFilterVariable,experimental,@grafana/dashboards-squad,false,false,false,true\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "pdfTables,privatePreview,@grafana/sharing-squad,false,false,false,false" ], "file_path": "pkg/services/featuremgmt/toggles_gen.csv", "type": "add", "edit_start_line_idx": 142 }
export interface AppNotification { id: string; severity: AppNotificationSeverity; icon: string; title: string; text: string; traceId?: string; component?: React.ReactElement; showing: boolean; timestamp: number; } export enum AppNotificationSeverity { Success = 'success', Warning = 'warning', Error = 'error', Info = 'info', } export enum AppNotificationTimeout { Success = 3000, Warning = 5000, Error = 7000, } export const timeoutMap = { [AppNotificationSeverity.Success]: AppNotificationTimeout.Success, [AppNotificationSeverity.Warning]: AppNotificationTimeout.Warning, [AppNotificationSeverity.Error]: AppNotificationTimeout.Error, [AppNotificationSeverity.Info]: AppNotificationTimeout.Success, }; export interface AppNotificationsState { byId: Record<string, AppNotification>; lastRead: number; }
public/app/types/appNotifications.ts
0
https://github.com/grafana/grafana/commit/95b48339f89c7d267bce7d894404d26ccd75d0e3
[ 0.00017426129488740116, 0.00017102021956816316, 0.00016891799168661237, 0.00017045078857336193, 0.0000022004637685313355 ]
{ "id": 2, "code_window": [ "extractFieldsNameDeduplication,experimental,@grafana/grafana-bi-squad,false,false,false,true\n", "dashboardSceneForViewers,experimental,@grafana/dashboards-squad,false,false,false,true\n", "panelFilterVariable,experimental,@grafana/dashboards-squad,false,false,false,true\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "pdfTables,privatePreview,@grafana/sharing-squad,false,false,false,false" ], "file_path": "pkg/services/featuremgmt/toggles_gen.csv", "type": "add", "edit_start_line_idx": 142 }
import { useId } from '@react-aria/utils'; import React, { useCallback, useState } from 'react'; import { selectors } from '@grafana/e2e-selectors'; import { TextArea, useStyles2 } from '@grafana/ui'; import { VariableQueryEditorProps } from '../types'; import { getStyles } from './VariableTextAreaField'; export const LEGACY_VARIABLE_QUERY_EDITOR_NAME = 'Grafana-LegacyVariableQueryEditor'; export const LegacyVariableQueryEditor = ({ onChange, query }: VariableQueryEditorProps) => { const styles = useStyles2(getStyles); const [value, setValue] = useState(query); const onValueChange = (event: React.FormEvent<HTMLTextAreaElement>) => { setValue(event.currentTarget.value); }; const onBlur = useCallback( (event: React.FormEvent<HTMLTextAreaElement>) => { onChange(event.currentTarget.value, event.currentTarget.value); }, [onChange] ); const id = useId(); return ( <TextArea id={id} rows={2} value={value} onChange={onValueChange} onBlur={onBlur} placeholder="Metric name or tags query" required aria-label={selectors.pages.Dashboard.Settings.Variables.Edit.QueryVariable.queryOptionsQueryInput} cols={52} className={styles.textarea} /> ); }; LegacyVariableQueryEditor.displayName = LEGACY_VARIABLE_QUERY_EDITOR_NAME;
public/app/features/variables/editor/LegacyVariableQueryEditor.tsx
0
https://github.com/grafana/grafana/commit/95b48339f89c7d267bce7d894404d26ccd75d0e3
[ 0.0002126469335053116, 0.00017784556257538497, 0.0001666586467763409, 0.0001684557064436376, 0.00001755715493345633 ]
{ "id": 3, "code_window": [ "\tFlagDashboardSceneForViewers = \"dashboardSceneForViewers\"\n", "\n", "\t// FlagPanelFilterVariable\n", "\t// Enables use of the `systemPanelFilterVar` variable to filter panels in a dashboard\n", "\tFlagPanelFilterVariable = \"panelFilterVariable\"\n", ")" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ "\n", "\t// FlagPdfTables\n", "\t// Enables generating table data as PDF in reporting\n", "\tFlagPdfTables = \"pdfTables\"\n" ], "file_path": "pkg/services/featuremgmt/toggles_gen.go", "type": "add", "edit_start_line_idx": 572 }
Name,Stage,Owner,requiresDevMode,RequiresLicense,RequiresRestart,FrontendOnly disableEnvelopeEncryption,GA,@grafana/grafana-as-code,false,false,false,false live-service-web-worker,experimental,@grafana/grafana-app-platform-squad,false,false,false,true queryOverLive,experimental,@grafana/grafana-app-platform-squad,false,false,false,true panelTitleSearch,preview,@grafana/grafana-app-platform-squad,false,false,false,false publicDashboards,GA,@grafana/sharing-squad,false,false,false,false publicDashboardsEmailSharing,preview,@grafana/sharing-squad,false,true,false,false lokiExperimentalStreaming,experimental,@grafana/observability-logs,false,false,false,false featureHighlights,GA,@grafana/grafana-as-code,false,false,false,false migrationLocking,preview,@grafana/backend-platform,false,false,false,false storage,experimental,@grafana/grafana-app-platform-squad,false,false,false,false correlations,preview,@grafana/explore-squad,false,false,false,false exploreContentOutline,GA,@grafana/explore-squad,false,false,false,true datasourceQueryMultiStatus,experimental,@grafana/plugins-platform-backend,false,false,false,false traceToMetrics,experimental,@grafana/observability-traces-and-profiling,false,false,false,true newDBLibrary,preview,@grafana/backend-platform,false,false,false,false autoMigrateOldPanels,preview,@grafana/dataviz-squad,false,false,false,true disableAngular,preview,@grafana/dataviz-squad,false,false,false,true canvasPanelNesting,experimental,@grafana/dataviz-squad,false,false,false,true scenes,experimental,@grafana/dashboards-squad,false,false,false,true disableSecretsCompatibility,experimental,@grafana/hosted-grafana-team,false,false,true,false logRequestsInstrumentedAsUnknown,experimental,@grafana/hosted-grafana-team,false,false,false,false dataConnectionsConsole,GA,@grafana/plugins-platform-backend,false,false,false,false topnav,deprecated,@grafana/grafana-frontend-platform,false,false,false,false dockedMegaMenu,experimental,@grafana/grafana-frontend-platform,false,false,false,true grpcServer,preview,@grafana/grafana-app-platform-squad,false,false,false,false entityStore,experimental,@grafana/grafana-app-platform-squad,true,false,false,false cloudWatchCrossAccountQuerying,GA,@grafana/aws-datasources,false,false,false,false redshiftAsyncQueryDataSupport,GA,@grafana/aws-datasources,false,false,false,false athenaAsyncQueryDataSupport,GA,@grafana/aws-datasources,false,false,false,true cloudwatchNewRegionsHandler,experimental,@grafana/aws-datasources,false,false,false,false showDashboardValidationWarnings,experimental,@grafana/dashboards-squad,false,false,false,false mysqlAnsiQuotes,experimental,@grafana/backend-platform,false,false,false,false accessControlOnCall,preview,@grafana/identity-access-team,false,false,false,false nestedFolders,preview,@grafana/backend-platform,false,false,false,false nestedFolderPicker,GA,@grafana/grafana-frontend-platform,false,false,false,true accessTokenExpirationCheck,GA,@grafana/identity-access-team,false,false,false,false emptyDashboardPage,GA,@grafana/dashboards-squad,false,false,false,true disablePrometheusExemplarSampling,GA,@grafana/observability-metrics,false,false,false,false alertingBacktesting,experimental,@grafana/alerting-squad,false,false,false,false editPanelCSVDragAndDrop,experimental,@grafana/grafana-bi-squad,false,false,false,true alertingNoNormalState,preview,@grafana/alerting-squad,false,false,false,false logsContextDatasourceUi,GA,@grafana/observability-logs,false,false,false,true lokiQuerySplitting,GA,@grafana/observability-logs,false,false,false,true lokiQuerySplittingConfig,experimental,@grafana/observability-logs,false,false,false,true individualCookiePreferences,experimental,@grafana/backend-platform,false,false,false,false gcomOnlyExternalOrgRoleSync,GA,@grafana/identity-access-team,false,false,false,false prometheusMetricEncyclopedia,GA,@grafana/observability-metrics,false,false,false,true influxdbBackendMigration,GA,@grafana/observability-metrics,false,false,false,true clientTokenRotation,experimental,@grafana/identity-access-team,false,false,false,false prometheusDataplane,GA,@grafana/observability-metrics,false,false,false,false lokiMetricDataplane,GA,@grafana/observability-logs,false,false,false,false lokiLogsDataplane,experimental,@grafana/observability-logs,false,false,false,false dataplaneFrontendFallback,GA,@grafana/observability-metrics,false,false,false,true disableSSEDataplane,experimental,@grafana/observability-metrics,false,false,false,false alertStateHistoryLokiSecondary,experimental,@grafana/alerting-squad,false,false,false,false alertingNotificationsPoliciesMatchingInstances,GA,@grafana/alerting-squad,false,false,false,true alertStateHistoryLokiPrimary,experimental,@grafana/alerting-squad,false,false,false,false alertStateHistoryLokiOnly,experimental,@grafana/alerting-squad,false,false,false,false unifiedRequestLog,experimental,@grafana/backend-platform,false,false,false,false renderAuthJWT,preview,@grafana/grafana-as-code,false,false,false,false externalServiceAuth,experimental,@grafana/identity-access-team,true,false,false,false refactorVariablesTimeRange,preview,@grafana/dashboards-squad,false,false,false,false useCachingService,GA,@grafana/grafana-operator-experience-squad,false,false,true,false enableElasticsearchBackendQuerying,GA,@grafana/observability-logs,false,false,false,false advancedDataSourcePicker,GA,@grafana/dashboards-squad,false,false,false,true faroDatasourceSelector,preview,@grafana/app-o11y,false,false,false,true enableDatagridEditing,preview,@grafana/grafana-bi-squad,false,false,false,true dataSourcePageHeader,preview,@grafana/enterprise-datasources,false,false,false,true extraThemes,experimental,@grafana/grafana-frontend-platform,false,false,false,true lokiPredefinedOperations,experimental,@grafana/observability-logs,false,false,false,true pluginsFrontendSandbox,experimental,@grafana/plugins-platform-backend,false,false,false,true dashboardEmbed,experimental,@grafana/grafana-as-code,false,false,false,true frontendSandboxMonitorOnly,experimental,@grafana/plugins-platform-backend,false,false,false,true sqlDatasourceDatabaseSelection,preview,@grafana/grafana-bi-squad,false,false,false,true lokiFormatQuery,experimental,@grafana/observability-logs,false,false,false,true cloudWatchLogsMonacoEditor,GA,@grafana/aws-datasources,false,false,false,true exploreScrollableLogsContainer,experimental,@grafana/observability-logs,false,false,false,true recordedQueriesMulti,GA,@grafana/observability-metrics,false,false,false,false pluginsDynamicAngularDetectionPatterns,experimental,@grafana/plugins-platform-backend,false,false,false,false vizAndWidgetSplit,experimental,@grafana/dashboards-squad,false,false,false,true prometheusIncrementalQueryInstrumentation,experimental,@grafana/observability-metrics,false,false,false,true logsExploreTableVisualisation,experimental,@grafana/observability-logs,false,false,false,true awsDatasourcesTempCredentials,experimental,@grafana/aws-datasources,false,false,false,false transformationsRedesign,GA,@grafana/observability-metrics,false,false,false,true mlExpressions,experimental,@grafana/alerting-squad,false,false,false,false traceQLStreaming,experimental,@grafana/observability-traces-and-profiling,false,false,false,true metricsSummary,experimental,@grafana/observability-traces-and-profiling,false,false,false,true grafanaAPIServer,experimental,@grafana/grafana-app-platform-squad,false,false,false,false grafanaAPIServerWithExperimentalAPIs,experimental,@grafana/grafana-app-platform-squad,false,false,false,false featureToggleAdminPage,experimental,@grafana/grafana-operator-experience-squad,false,false,true,false awsAsyncQueryCaching,preview,@grafana/aws-datasources,false,false,false,false splitScopes,preview,@grafana/identity-access-team,false,false,true,false azureMonitorDataplane,GA,@grafana/partner-datasources,false,false,false,false traceToProfiles,experimental,@grafana/observability-traces-and-profiling,false,false,false,true permissionsFilterRemoveSubquery,experimental,@grafana/backend-platform,false,false,false,false prometheusConfigOverhaulAuth,GA,@grafana/observability-metrics,false,false,false,false configurableSchedulerTick,experimental,@grafana/alerting-squad,false,false,true,false influxdbSqlSupport,experimental,@grafana/observability-metrics,false,false,false,false alertingNoDataErrorExecution,privatePreview,@grafana/alerting-squad,false,false,true,false angularDeprecationUI,experimental,@grafana/plugins-platform-backend,false,false,false,true dashgpt,GA,@grafana/dashboards-squad,false,false,false,true reportingRetries,preview,@grafana/sharing-squad,false,false,true,false newBrowseDashboards,GA,@grafana/grafana-frontend-platform,false,false,false,true sseGroupByDatasource,experimental,@grafana/observability-metrics,false,false,false,false requestInstrumentationStatusSource,experimental,@grafana/plugins-platform-backend,false,false,false,false libraryPanelRBAC,experimental,@grafana/dashboards-squad,false,false,true,false lokiRunQueriesInParallel,privatePreview,@grafana/observability-logs,false,false,false,false wargamesTesting,experimental,@grafana/hosted-grafana-team,false,false,false,false alertingInsights,GA,@grafana/alerting-squad,false,false,false,true alertingContactPointsV2,preview,@grafana/alerting-squad,false,false,false,true externalCorePlugins,experimental,@grafana/plugins-platform-backend,false,false,false,false pluginsAPIMetrics,experimental,@grafana/plugins-platform-backend,false,false,false,true httpSLOLevels,experimental,@grafana/hosted-grafana-team,false,false,true,false idForwarding,experimental,@grafana/identity-access-team,true,false,false,false cloudWatchWildCardDimensionValues,GA,@grafana/aws-datasources,false,false,false,false externalServiceAccounts,experimental,@grafana/identity-access-team,true,false,false,false panelMonitoring,experimental,@grafana/dataviz-squad,false,false,false,true enableNativeHTTPHistogram,experimental,@grafana/hosted-grafana-team,false,false,false,false formatString,experimental,@grafana/grafana-bi-squad,false,false,false,true transformationsVariableSupport,experimental,@grafana/grafana-bi-squad,false,false,false,true kubernetesPlaylists,experimental,@grafana/grafana-app-platform-squad,false,false,false,true kubernetesPlaylistsAPI,experimental,@grafana/grafana-app-platform-squad,false,false,true,false cloudWatchBatchQueries,preview,@grafana/aws-datasources,false,false,false,false navAdminSubsections,experimental,@grafana/grafana-frontend-platform,false,false,false,false recoveryThreshold,experimental,@grafana/alerting-squad,false,false,true,false teamHttpHeaders,experimental,@grafana/identity-access-team,false,false,false,false awsDatasourcesNewFormStyling,experimental,@grafana/aws-datasources,false,false,false,true cachingOptimizeSerializationMemoryUsage,experimental,@grafana/grafana-operator-experience-squad,false,false,false,false panelTitleSearchInV1,experimental,@grafana/backend-platform,true,false,false,false pluginsInstrumentationStatusSource,experimental,@grafana/plugins-platform-backend,false,false,false,false costManagementUi,experimental,@grafana/databases-frontend,false,false,false,false managedPluginsInstall,experimental,@grafana/plugins-platform-backend,false,false,false,false prometheusPromQAIL,experimental,@grafana/observability-metrics,false,false,false,true addFieldFromCalculationStatFunctions,experimental,@grafana/grafana-bi-squad,false,false,false,true alertmanagerRemoteSecondary,experimental,@grafana/alerting-squad,false,false,false,false alertmanagerRemotePrimary,experimental,@grafana/alerting-squad,false,false,false,false alertmanagerRemoteOnly,experimental,@grafana/alerting-squad,false,false,false,false annotationPermissionUpdate,experimental,@grafana/identity-access-team,false,false,false,false extractFieldsNameDeduplication,experimental,@grafana/grafana-bi-squad,false,false,false,true dashboardSceneForViewers,experimental,@grafana/dashboards-squad,false,false,false,true panelFilterVariable,experimental,@grafana/dashboards-squad,false,false,false,true
pkg/services/featuremgmt/toggles_gen.csv
1
https://github.com/grafana/grafana/commit/95b48339f89c7d267bce7d894404d26ccd75d0e3
[ 0.003386350581422448, 0.00038342972402460873, 0.00016106791736092418, 0.00017050575115717947, 0.0008025740971788764 ]
{ "id": 3, "code_window": [ "\tFlagDashboardSceneForViewers = \"dashboardSceneForViewers\"\n", "\n", "\t// FlagPanelFilterVariable\n", "\t// Enables use of the `systemPanelFilterVar` variable to filter panels in a dashboard\n", "\tFlagPanelFilterVariable = \"panelFilterVariable\"\n", ")" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ "\n", "\t// FlagPdfTables\n", "\t// Enables generating table data as PDF in reporting\n", "\tFlagPdfTables = \"pdfTables\"\n" ], "file_path": "pkg/services/featuremgmt/toggles_gen.go", "type": "add", "edit_start_line_idx": 572 }
--- aliases: - ../../features/navigation-links/ - ../../linking/ - ../../linking/dashboard-links/ - ../../linking/linking-overview/ - ../../panels/working-with-panels/add-link-to-panel/ - ../manage-dashboard-links/ description: How to link Grafana dashboards. keywords: - link - dashboard - grafana - linking - create links - link dashboards - navigate labels: products: - cloud - enterprise - oss menuTitle: Manage dashboard links title: Manage dashboard links weight: 500 --- # Manage dashboard links You can use links to navigate between commonly-used dashboards or to connect others to your visualizations. Links let you create shortcuts to other dashboards, panels, and even external websites. Grafana supports dashboard links, panel links, and data links. Dashboard links are displayed at the top of the dashboard. Panel links are accessible by clicking the icon next to the panel title. ## Which link should you use? Start by figuring out how you're currently navigating between dashboards. If you're often jumping between a set of dashboards and struggling to find the same context in each, links can help optimize your workflow. The next step is to figure out which link type is right for your workflow. Even though all the link types in Grafana are used to create shortcuts to other dashboards or external websites, they work in different contexts. - If the link relates to most if not all of the panels in the dashboard, use [dashboard links](#dashboard-links). - If you want to drill down into specific panels, use [panel links](#panel-links). - If you want to link to an external site, you can use either a dashboard link or a panel link. - If you want to drill down into a specific series, or even a single measurement, use [data links][]. ## Controlling time range using the URL To control the time range of a panel or dashboard, you can provide query parameters in the dashboard URL: - `from` - defines lower limit of the time range, specified in ms epoch - `to` - defines upper limit of the time range, specified in ms epoch - `time` and `time.window` - defines a time range from `time-time.window/2` to `time+time.window/2`. Both params should be specified in ms. For example `?time=1500000000000&time.window=10000` will result in 10s time range from 1499999995000 to 1500000005000 ## Dashboard links When you create a dashboard link, you can include the time range and current template variables to directly jump to the same context in another dashboard. This way, you don’t have to worry whether the person you send the link to is looking at the right data. For other types of links, refer to [Data link variables][]. Dashboard links can also be used as shortcuts to external systems, such as submitting [a GitHub issue with the current dashboard name](https://github.com/grafana/grafana/issues/new?title=Dashboard%3A%20HTTP%20Requests). To see an example of dashboard links in action, check out: - [Dashboard links with variables](https://play.grafana.org/d/rUpVRdamz/dashboard-links-with-variables?orgId=1) - [Prometheus repeat](https://play.grafana.org/d/000000036/prometheus-repeat?orgId=1) Once you've added a dashboard link, it appears in the upper right corner of your dashboard. ### Add links to dashboards Add links to other dashboards at the top of your current dashboard. 1. While viewing the dashboard you want to link, click the gear at the top of the screen to open **Dashboard settings**. 1. Click **Links** and then click **Add Dashboard Link** or **New**. 1. In **Type**, select **dashboards**. 1. Select link options: - **With tags** – Enter tags to limit the linked dashboards to only the ones with the tags you enter. Otherwise, Grafana includes links to all other dashboards. - **As dropdown** – If you are linking to lots of dashboards, then you probably want to select this option and add an optional title to the dropdown. Otherwise, Grafana displays the dashboard links side by side across the top of your dashboard. - **Time range** – Select this option to include the dashboard time range in the link. When the user clicks the link, the linked dashboard opens with the indicated time range already set. **Example:** https://play.grafana.org/d/000000010/annotations?orgId=1&from=now-3h&to=now - **Variable values** – Select this option to include template variables currently used as query parameters in the link. When the user clicks the link, any matching templates in the linked dashboard are set to the values from the link. For more information, see [Dashboard URL variables][]. - **Open in new tab** – Select this option if you want the dashboard link to open in a new tab or window. 1. Click **Add**. ### Add a URL link to a dashboard Add a link to a URL at the top of your current dashboard. You can link to any available URL, including dashboards, panels, or external sites. You can even control the time range to ensure the user is zoomed in on the right data in Grafana. 1. While viewing the dashboard you want to link, click the gear at the top of the screen to open **Dashboard settings**. 1. Click **Links** and then click **Add Dashboard Link** or **New**. 1. In **Type**, select **link**. 1. Select link options: - **Url** – Enter the URL you want to link to. Depending on the target, you might want to include field values. **Example:** https://github.com/grafana/grafana/issues/new?title=Dashboard%3A%20HTTP%20Requests - **Title** – Enter the title you want the link to display. - **Tooltip** – Enter the tooltip you want the link to display when the user hovers their mouse over it. - **Icon** – Choose the icon you want displayed with the link. - **Time range** – Select this option to include the dashboard time range in the link. When the user clicks the link, the linked dashboard opens with the indicated time range already set. **Example:** https://play.grafana.org/d/000000010/annotations?orgId=1&from=now-3h&to=now - `from` - Defines the lower limit of the time range, specified in ms epoch. - `to` - Defines the upper limit of the time range, specified in ms epoch. - `time` and `time.window` - Define a time range from `time-time.window/2` to `time+time.window/2`. Both params should be specified in ms. For example `?time=1500000000000&time.window=10000` will result in 10s time range from 1499999995000 to 1500000005000. - **Variable values** – Select this option to include template variables currently used as query parameters in the link. When the user clicks the link, any matching templates in the linked dashboard are set to the values from the link. Here is the variable format: `https://${you-domain}/path/to/your/dashboard?var-${template-varable1}=value1&var-{template-variable2}=value2` **Example:** https://play.grafana.org/d/000000074/alerting?var-app=backend&var-server=backend_01&var-server=backend_03&var-interval=1h - **Open in new tab** – Select this option if you want the dashboard link to open in a new tab or window. 1. Click **Add**. ### Update a dashboard link To change or update an existing dashboard link, follow this procedure. 1. In Dashboard Settings, on the Links tab, click the existing link that you want to edit. 1. Change the settings and then click **Update**. ## Duplicate a dashboard link To duplicate an existing dashboard link, click the duplicate icon next to the existing link that you want to duplicate. ### Delete a dashboard link To delete an existing dashboard link, click the trash icon next to the duplicate icon that you want to delete. ## Panel links Each panel can have its own set of links that are shown in the upper left of the panel after the panel title. You can link to any available URL, including dashboards, panels, or external sites. You can even control the time range to ensure the user is zoomed in on the right data in Grafana. Click the icon next to the panel title to see available panel links. {{< figure src="/media/docs/grafana/screenshot-panel-links.png" width="200px" >}} ### Add a panel link 1. Hover over any part of the panel to which you want to add the link to display the actions menu on the top right corner. 1. Click the menu and select **Edit**. To use a keyboard shortcut to open the panel, hover over the panel and press `e`. 1. Expand the **Panel options** section, scroll down to Panel links. 1. Click **Add link**. 1. Enter a **Title**. **Title** is a human-readable label for the link that will be displayed in the UI. 1. Enter the **URL** you want to link to. You can even add one of the template variables defined in the dashboard. Press Ctrl+Space or Cmd+Space and click in the **URL** field to see the available variables. By adding template variables to your panel link, the link sends the user to the right context, with the relevant variables already set. You can also use time variables: - `from` - Defines the lower limit of the time range, specified in ms epoch. - `to` - Defines the upper limit of the time range, specified in ms epoch. - `time` and `time.window` - Define a time range from `time-time.window/2` to `time+time.window/2`. Both params should be specified in ms. For example `?time=1500000000000&time.window=10000` will result in 10s time range from 1499999995000 to 1500000005000. 1. If you want the link to open in a new tab, then select **Open in a new tab**. 1. Click **Save** to save changes and close the window. 1. Click **Save** in the upper right to save your changes to the dashboard. ### Update a panel link 1. Hover over any part of the panel to display the actions menu on the top right corner. 1. Click the menu and select **Edit**. To use a keyboard shortcut to open the panel, hover over the panel and press `e`. 1. Expand the **Panel options** section, scroll down to Panel links. 1. Find the link that you want to make changes to. 1. Click the Edit (pencil) icon to open the Edit link window. 1. Make any necessary changes. 1. Click **Save** to save changes and close the window. 1. Click **Save** in the upper right to save your changes to the dashboard. ### Delete a panel link 1. Hover over any part of the panel to display the actions menu on the top right corner. 1. Click the menu and select **Edit**. To use a keyboard shortcut to open the panel, hover over the panel and press `e`. 1. Expand the **Panel options** section, scroll down to Panel links. 1. Find the link that you want to delete. 1. Click the **X** icon next to the link you want to delete. 1. Click **Save** in the upper right to save your changes to the dashboard. {{% docs/reference %}} [data links]: "/docs/grafana/ -> /docs/grafana/<GRAFANA VERSION>/panels-visualizations/configure-data-links#data-links" [data links]: "/docs/grafana-cloud/ -> /docs/grafana/<GRAFANA VERSION>/panels-visualizations/configure-data-links#data-links" [Dashboard URL variables]: "/docs/grafana/ -> /docs/grafana/<GRAFANA VERSION>/dashboards/build-dashboards/create-dashboard-url-variables" [Dashboard URL variables]: "/docs/grafana-cloud/ -> /docs/grafana/<GRAFANA VERSION>/dashboards/build-dashboards/create-dashboard-url-variables" [Data link variables]: "/docs/grafana/ -> /docs/grafana/<GRAFANA VERSION>/panels-visualizations/configure-data-links#data-link-variables" [Data link variables]: "/docs/grafana-cloud/ -> /docs/grafana/<GRAFANA VERSION>/panels-visualizations/configure-data-links#data-link-variables" {{% /docs/reference %}}
docs/sources/dashboards/build-dashboards/manage-dashboard-links/index.md
0
https://github.com/grafana/grafana/commit/95b48339f89c7d267bce7d894404d26ccd75d0e3
[ 0.00535855395719409, 0.0006737895892001688, 0.00016769749345257878, 0.0003390801721252501, 0.001156094134785235 ]
{ "id": 3, "code_window": [ "\tFlagDashboardSceneForViewers = \"dashboardSceneForViewers\"\n", "\n", "\t// FlagPanelFilterVariable\n", "\t// Enables use of the `systemPanelFilterVar` variable to filter panels in a dashboard\n", "\tFlagPanelFilterVariable = \"panelFilterVariable\"\n", ")" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ "\n", "\t// FlagPdfTables\n", "\t// Enables generating table data as PDF in reporting\n", "\tFlagPdfTables = \"pdfTables\"\n" ], "file_path": "pkg/services/featuremgmt/toggles_gen.go", "type": "add", "edit_start_line_idx": 572 }
package database import ( "context" // #nosec G505 Used only for generating a 160 bit hash, it's not used for security purposes "errors" "testing" "github.com/grafana/grafana/pkg/infra/db" "github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/stretchr/testify/require" ) func TestAccessControlStore_SaveExternalServiceRole(t *testing.T) { type run struct { cmd accesscontrol.SaveExternalServiceRoleCommand wantErr bool } tests := []struct { name string runs []run }{ { name: "create app role", runs: []run{ { cmd: accesscontrol.SaveExternalServiceRoleCommand{ ExternalServiceID: "app1", Global: true, ServiceAccountID: 1, Permissions: []accesscontrol.Permission{ {Action: "users:read", Scope: "users:id:1"}, {Action: "users:read", Scope: "users:id:2"}, }, }, wantErr: false, }, }, }, { name: "update app role", runs: []run{ { cmd: accesscontrol.SaveExternalServiceRoleCommand{ ExternalServiceID: "app1", Global: true, ServiceAccountID: 1, Permissions: []accesscontrol.Permission{ {Action: "users:read", Scope: "users:id:1"}, {Action: "users:read", Scope: "users:id:2"}, }, }, }, { cmd: accesscontrol.SaveExternalServiceRoleCommand{ ExternalServiceID: "app1", Global: true, ServiceAccountID: 1, Permissions: []accesscontrol.Permission{ {Action: "users:write", Scope: "users:id:1"}, {Action: "users:write", Scope: "users:id:2"}, }, }, }, }, }, { name: "allow switching role from local to global and back", runs: []run{ { cmd: accesscontrol.SaveExternalServiceRoleCommand{ ExternalServiceID: "app1", OrgID: 1, ServiceAccountID: 1, Permissions: []accesscontrol.Permission{ {Action: "users:read", Scope: "users:id:1"}, {Action: "users:read", Scope: "users:id:2"}, }, }, }, { cmd: accesscontrol.SaveExternalServiceRoleCommand{ ExternalServiceID: "app1", Global: true, ServiceAccountID: 1, Permissions: []accesscontrol.Permission{ {Action: "users:read", Scope: "users:id:1"}, {Action: "users:read", Scope: "users:id:2"}, }, }, }, { cmd: accesscontrol.SaveExternalServiceRoleCommand{ ExternalServiceID: "app1", OrgID: 1, ServiceAccountID: 1, Permissions: []accesscontrol.Permission{ {Action: "users:read", Scope: "users:id:1"}, {Action: "users:read", Scope: "users:id:2"}, }, }, }, }, }, { name: "edge case - remove all permissions", runs: []run{ { cmd: accesscontrol.SaveExternalServiceRoleCommand{ ExternalServiceID: "app1", Global: true, ServiceAccountID: 1, Permissions: []accesscontrol.Permission{ {Action: "users:read", Scope: "users:id:1"}, {Action: "users:read", Scope: "users:id:2"}, }, }, }, { cmd: accesscontrol.SaveExternalServiceRoleCommand{ ExternalServiceID: "app1", Global: true, ServiceAccountID: 1, Permissions: []accesscontrol.Permission{}, }, }, }, }, { name: "edge case - reassign to another service account", runs: []run{ { cmd: accesscontrol.SaveExternalServiceRoleCommand{ ExternalServiceID: "app1", Global: true, ServiceAccountID: 1, }, }, { cmd: accesscontrol.SaveExternalServiceRoleCommand{ ExternalServiceID: "app1", Global: true, ServiceAccountID: 2, }, wantErr: true, }, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx := context.Background() s := &AccessControlStore{ sql: db.InitTestDB(t), } for i := range tt.runs { err := s.SaveExternalServiceRole(ctx, tt.runs[i].cmd) if tt.runs[i].wantErr { require.Error(t, err) continue } require.NoError(t, err) errDBSession := s.sql.WithDbSession(ctx, func(sess *db.Session) error { storedRole, err := getRoleByUID(ctx, sess, accesscontrol.PrefixedRoleUID(extServiceRoleName(tt.runs[i].cmd.ExternalServiceID))) require.NoError(t, err) require.NotNil(t, storedRole) require.Equal(t, tt.runs[i].cmd.Global, storedRole.Global(), "Incorrect global state of the role") require.Equal(t, tt.runs[i].cmd.OrgID, storedRole.OrgID, "Incorrect OrgID of the role") storedPerm, err := getRolePermissions(ctx, sess, storedRole.ID) require.NoError(t, err) for i := range storedPerm { storedPerm[i] = accesscontrol.Permission{Action: storedPerm[i].Action, Scope: storedPerm[i].Scope} } require.ElementsMatch(t, tt.runs[i].cmd.Permissions, storedPerm) var assignment accesscontrol.UserRole has, err := sess.Where("role_id = ? AND user_id = ?", storedRole.ID, tt.runs[i].cmd.ServiceAccountID).Get(&assignment) require.NoError(t, err) require.True(t, has) require.Equal(t, tt.runs[i].cmd.Global, assignment.OrgID == accesscontrol.GlobalOrgID, "Incorrect global state of the assignment") require.Equal(t, tt.runs[i].cmd.OrgID, assignment.OrgID, "Incorrect OrgID for the role assignment") return nil }) require.NoError(t, errDBSession) } }) } } func TestAccessControlStore_DeleteExternalServiceRole(t *testing.T) { extID := "app1" tests := []struct { name string init func(t *testing.T, ctx context.Context, s *AccessControlStore) id string wantErr bool }{ { name: "delete no role", id: extID, wantErr: false, }, { name: "delete local role", init: func(t *testing.T, ctx context.Context, s *AccessControlStore) { errSave := s.SaveExternalServiceRole(ctx, accesscontrol.SaveExternalServiceRoleCommand{ OrgID: 2, ExternalServiceID: extID, ServiceAccountID: 3, Permissions: []accesscontrol.Permission{ {Action: "users:read", Scope: "users:id:1"}, {Action: "users:write", Scope: "users:id:1"}, }, }) require.NoError(t, errSave) }, id: extID, wantErr: false, }, { name: "delete global role", init: func(t *testing.T, ctx context.Context, s *AccessControlStore) { errSave := s.SaveExternalServiceRole(ctx, accesscontrol.SaveExternalServiceRoleCommand{ Global: true, ExternalServiceID: extID, ServiceAccountID: 3, Permissions: []accesscontrol.Permission{ {Action: "users:read", Scope: "users:id:1"}, {Action: "users:write", Scope: "users:id:1"}, }, }) require.NoError(t, errSave) }, id: extID, wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx := context.Background() s := &AccessControlStore{ sql: db.InitTestDB(t), } if tt.init != nil { tt.init(t, ctx, s) } roleID := int64(-1) err := s.sql.WithDbSession(ctx, func(sess *db.Session) error { role, err := getRoleByUID(ctx, sess, accesscontrol.PrefixedRoleUID(extServiceRoleName(tt.id))) if err != nil && !errors.Is(err, accesscontrol.ErrRoleNotFound) { return err } if role != nil { roleID = role.ID } return nil }) require.NoError(t, err) err = s.DeleteExternalServiceRole(ctx, tt.id) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) // Only check removal if the role existed before if roleID == -1 { return } // Assignments should be deleted _ = s.sql.WithDbSession(ctx, func(sess *db.Session) error { var assignment accesscontrol.UserRole count, err := sess.Where("role_id = ?", roleID).Count(&assignment) require.NoError(t, err) require.Zero(t, count) return nil }) // Permissions should be deleted _ = s.sql.WithDbSession(ctx, func(sess *db.Session) error { var permission accesscontrol.Permission count, err := sess.Where("role_id = ?", roleID).Count(&permission) require.NoError(t, err) require.Zero(t, count) return nil }) // Role should be deleted _ = s.sql.WithDbSession(ctx, func(sess *db.Session) error { storedRole, err := getRoleByUID(ctx, sess, accesscontrol.PrefixedRoleUID(extServiceRoleName(tt.id))) require.ErrorIs(t, err, accesscontrol.ErrRoleNotFound) require.Nil(t, storedRole) return nil }) }) } }
pkg/services/accesscontrol/database/externalservices_test.go
0
https://github.com/grafana/grafana/commit/95b48339f89c7d267bce7d894404d26ccd75d0e3
[ 0.00017722102347761393, 0.00017287702939938754, 0.00016854246496222913, 0.00017317237507086247, 0.000001710383003228344 ]
{ "id": 3, "code_window": [ "\tFlagDashboardSceneForViewers = \"dashboardSceneForViewers\"\n", "\n", "\t// FlagPanelFilterVariable\n", "\t// Enables use of the `systemPanelFilterVar` variable to filter panels in a dashboard\n", "\tFlagPanelFilterVariable = \"panelFilterVariable\"\n", ")" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep" ], "after_edit": [ "\n", "\t// FlagPdfTables\n", "\t// Enables generating table data as PDF in reporting\n", "\tFlagPdfTables = \"pdfTables\"\n" ], "file_path": "pkg/services/featuremgmt/toggles_gen.go", "type": "add", "edit_start_line_idx": 572 }
/* Prometheus internal models */ import { AlertState, DataSourceInstanceSettings } from '@grafana/data'; import { Annotations, GrafanaAlertState, GrafanaAlertStateWithReason, Labels, mapStateWithReasonToBaseState, PromAlertingRuleState, PromRuleType, RulerRuleDTO, RulerRuleGroupDTO, } from './unified-alerting-dto'; export type Alert = { activeAt: string; annotations: { [key: string]: string }; labels: { [key: string]: string }; state: Exclude<PromAlertingRuleState | GrafanaAlertStateWithReason, PromAlertingRuleState.Inactive>; value: string; }; export function hasAlertState(alert: Alert, state: PromAlertingRuleState | GrafanaAlertState): boolean { return mapStateWithReasonToBaseState(alert.state) === state; } interface RuleBase { health: string; name: string; query: string; lastEvaluation?: string; evaluationTime?: number; lastError?: string; } export interface AlertingRule extends RuleBase { alerts?: Alert[]; labels: { [key: string]: string; }; annotations?: { [key: string]: string; }; state: PromAlertingRuleState; type: PromRuleType.Alerting; totals?: Partial<Record<Lowercase<GrafanaAlertState>, number>>; totalsFiltered?: Partial<Record<Lowercase<GrafanaAlertState>, number>>; activeAt?: string; // ISO timestamp } export interface RecordingRule extends RuleBase { type: PromRuleType.Recording; labels?: { [key: string]: string; }; } export type Rule = AlertingRule | RecordingRule; export type BaseRuleGroup = { name: string }; type TotalsWithoutAlerting = Exclude<AlertInstanceTotalState, AlertInstanceTotalState.Alerting>; enum FiringTotal { Firing = 'firing', } export interface RuleGroup { name: string; interval: number; rules: Rule[]; // totals only exist for Grafana Managed rules totals?: Partial<Record<TotalsWithoutAlerting | FiringTotal, number>>; } export interface RuleNamespace { dataSourceName: string; name: string; groups: RuleGroup[]; } export interface RulesSourceResult { dataSourceName: string; error?: unknown; namespaces?: RuleNamespace[]; } export type RulesSource = DataSourceInstanceSettings | 'grafana'; // combined prom and ruler result export interface CombinedRule { name: string; query: string; labels: Labels; annotations: Annotations; promRule?: Rule; rulerRule?: RulerRuleDTO; group: CombinedRuleGroup; namespace: CombinedRuleNamespace; instanceTotals: AlertInstanceTotals; filteredInstanceTotals: AlertInstanceTotals; } // export type AlertInstanceState = PromAlertingRuleState | 'nodata' | 'error'; export enum AlertInstanceTotalState { Alerting = 'alerting', Pending = 'pending', Normal = 'inactive', NoData = 'nodata', Error = 'error', } export type AlertInstanceTotals = Partial<Record<AlertInstanceTotalState, number>>; // AlertGroupTotals also contain the amount of recording and paused rules export type AlertGroupTotals = Partial<Record<AlertInstanceTotalState | 'paused' | 'recording', number>>; export interface CombinedRuleGroup { name: string; interval?: string; source_tenants?: string[]; rules: CombinedRule[]; totals: AlertGroupTotals; } export interface CombinedRuleNamespace { rulesSource: RulesSource; name: string; groups: CombinedRuleGroup[]; } export interface RuleWithLocation<T = RulerRuleDTO> { ruleSourceName: string; namespace: string; group: RulerRuleGroupDTO; rule: T; } export interface CombinedRuleWithLocation extends CombinedRule { dataSourceName: string; namespaceName: string; groupName: string; } export interface PromRuleWithLocation { rule: AlertingRule; dataSourceName: string; namespaceName: string; groupName: string; } export interface CloudRuleIdentifier { ruleSourceName: string; namespace: string; groupName: string; ruleName: string; rulerRuleHash: string; } export interface GrafanaRuleIdentifier { ruleSourceName: 'grafana'; uid: string; } // Rule read directly from Prometheus without existing in the ruler API export interface PrometheusRuleIdentifier { ruleSourceName: string; namespace: string; groupName: string; ruleName: string; ruleHash: string; } export type RuleIdentifier = CloudRuleIdentifier | GrafanaRuleIdentifier | PrometheusRuleIdentifier; export interface FilterState { queryString?: string; dataSource?: string; alertState?: string; groupBy?: string[]; ruleType?: string; } export interface SilenceFilterState { queryString?: string; silenceState?: string; } interface EvalMatch { metric: string; tags?: Record<string, string>; value: number; } export interface StateHistoryItemData { noData?: boolean; evalMatches?: EvalMatch[]; } export interface StateHistoryItem { id: number; alertId: number; alertName: string; dashboardId: number; panelId: number; userId: number; newState: AlertState; prevState: AlertState; created: number; updated: number; time: number; timeEnd: number; text: string; tags: string[]; login: string; email: string; avatarUrl: string; data: StateHistoryItemData; } export interface RulerDataSourceConfig { dataSourceName: string; apiVersion: 'legacy' | 'config'; } export interface PromBasedDataSource { name: string; id: string | number; rulerConfig?: RulerDataSourceConfig; } export interface PaginationProps { itemsPerPage: number; }
public/app/types/unified-alerting.ts
0
https://github.com/grafana/grafana/commit/95b48339f89c7d267bce7d894404d26ccd75d0e3
[ 0.0003484306507743895, 0.00018296010966878384, 0.00016809118096716702, 0.00017508755263406783, 0.000035121451219310984 ]
{ "id": 0, "code_window": [ " const baseAnimation = createAnimation()\n", " .addElement(baseEl)\n", " .easing('cubic-bezier(0.32,0.72,0,1)')\n", " .duration(500)\n", " .beforeAddClass('show-modal')\n", " .addAnimation([backdropAnimation, wrapperAnimation]);\n", "\n", " if (presentingEl) {\n", " /**\n", " * Fallback for browsers that does not support `max()` (ex: Firefox)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "core/src/components/modal/animations/ios.enter.ts", "type": "replace", "edit_start_line_idx": 29 }
import { Component, ComponentInterface, Element, Event, EventEmitter, Host, Method, Prop, h } from '@stencil/core'; import { config } from '../../global/config'; import { getIonMode } from '../../global/ionic-global'; import { Animation, AnimationBuilder, ComponentProps, ComponentRef, FrameworkDelegate, Gesture, OverlayEventDetail, OverlayInterface } from '../../interface'; import { attachComponent, detachComponent } from '../../utils/framework-delegate'; import { BACKDROP, activeAnimations, dismiss, eventMethod, prepareOverlay, present } from '../../utils/overlays'; import { getClassMap } from '../../utils/theme'; import { deepReady } from '../../utils/transition'; import { iosEnterAnimation } from './animations/ios.enter'; import { iosLeaveAnimation } from './animations/ios.leave'; import { mdEnterAnimation } from './animations/md.enter'; import { mdLeaveAnimation } from './animations/md.leave'; import { createSwipeToCloseGesture } from './gestures/swipe-to-close'; /** * @virtualProp {"ios" | "md"} mode - The mode determines which platform styles to use. */ @Component({ tag: 'ion-modal', styleUrls: { ios: 'modal.ios.scss', md: 'modal.md.scss' }, scoped: true }) export class Modal implements ComponentInterface, OverlayInterface { private gesture?: Gesture; // Reference to the user's provided modal content private usersElement?: HTMLElement; // Whether or not modal is being dismissed via gesture private gestureAnimationDismissing = false; presented = false; animation?: Animation; mode = getIonMode(this); @Element() el!: HTMLIonModalElement; /** @internal */ @Prop() overlayIndex!: number; /** @internal */ @Prop() delegate?: FrameworkDelegate; /** * If `true`, the keyboard will be automatically dismissed when the overlay is presented. */ @Prop() keyboardClose = true; /** * Animation to use when the modal is presented. */ @Prop() enterAnimation?: AnimationBuilder; /** * Animation to use when the modal is dismissed. */ @Prop() leaveAnimation?: AnimationBuilder; /** * The component to display inside of the modal. */ @Prop() component!: ComponentRef; /** * The data to pass to the modal component. */ @Prop() componentProps?: ComponentProps; /** * Additional classes to apply for custom CSS. If multiple classes are * provided they should be separated by spaces. */ @Prop() cssClass?: string | string[]; /** * If `true`, the modal will be dismissed when the backdrop is clicked. */ @Prop() backdropDismiss = true; /** * If `true`, a backdrop will be displayed behind the modal. */ @Prop() showBackdrop = true; /** * If `true`, the modal will animate. */ @Prop() animated = true; /** * If `true`, the modal can be swiped to dismiss. Only applies in iOS mode. */ @Prop() swipeToClose = false; /** * The element that presented the modal. This is used for card presentation effects * and for stacking multiple modals on top of each other. Only applies in iOS mode. */ @Prop() presentingElement?: HTMLElement; /** * Emitted after the modal has presented. */ @Event({ eventName: 'ionModalDidPresent' }) didPresent!: EventEmitter<void>; /** * Emitted before the modal has presented. */ @Event({ eventName: 'ionModalWillPresent' }) willPresent!: EventEmitter<void>; /** * Emitted before the modal has dismissed. */ @Event({ eventName: 'ionModalWillDismiss' }) willDismiss!: EventEmitter<OverlayEventDetail>; /** * Emitted after the modal has dismissed. */ @Event({ eventName: 'ionModalDidDismiss' }) didDismiss!: EventEmitter<OverlayEventDetail>; constructor() { prepareOverlay(this.el); } /** * Present the modal overlay after it has been created. */ @Method() async present(): Promise<void> { if (this.presented) { return; } const container = this.el.querySelector(`.modal-wrapper`); if (!container) { throw new Error('container is undefined'); } const componentProps = { ...this.componentProps, modal: this.el }; this.usersElement = await attachComponent(this.delegate, container, this.component, ['ion-page'], componentProps); await deepReady(this.usersElement); await present(this, 'modalEnter', iosEnterAnimation, mdEnterAnimation, this.presentingElement); const mode = getIonMode(this); if (this.swipeToClose && mode === 'ios') { // All of the elements needed for the swipe gesture // should be in the DOM and referenced by now, except // for the presenting el const animationBuilder = this.leaveAnimation || config.get('modalLeave', iosLeaveAnimation); const ani = this.animation = animationBuilder(this.el, this.presentingElement); this.gesture = createSwipeToCloseGesture( this.el, ani, () => { /** * While the gesture animation is finishing * it is possible for a user to tap the backdrop. * This would result in the dismiss animation * being played again. Typically this is avoided * by setting `presented = false` on the overlay * component; however, we cannot do that here as * that would prevent the element from being * removed from the DOM. */ this.gestureAnimationDismissing = true; this.animation!.onFinish(async () => { await this.dismiss(undefined, 'gesture'); this.gestureAnimationDismissing = false; }); }, ); this.gesture.enable(true); } } /** * Dismiss the modal overlay after it has been presented. * * @param data Any data to emit in the dismiss events. * @param role The role of the element that is dismissing the modal. For example, 'cancel' or 'backdrop'. */ @Method() async dismiss(data?: any, role?: string): Promise<boolean> { if (this.gestureAnimationDismissing && role !== 'gesture') { return false; } const enteringAnimation = activeAnimations.get(this) || []; const dismissed = await dismiss(this, data, role, 'modalLeave', iosLeaveAnimation, mdLeaveAnimation, this.presentingElement); if (dismissed) { await detachComponent(this.delegate, this.usersElement); if (this.animation) { this.animation.destroy(); } enteringAnimation.forEach(ani => ani.destroy()); } this.animation = undefined; return dismissed; } /** * Returns a promise that resolves when the modal did dismiss. */ @Method() onDidDismiss(): Promise<OverlayEventDetail> { return eventMethod(this.el, 'ionModalDidDismiss'); } /** * Returns a promise that resolves when the modal will dismiss. */ @Method() onWillDismiss(): Promise<OverlayEventDetail> { return eventMethod(this.el, 'ionModalWillDismiss'); } private onBackdropTap = () => { this.dismiss(undefined, BACKDROP); } private onDismiss = (ev: UIEvent) => { ev.stopPropagation(); ev.preventDefault(); this.dismiss(); } private onLifecycle = (modalEvent: CustomEvent) => { const el = this.usersElement; const name = LIFECYCLE_MAP[modalEvent.type]; if (el && name) { const ev = new CustomEvent(name, { bubbles: false, cancelable: false, detail: modalEvent.detail }); el.dispatchEvent(ev); } } render() { const mode = getIonMode(this); return ( <Host no-router aria-modal="true" class={{ [mode]: true, [`modal-card`]: this.presentingElement !== undefined && mode === 'ios', ...getClassMap(this.cssClass) }} style={{ zIndex: `${20000 + this.overlayIndex}`, }} onIonBackdropTap={this.onBackdropTap} onIonDismiss={this.onDismiss} onIonModalDidPresent={this.onLifecycle} onIonModalWillPresent={this.onLifecycle} onIonModalWillDismiss={this.onLifecycle} onIonModalDidDismiss={this.onLifecycle} > <ion-backdrop visible={this.showBackdrop} tappable={this.backdropDismiss}/> <div role="dialog" class="modal-wrapper" > </div> </Host> ); } } const LIFECYCLE_MAP: any = { 'ionModalDidPresent': 'ionViewDidEnter', 'ionModalWillPresent': 'ionViewWillEnter', 'ionModalWillDismiss': 'ionViewWillLeave', 'ionModalDidDismiss': 'ionViewDidLeave', };
core/src/components/modal/modal.tsx
1
https://github.com/ionic-team/ionic-framework/commit/14ac8ae24cab29b8c93b9271ad999ef07aeab98f
[ 0.003917063120752573, 0.0003755515208467841, 0.0001637832901906222, 0.00017397971532773226, 0.0006864604656584561 ]
{ "id": 0, "code_window": [ " const baseAnimation = createAnimation()\n", " .addElement(baseEl)\n", " .easing('cubic-bezier(0.32,0.72,0,1)')\n", " .duration(500)\n", " .beforeAddClass('show-modal')\n", " .addAnimation([backdropAnimation, wrapperAnimation]);\n", "\n", " if (presentingEl) {\n", " /**\n", " * Fallback for browsers that does not support `max()` (ex: Firefox)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "core/src/components/modal/animations/ios.enter.ts", "type": "replace", "edit_start_line_idx": 29 }
<!DOCTYPE html> <html dir="ltr"> <head> <meta charset="UTF-8"> <title>Select - Single Value</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link href="../../../../../css/ionic.bundle.css" rel="stylesheet"> <link href="../../../../../scripts/testing/styles.css" rel="stylesheet"> <script src="../../../../../scripts/testing/scripts.js"></script> <script nomodule src="../../../../../dist/ionic/ionic.js"></script> <script type="module" src="../../../../../dist/ionic/ionic.esm.js"></script></head> <body> <ion-app> <ion-header> <ion-toolbar> <ion-title>Select Item: Single Value</ion-title> </ion-toolbar> </ion-header> <ion-content class="outer-content"> <ion-item> <ion-label position="stacked">Gender</ion-label> <ion-select id="gender"> <ion-select-option value="f">Female</ion-select-option> <ion-select-option value="m">Male</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Popover</ion-label> <ion-select interface="popover"> <ion-select-option value="select">Select</ion-select-option> <ion-select-option value="action">Action Sheet</ion-select-option> <ion-select-option value="popover">Popover</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Gaming</ion-label> <ion-select id="gaming"> <ion-select-option value="nes">NES</ion-select-option> <ion-select-option value="n64">Nintendo64</ion-select-option> <ion-select-option value="ps">PlayStation</ion-select-option> <ion-select-option value="genesis">Sega Genesis</ion-select-option> <ion-select-option value="saturn">Sega Saturn</ion-select-option> <ion-select-option value="snes">SNES</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label position="floating">Operating System</ion-label> <ion-select id="os"> <ion-select-option value="dos">DOS</ion-select-option> <ion-select-option value="lunix">Linux</ion-select-option> <ion-select-option value="mac7">Mac OS 7</ion-select-option> <ion-select-option value="mac8">Mac OS 8</ion-select-option> <ion-select-option value="win3.1">Windows 3.1</ion-select-option> <ion-select-option value="win95">Windows 95</ion-select-option> <ion-select-option value="win98">Windows 98</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Notifications</ion-label> <ion-select id="notifications"> <ion-select-option value="enable">Enable</ion-select-option> <ion-select-option value="mute">Mute</ion-select-option> <ion-select-option value="mute_week">Mute for a week</ion-select-option> <ion-select-option value="mute_year" (ionSelect)="notificationSelect($event)">Mute for a year</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Edit</ion-label> <ion-select> <ion-select-option value="add_reaction">Add Reaction</ion-select-option> <ion-select-option value="copy_text">Copy Text</ion-select-option> <ion-select-option value="share_text">Share Text</ion-select-option> <ion-select-option value="copy_link">Copy Link to Message</ion-select-option> <ion-select-option value="remind_me">Remind Me</ion-select-option> <ion-select-option value="pin_file">Pin File</ion-select-option> <ion-select-option value="star_file">Star File</ion-select-option> <ion-select-option value="mark_unread">Mark Unread</ion-select-option> <ion-select-option value="edit_title">Edit Title</ion-select-option> <ion-select-option value="save_image">Save Image</ion-select-option> <ion-select-option value="copy_image">Copy Image</ion-select-option> <ion-select-option value="delete_file">Delete File</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Music</ion-label> <ion-select id="music" placeholder="Select Music"> <ion-select-option>Alice in Chains</ion-select-option> <ion-select-option>Green Day</ion-select-option> <ion-select-option>Nirvana</ion-select-option> <ion-select-option>Pearl Jam</ion-select-option> <ion-select-option>Smashing Pumpkins</ion-select-option> <ion-select-option>Soundgarden</ion-select-option> <ion-select-option (ionSelect)="musicSelect($event)">Stone Temple Pilots</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Date</ion-label> <ion-select id="month"> <ion-select-option value="01">January</ion-select-option> <ion-select-option value="02">February</ion-select-option> <ion-select-option value="03">March</ion-select-option> <ion-select-option value="04">April</ion-select-option> <ion-select-option value="05">May</ion-select-option> <ion-select-option value="06">June</ion-select-option> <ion-select-option value="07">July</ion-select-option> <ion-select-option value="08">August</ion-select-option> <ion-select-option value="09">September</ion-select-option> <ion-select-option value="10">October</ion-select-option> <ion-select-option value="11">November</ion-select-option> <ion-select-option value="12">December</ion-select-option> </ion-select> <ion-select id="year"> </ion-select> </ion-item> <ion-item> <ion-label>Statuses</ion-label> <ion-select id="status" value="selected"> <ion-select-option value="selected">Selected</ion-select-option> <ion-select-option value="default">Default</ion-select-option> <ion-select-option value="disabled" disabled="true">Disabled</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Currency</ion-label> <ion-select id="currency"> </ion-select> </ion-item> <ion-button onclick="resetGender()">Reset Gender</ion-button> <p aria-hidden="true" class="ion-padding"> <code>gender: <span id="genderResult"></span></code> <br> <code>gaming: <span id="gamingResult"></span></code> <br> <code>os: <span id="osResult"></span></code> <br> <code>notifications: <span id="notificationsResult"></span></code> <br> <code>music: <span id="musicResult"></span></code> <br> <code>date: <span id="monthResult"></span>/<span id="yearResult"></span></code> <br> <code>status: <span id="statusResult"></span></code> <br> <code>currency: <span id="currencyResult"></span></code> <br> </p> </ion-content> <style> .outer-content { --background: #f2f2f2; } </style> <script> customElements.whenDefined('ion-select-option').then(() => { let selects = document.querySelectorAll('ion-select'); selects.forEach(function (select) { select.addEventListener("ionChange", function () { setResults(select); }); }); function setResults(select) { if (select.id) { var resultsEl = document.getElementById(select.id + 'Result'); if (resultsEl) { var value = typeof select.value === 'object' ? JSON.stringify(select.value) : select.value; resultsEl.innerHTML = value; } } } var os = document.getElementById('os'); os.value = 'win3.1'; setResults(os); var month = document.getElementById('month'); month.value = '12'; setResults(month); var year = document.getElementById('year'); var years = [1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999]; for (var i = 0; i < years.length; i++) { var option = document.createElement('ion-select-option'); option.value = option.innerHTML = years[i]; year.appendChild(option); } year.componentOnReady().then(() => { year.value = 1994; }); setResults(year); var currencies = [ { symbol: '$', code: 'USD', name: 'US Dollar' }, { symbol: '€', code: 'EUR', name: 'Euro' }, { symbol: '£', code: 'FKP', name: 'Falkland Islands Pound' }, { symbol: '¢', code: 'GHS', name: 'Ghana Cedi' } ]; var currency = document.getElementById('currency'); for (var i = 0; i < currencies.length; i++) { var option = document.createElement('ion-select-option'); option.value = currencies[i]; option.innerHTML = `${currencies[i].symbol} (${currencies[i].code}) ${currencies[i].name}`; currency.appendChild(option); } currency.value = currencies[0]; currency.selectedText = getCurrencySelectedText(); setResults(currency); currency.addEventListener('ionChange', function (ev) { currency.selectedText = getCurrencySelectedText(); }); function getCurrencySelectedText() { return currency.value.symbol; } }); function resetGender() { var gender = document.getElementById('gender'); gender.value = null; } </script> </ion-app> </body> </html>
core/src/components/select/test/single-value/index.html
0
https://github.com/ionic-team/ionic-framework/commit/14ac8ae24cab29b8c93b9271ad999ef07aeab98f
[ 0.000176319939782843, 0.00017315444711130112, 0.00016658984532114118, 0.00017361663049086928, 0.00000212630811802228 ]
{ "id": 0, "code_window": [ " const baseAnimation = createAnimation()\n", " .addElement(baseEl)\n", " .easing('cubic-bezier(0.32,0.72,0,1)')\n", " .duration(500)\n", " .beforeAddClass('show-modal')\n", " .addAnimation([backdropAnimation, wrapperAnimation]);\n", "\n", " if (presentingEl) {\n", " /**\n", " * Fallback for browsers that does not support `max()` (ex: Firefox)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "core/src/components/modal/animations/ios.enter.ts", "type": "replace", "edit_start_line_idx": 29 }
<!DOCTYPE html> <html dir="ltr"> <head> <meta charset="UTF-8"> <title>Button - Standalone</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link href="../../../../../css/core.css" rel="stylesheet"> <link href="../../../../../scripts/testing/styles.css" rel="stylesheet"> <script src="../../../../../scripts/testing/scripts.js"></script> <script nomodule src="../../../../../dist/ionic/ionic.js"></script> <script type="module" src="../../../../../dist/ionic/ionic.esm.js"></script></head> <body> <h3>Default</h3> <p> <ion-button>Default</ion-button> <ion-button><ion-icon slot="icon-only" name="star"></ion-icon></ion-button> <ion-button><ion-icon slot="start" name="pin"></ion-icon>Map</ion-button> <ion-button shape="round">Round</ion-button> <ion-button fill="outline">Outline</ion-button> <ion-button fill="clear">Clear</ion-button> <ion-button fill="outline" expand="full">Full Outline Full Outline Full Outline Full Outline Full Outline Full Outline Full Outline</ion-button> <ion-button fill="clear" expand="block">Block Clear</ion-button> </p> <h3>Round button combinations</h3> <p> <ion-button shape="round" size="small">Round & Small</ion-button> <ion-button shape="round" size="large">Round & Large</ion-button> <ion-button shape="round" fill="outline">Round & Outline</ion-button> </p> <h3>Colors</h3> <p> <ion-button color="primary">Primary</ion-button> <ion-button color="secondary">Secondary</ion-button> <ion-button color="tertiary">Tertiary</ion-button> <ion-button fill="outline" color="success">Success Outline</ion-button> <ion-button fill="clear" color="warning">Warning Clear</ion-button> <ion-button color="danger">Danger</ion-button> <ion-button color="light">Light</ion-button> <ion-button expand="block" fill="outline" color="medium">Medium Outline</ion-button> <ion-button expand="full" fill="clear" color="dark">Dark Clear</ion-button> </p> <h3>Custom</h3> <!-- Custom Font --> <ion-button class="wide">wide</ion-button> <ion-button class="large">large</ion-button> <ion-button class="round">rounded</ion-button> <!-- Custom Colors --> <ion-button class="custom">custom</ion-button> <ion-button class="custom ion-activated ion-focused">custom.focused</ion-button> <ion-button class="custom ion-activated">custom.activated</ion-button> <ion-button color="secondary" class="custom">custom w/ secondary</ion-button> <ion-button fill="clear" class="medium">custom medium</ion-button> <ion-toolbar> <ion-buttons slot="start"> <ion-button>Default</ion-button> </ion-buttons> <ion-title>Bar</ion-title> <ion-buttons slot="end"> <ion-button color="secondary">Secondary</ion-button> </ion-buttons> </ion-toolbar> <ion-toolbar> <ion-buttons slot="start"> <ion-button class="custom">Custom</ion-button> <ion-button class="custom ion-activated">Custom.a</ion-button> </ion-buttons> <ion-title>Bar</ion-title> <ion-buttons slot="end"> <ion-button color="secondary" class="custom">Custom Secondary</ion-button> </ion-buttons> </ion-toolbar> <style> .wide { width: 100px; } .large { font-weight: normal; font-size: 24px; } .round { width: 60px; height: 60px; --border-radius: 50%; --vertical-align: middle; --padding-start: 10px; --padding-end: 10px; } .custom { --background: lightpink; --background-hover: #ffb6c1; --background-activated: green; --color: #222; --color-activated: white; --opacity: 1; } .medium { --color: #989aa2; --background-hover: #989aa2; } </style> </body> </html>
core/src/components/button/test/standalone/index.html
0
https://github.com/ionic-team/ionic-framework/commit/14ac8ae24cab29b8c93b9271ad999ef07aeab98f
[ 0.00017867921269498765, 0.0001738206046866253, 0.0001680331479292363, 0.00017392108566127717, 0.0000025045837901416235 ]
{ "id": 0, "code_window": [ " const baseAnimation = createAnimation()\n", " .addElement(baseEl)\n", " .easing('cubic-bezier(0.32,0.72,0,1)')\n", " .duration(500)\n", " .beforeAddClass('show-modal')\n", " .addAnimation([backdropAnimation, wrapperAnimation]);\n", "\n", " if (presentingEl) {\n", " /**\n", " * Fallback for browsers that does not support `max()` (ex: Firefox)\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "core/src/components/modal/animations/ios.enter.ts", "type": "replace", "edit_start_line_idx": 29 }
## Single Selection ```html <ion-list> <ion-list-header> <ion-label> Single Selection </ion-label> </ion-list-header> <ion-item> <ion-label>Gender</ion-label> <ion-select placeholder="Select One"> <ion-select-option value="f">Female</ion-select-option> <ion-select-option value="m">Male</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Hair Color</ion-label> <ion-select value="brown" okText="Okay" cancelText="Dismiss"> <ion-select-option value="brown">Brown</ion-select-option> <ion-select-option value="blonde">Blonde</ion-select-option> <ion-select-option value="black">Black</ion-select-option> <ion-select-option value="red">Red</ion-select-option> </ion-select> </ion-item> </ion-list> ``` ## Multiple Selection ```html <ion-list> <ion-list-header> <ion-label> Multiple Selection </ion-label> </ion-list-header> <ion-item> <ion-label>Toppings</ion-label> <ion-select multiple="true" cancelText="Nah" okText="Okay!"> <ion-select-option value="bacon">Bacon</ion-select-option> <ion-select-option value="olives">Black Olives</ion-select-option> <ion-select-option value="xcheese">Extra Cheese</ion-select-option> <ion-select-option value="peppers">Green Peppers</ion-select-option> <ion-select-option value="mushrooms">Mushrooms</ion-select-option> <ion-select-option value="onions">Onions</ion-select-option> <ion-select-option value="pepperoni">Pepperoni</ion-select-option> <ion-select-option value="pineapple">Pineapple</ion-select-option> <ion-select-option value="sausage">Sausage</ion-select-option> <ion-select-option value="Spinach">Spinach</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Pets</ion-label> <ion-select multiple="true" [value]="['bird', 'dog']"> <ion-select-option value="bird">Bird</ion-select-option> <ion-select-option value="cat">Cat</ion-select-option> <ion-select-option value="dog">Dog</ion-select-option> <ion-select-option value="honeybadger">Honey Badger</ion-select-option> </ion-select> </ion-item> </ion-list> ``` ## Objects as Values ```html <ion-list> <ion-list-header> <ion-label> Objects as Values (compareWith) </ion-label> </ion-list-header> <ion-item> <ion-label>Users</ion-label> <ion-select [compareWith]="compareWith"> <ion-select-option *ngFor="let user of users">{{user.first + ' ' + user.last}}</ion-select-option> </ion-select> </ion-item> </ion-list> ``` ```typescript import { Component } from '@angular/core'; @Component({ selector: 'select-example', templateUrl: 'select-example.html', styleUrls: ['./select-example.css'], }) export class SelectExample { users: any[] = [ { id: 1, first: 'Alice', last: 'Smith', }, { id: 2, first: 'Bob', last: 'Davis', }, { id: 3, first: 'Charlie', last: 'Rosenburg', } ]; compareWithFn = (o1, o2) => { return o1 && o2 ? o1.id === o2.id : o1 === o2; }; compareWith = compareWithFn; } ``` ## Interface Options ```html <ion-list> <ion-list-header> <ion-label> Interface Options </ion-label> </ion-list-header> <ion-item> <ion-label>Alert</ion-label> <ion-select [interfaceOptions]="customAlertOptions" interface="alert" multiple="true" placeholder="Select One"> <ion-select-option value="bacon">Bacon</ion-select-option> <ion-select-option value="olives">Black Olives</ion-select-option> <ion-select-option value="xcheese">Extra Cheese</ion-select-option> <ion-select-option value="peppers">Green Peppers</ion-select-option> <ion-select-option value="mushrooms">Mushrooms</ion-select-option> <ion-select-option value="onions">Onions</ion-select-option> <ion-select-option value="pepperoni">Pepperoni</ion-select-option> <ion-select-option value="pineapple">Pineapple</ion-select-option> <ion-select-option value="sausage">Sausage</ion-select-option> <ion-select-option value="Spinach">Spinach</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Popover</ion-label> <ion-select [interfaceOptions]="customPopoverOptions" interface="popover" placeholder="Select One"> <ion-select-option value="brown">Brown</ion-select-option> <ion-select-option value="blonde">Blonde</ion-select-option> <ion-select-option value="black">Black</ion-select-option> <ion-select-option value="red">Red</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Action Sheet</ion-label> <ion-select [interfaceOptions]="customActionSheetOptions" interface="action-sheet" placeholder="Select One"> <ion-select-option value="red">Red</ion-select-option> <ion-select-option value="purple">Purple</ion-select-option> <ion-select-option value="yellow">Yellow</ion-select-option> <ion-select-option value="orange">Orange</ion-select-option> <ion-select-option value="green">Green</ion-select-option> </ion-select> </ion-item> </ion-list> ``` ```typescript import { Component } from '@angular/core'; @Component({ selector: 'select-example', templateUrl: 'select-example.html', styleUrls: ['./select-example.css'], }) export class SelectExample { customAlertOptions: any = { header: 'Pizza Toppings', subHeader: 'Select your toppings', message: '$1.00 per topping', translucent: true }; customPopoverOptions: any = { header: 'Hair Color', subHeader: 'Select your hair color', message: 'Only select your dominant hair color' }; customActionSheetOptions: any = { header: 'Colors', subHeader: 'Select your favorite color' }; } ```
core/src/components/select/usage/angular.md
0
https://github.com/ionic-team/ionic-framework/commit/14ac8ae24cab29b8c93b9271ad999ef07aeab98f
[ 0.00017530706827528775, 0.00017285384819842875, 0.00016344319737982005, 0.0001735472760628909, 0.0000025079946226469474 ]
{ "id": 1, "code_window": [ " .addElement(baseEl)\n", " .easing('cubic-bezier(0.36,0.66,0.04,1)')\n", " .duration(280)\n", " .beforeAddClass('show-modal')\n", " .addAnimation([backdropAnimation, wrapperAnimation]);\n", "};" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "core/src/components/modal/animations/md.enter.ts", "type": "replace", "edit_start_line_idx": 30 }
import { Animation } from '../../../interface'; import { createAnimation } from '../../../utils/animation/animation'; import { SwipeToCloseDefaults } from '../gestures/swipe-to-close'; /** * iOS Modal Enter Animation for the Card presentation style */ export const iosEnterAnimation = ( baseEl: HTMLElement, presentingEl?: HTMLElement, ): Animation => { // The top translate Y for the presenting element const backdropAnimation = createAnimation() .addElement(baseEl.querySelector('ion-backdrop')!) .fromTo('opacity', 0.01, 'var(--backdrop-opacity)') .beforeStyles({ 'pointer-events': 'none' }) .afterClearStyles(['pointer-events']); const wrapperAnimation = createAnimation() .addElement(baseEl.querySelector('.modal-wrapper')!) .beforeStyles({ 'opacity': 1 }) .fromTo('transform', 'translateY(100vh)', 'translateY(0vh)'); const baseAnimation = createAnimation() .addElement(baseEl) .easing('cubic-bezier(0.32,0.72,0,1)') .duration(500) .beforeAddClass('show-modal') .addAnimation([backdropAnimation, wrapperAnimation]); if (presentingEl) { /** * Fallback for browsers that does not support `max()` (ex: Firefox) * No need to wrry about statusbar padding since engines like Gecko * are not used as the engine for standlone Cordova/Capacitor apps */ const transformOffset = (!CSS.supports('width', 'max(0px, 1px)')) ? '30px' : 'max(30px, var(--ion-safe-area-top))'; const modalTransform = (presentingEl.tagName === 'ION-MODAL' && (presentingEl as HTMLIonModalElement).presentingElement !== undefined) ? '-10px' : transformOffset; const bodyEl = document.body; const toPresentingScale = SwipeToCloseDefaults.MIN_PRESENTING_SCALE; const finalTransform = `translateY(${modalTransform}) scale(${toPresentingScale})`; const presentingAnimation = createAnimation() .beforeStyles({ 'transform': 'translateY(0)', 'transform-origin': 'top center', 'overflow': 'hidden' }) .afterStyles({ 'transform': finalTransform }) .beforeAddWrite(() => bodyEl.style.setProperty('background-color', 'black')) .addElement(presentingEl) .keyframes([ { offset: 0, filter: 'contrast(1)', transform: 'translateY(0px) scale(1)', borderRadius: '0px' }, { offset: 1, filter: 'contrast(0.85)', transform: finalTransform, borderRadius: '10px 10px 0 0' } ]); baseAnimation.addAnimation(presentingAnimation); } return baseAnimation; };
core/src/components/modal/animations/ios.enter.ts
1
https://github.com/ionic-team/ionic-framework/commit/14ac8ae24cab29b8c93b9271ad999ef07aeab98f
[ 0.040206070989370346, 0.0066037653014063835, 0.0001646418240852654, 0.0006177285686135292, 0.013746911659836769 ]
{ "id": 1, "code_window": [ " .addElement(baseEl)\n", " .easing('cubic-bezier(0.36,0.66,0.04,1)')\n", " .duration(280)\n", " .beforeAddClass('show-modal')\n", " .addAnimation([backdropAnimation, wrapperAnimation]);\n", "};" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "core/src/components/modal/animations/md.enter.ts", "type": "replace", "edit_start_line_idx": 30 }
import { Component, NgZone } from '@angular/core'; import { Platform, ModalController, AlertController, ActionSheetController, PopoverController, ToastController, PickerController, MenuController, LoadingController, NavController, DomController, Config } from '@ionic/angular'; @Component({ selector: 'app-providers', templateUrl: './providers.component.html', }) export class ProvidersComponent { isLoaded = false; isReady = false; isResumed = false; isPaused = false; isResized = false; isTesting: boolean = undefined; isDesktop: boolean = undefined; isMobile: boolean = undefined; keyboardHeight = 0; constructor( actionSheetCtrl: ActionSheetController, alertCtrl: AlertController, loadingCtrl: LoadingController, menuCtrl: MenuController, pickerCtrl: PickerController, modalCtrl: ModalController, platform: Platform, popoverCtrl: PopoverController, toastCtrl: ToastController, navCtrl: NavController, domCtrl: DomController, config: Config, zone: NgZone ) { // test all providers load if ( actionSheetCtrl && alertCtrl && loadingCtrl && menuCtrl && pickerCtrl && modalCtrl && platform && popoverCtrl && toastCtrl && navCtrl && domCtrl && config ) { this.isLoaded = true; } // test platform ready() platform.ready().then(() => { NgZone.assertInAngularZone(); this.isReady = true; }); platform.resume.subscribe(() => { console.log('platform:resume'); NgZone.assertInAngularZone(); this.isResumed = true; }); platform.pause.subscribe(() => { console.log('platform:pause'); NgZone.assertInAngularZone(); this.isPaused = true; }); platform.resize.subscribe(() => { console.log('platform:resize'); NgZone.assertInAngularZone(); this.isResized = true; }); this.isDesktop = platform.is('desktop'); this.isMobile = platform.is('mobile'); // test config this.isTesting = config.getBoolean('_testing'); config.set('keyboardHeight', 12345); this.keyboardHeight = config.getNumber('keyboardHeight'); zone.runOutsideAngular(() => { document.dispatchEvent(new CustomEvent('pause')); document.dispatchEvent(new CustomEvent('resume')); window.dispatchEvent(new CustomEvent('resize')); }); } }
angular/test/test-app/src/app/providers/providers.component.ts
0
https://github.com/ionic-team/ionic-framework/commit/14ac8ae24cab29b8c93b9271ad999ef07aeab98f
[ 0.00017895252676680684, 0.00017346051754429936, 0.00016458499885629863, 0.0001752444077283144, 0.000004506689037953038 ]
{ "id": 1, "code_window": [ " .addElement(baseEl)\n", " .easing('cubic-bezier(0.36,0.66,0.04,1)')\n", " .duration(280)\n", " .beforeAddClass('show-modal')\n", " .addAnimation([backdropAnimation, wrapperAnimation]);\n", "};" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "core/src/components/modal/animations/md.enter.ts", "type": "replace", "edit_start_line_idx": 30 }
<!DOCTYPE html> <html dir="ltr"> <head> <meta charset="UTF-8"> <title>Select - Single Value</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link href="../../../../../css/ionic.bundle.css" rel="stylesheet"> <link href="../../../../../scripts/testing/styles.css" rel="stylesheet"> <script src="../../../../../scripts/testing/scripts.js"></script> <script nomodule src="../../../../../dist/ionic/ionic.js"></script> <script type="module" src="../../../../../dist/ionic/ionic.esm.js"></script></head> <body> <ion-app> <ion-header> <ion-toolbar> <ion-title>Select Item: Single Value</ion-title> </ion-toolbar> </ion-header> <ion-content class="outer-content"> <ion-item> <ion-label position="stacked">Gender</ion-label> <ion-select id="gender"> <ion-select-option value="f">Female</ion-select-option> <ion-select-option value="m">Male</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Popover</ion-label> <ion-select interface="popover"> <ion-select-option value="select">Select</ion-select-option> <ion-select-option value="action">Action Sheet</ion-select-option> <ion-select-option value="popover">Popover</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Gaming</ion-label> <ion-select id="gaming"> <ion-select-option value="nes">NES</ion-select-option> <ion-select-option value="n64">Nintendo64</ion-select-option> <ion-select-option value="ps">PlayStation</ion-select-option> <ion-select-option value="genesis">Sega Genesis</ion-select-option> <ion-select-option value="saturn">Sega Saturn</ion-select-option> <ion-select-option value="snes">SNES</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label position="floating">Operating System</ion-label> <ion-select id="os"> <ion-select-option value="dos">DOS</ion-select-option> <ion-select-option value="lunix">Linux</ion-select-option> <ion-select-option value="mac7">Mac OS 7</ion-select-option> <ion-select-option value="mac8">Mac OS 8</ion-select-option> <ion-select-option value="win3.1">Windows 3.1</ion-select-option> <ion-select-option value="win95">Windows 95</ion-select-option> <ion-select-option value="win98">Windows 98</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Notifications</ion-label> <ion-select id="notifications"> <ion-select-option value="enable">Enable</ion-select-option> <ion-select-option value="mute">Mute</ion-select-option> <ion-select-option value="mute_week">Mute for a week</ion-select-option> <ion-select-option value="mute_year" (ionSelect)="notificationSelect($event)">Mute for a year</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Edit</ion-label> <ion-select> <ion-select-option value="add_reaction">Add Reaction</ion-select-option> <ion-select-option value="copy_text">Copy Text</ion-select-option> <ion-select-option value="share_text">Share Text</ion-select-option> <ion-select-option value="copy_link">Copy Link to Message</ion-select-option> <ion-select-option value="remind_me">Remind Me</ion-select-option> <ion-select-option value="pin_file">Pin File</ion-select-option> <ion-select-option value="star_file">Star File</ion-select-option> <ion-select-option value="mark_unread">Mark Unread</ion-select-option> <ion-select-option value="edit_title">Edit Title</ion-select-option> <ion-select-option value="save_image">Save Image</ion-select-option> <ion-select-option value="copy_image">Copy Image</ion-select-option> <ion-select-option value="delete_file">Delete File</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Music</ion-label> <ion-select id="music" placeholder="Select Music"> <ion-select-option>Alice in Chains</ion-select-option> <ion-select-option>Green Day</ion-select-option> <ion-select-option>Nirvana</ion-select-option> <ion-select-option>Pearl Jam</ion-select-option> <ion-select-option>Smashing Pumpkins</ion-select-option> <ion-select-option>Soundgarden</ion-select-option> <ion-select-option (ionSelect)="musicSelect($event)">Stone Temple Pilots</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Date</ion-label> <ion-select id="month"> <ion-select-option value="01">January</ion-select-option> <ion-select-option value="02">February</ion-select-option> <ion-select-option value="03">March</ion-select-option> <ion-select-option value="04">April</ion-select-option> <ion-select-option value="05">May</ion-select-option> <ion-select-option value="06">June</ion-select-option> <ion-select-option value="07">July</ion-select-option> <ion-select-option value="08">August</ion-select-option> <ion-select-option value="09">September</ion-select-option> <ion-select-option value="10">October</ion-select-option> <ion-select-option value="11">November</ion-select-option> <ion-select-option value="12">December</ion-select-option> </ion-select> <ion-select id="year"> </ion-select> </ion-item> <ion-item> <ion-label>Statuses</ion-label> <ion-select id="status" value="selected"> <ion-select-option value="selected">Selected</ion-select-option> <ion-select-option value="default">Default</ion-select-option> <ion-select-option value="disabled" disabled="true">Disabled</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Currency</ion-label> <ion-select id="currency"> </ion-select> </ion-item> <ion-button onclick="resetGender()">Reset Gender</ion-button> <p aria-hidden="true" class="ion-padding"> <code>gender: <span id="genderResult"></span></code> <br> <code>gaming: <span id="gamingResult"></span></code> <br> <code>os: <span id="osResult"></span></code> <br> <code>notifications: <span id="notificationsResult"></span></code> <br> <code>music: <span id="musicResult"></span></code> <br> <code>date: <span id="monthResult"></span>/<span id="yearResult"></span></code> <br> <code>status: <span id="statusResult"></span></code> <br> <code>currency: <span id="currencyResult"></span></code> <br> </p> </ion-content> <style> .outer-content { --background: #f2f2f2; } </style> <script> customElements.whenDefined('ion-select-option').then(() => { let selects = document.querySelectorAll('ion-select'); selects.forEach(function (select) { select.addEventListener("ionChange", function () { setResults(select); }); }); function setResults(select) { if (select.id) { var resultsEl = document.getElementById(select.id + 'Result'); if (resultsEl) { var value = typeof select.value === 'object' ? JSON.stringify(select.value) : select.value; resultsEl.innerHTML = value; } } } var os = document.getElementById('os'); os.value = 'win3.1'; setResults(os); var month = document.getElementById('month'); month.value = '12'; setResults(month); var year = document.getElementById('year'); var years = [1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999]; for (var i = 0; i < years.length; i++) { var option = document.createElement('ion-select-option'); option.value = option.innerHTML = years[i]; year.appendChild(option); } year.componentOnReady().then(() => { year.value = 1994; }); setResults(year); var currencies = [ { symbol: '$', code: 'USD', name: 'US Dollar' }, { symbol: '€', code: 'EUR', name: 'Euro' }, { symbol: '£', code: 'FKP', name: 'Falkland Islands Pound' }, { symbol: '¢', code: 'GHS', name: 'Ghana Cedi' } ]; var currency = document.getElementById('currency'); for (var i = 0; i < currencies.length; i++) { var option = document.createElement('ion-select-option'); option.value = currencies[i]; option.innerHTML = `${currencies[i].symbol} (${currencies[i].code}) ${currencies[i].name}`; currency.appendChild(option); } currency.value = currencies[0]; currency.selectedText = getCurrencySelectedText(); setResults(currency); currency.addEventListener('ionChange', function (ev) { currency.selectedText = getCurrencySelectedText(); }); function getCurrencySelectedText() { return currency.value.symbol; } }); function resetGender() { var gender = document.getElementById('gender'); gender.value = null; } </script> </ion-app> </body> </html>
core/src/components/select/test/single-value/index.html
0
https://github.com/ionic-team/ionic-framework/commit/14ac8ae24cab29b8c93b9271ad999ef07aeab98f
[ 0.00017786602256819606, 0.00017283901979681104, 0.00016695974045433104, 0.00017365570238325745, 0.000002683071897990885 ]
{ "id": 1, "code_window": [ " .addElement(baseEl)\n", " .easing('cubic-bezier(0.36,0.66,0.04,1)')\n", " .duration(280)\n", " .beforeAddClass('show-modal')\n", " .addAnimation([backdropAnimation, wrapperAnimation]);\n", "};" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [], "file_path": "core/src/components/modal/animations/md.enter.ts", "type": "replace", "edit_start_line_idx": 30 }
import { Animation } from '../../../interface'; import { createAnimation } from '../../../utils/animation/animation'; /** * MD Action Sheet Leave Animation */ export const mdLeaveAnimation = (baseEl: HTMLElement): Animation => { const baseAnimation = createAnimation(); const backdropAnimation = createAnimation(); const wrapperAnimation = createAnimation(); backdropAnimation .addElement(baseEl.querySelector('ion-backdrop')!) .fromTo('opacity', 'var(--backdrop-opacity)', 0); wrapperAnimation .addElement(baseEl.querySelector('.action-sheet-wrapper')!) .fromTo('transform', 'translateY(0%)', 'translateY(100%)'); return baseAnimation .addElement(baseEl) .easing('cubic-bezier(.36,.66,.04,1)') .duration(450) .addAnimation([backdropAnimation, wrapperAnimation]); };
core/src/components/action-sheet/animations/md.leave.ts
0
https://github.com/ionic-team/ionic-framework/commit/14ac8ae24cab29b8c93b9271ad999ef07aeab98f
[ 0.02882303111255169, 0.019395409151911736, 0.002320061204954982, 0.027043137699365616, 0.012095940299332142 ]
{ "id": 2, "code_window": [ "import { Component, ComponentInterface, Element, Event, EventEmitter, Host, Method, Prop, h } from '@stencil/core';\n", "\n", "import { config } from '../../global/config';\n", "import { getIonMode } from '../../global/ionic-global';\n", "import { Animation, AnimationBuilder, ComponentProps, ComponentRef, FrameworkDelegate, Gesture, OverlayEventDetail, OverlayInterface } from '../../interface';\n" ], "labels": [ "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { Component, ComponentInterface, Element, Event, EventEmitter, Host, Method, Prop, h, writeTask } from '@stencil/core';\n" ], "file_path": "core/src/components/modal/modal.tsx", "type": "replace", "edit_start_line_idx": 0 }
import { Animation } from '../../../interface'; import { createAnimation } from '../../../utils/animation/animation'; /** * Md Modal Enter Animation */ export const mdEnterAnimation = (baseEl: HTMLElement): Animation => { const baseAnimation = createAnimation(); const backdropAnimation = createAnimation(); const wrapperAnimation = createAnimation(); backdropAnimation .addElement(baseEl.querySelector('ion-backdrop')!) .fromTo('opacity', 0.01, 'var(--backdrop-opacity)') .beforeStyles({ 'pointer-events': 'none' }) .afterClearStyles(['pointer-events']); wrapperAnimation .addElement(baseEl.querySelector('.modal-wrapper')!) .keyframes([ { offset: 0, opacity: 0.01, transform: 'translateY(40px)' }, { offset: 1, opacity: 1, transform: 'translateY(0px)' } ]); return baseAnimation .addElement(baseEl) .easing('cubic-bezier(0.36,0.66,0.04,1)') .duration(280) .beforeAddClass('show-modal') .addAnimation([backdropAnimation, wrapperAnimation]); };
core/src/components/modal/animations/md.enter.ts
1
https://github.com/ionic-team/ionic-framework/commit/14ac8ae24cab29b8c93b9271ad999ef07aeab98f
[ 0.0002721914497669786, 0.00019606927526183426, 0.0001671929785516113, 0.00017244633636437356, 0.00004400621764943935 ]
{ "id": 2, "code_window": [ "import { Component, ComponentInterface, Element, Event, EventEmitter, Host, Method, Prop, h } from '@stencil/core';\n", "\n", "import { config } from '../../global/config';\n", "import { getIonMode } from '../../global/ionic-global';\n", "import { Animation, AnimationBuilder, ComponentProps, ComponentRef, FrameworkDelegate, Gesture, OverlayEventDetail, OverlayInterface } from '../../interface';\n" ], "labels": [ "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { Component, ComponentInterface, Element, Event, EventEmitter, Host, Method, Prop, h, writeTask } from '@stencil/core';\n" ], "file_path": "core/src/components/modal/modal.tsx", "type": "replace", "edit_start_line_idx": 0 }
```html <template> <!-- Listen to before and after tab change events --> <ion-tabs @IonTabsWillChange="beforeTabChange" @IonTabsDidChange="afterTabChange"> <ion-tab tab="schedule"> <Schedule /> </ion-tab> <!-- Match by "app.speakers" route name --> <ion-tab tab="speakers" :routes="'app.speakers'"> <Speakers /> </ion-tab> <!-- Match by an array of route names --> <ion-tab tab="map" :routes="['app.map', 'app.other.route']"> <Map /> </ion-tab> <!-- Get matched routes with a helper method --> <ion-tab tab="about" :routes="getMatchedRoutes"> <About /> </ion-tab> <!-- Use v-slot:bottom with Vue ^2.6.0 --> <template slot="bottom"> <ion-tab-bar> <ion-tab-button tab="schedule"> <ion-icon name="calendar"></ion-icon> <ion-label>Schedule</ion-label> <ion-badge>6</ion-badge> </ion-tab-button> <!-- Provide a custom route to navigate to --> <ion-tab-button tab="speakers" :to="{ name: 'app.speakers' }"> <ion-icon name="person-circle"></ion-icon> <ion-label>Speakers</ion-label> </ion-tab-button> <!-- Provide extra data to route --> <ion-tab-button tab="map" :to="{ name: 'app.map', params: { mode: 'dark' } }"> <ion-icon name="map"></ion-icon> <ion-label>Map</ion-label> </ion-tab-button> <!-- Provide custom click handler --> <ion-tab-button tab="about" @click="goToAboutTab"> <ion-icon name="information-circle"></ion-icon> <ion-label>About</ion-label> </ion-tab-button> </ion-tab-bar> </template> </ion-tabs> </template> ```
core/src/components/tabs/usage/vue.md
0
https://github.com/ionic-team/ionic-framework/commit/14ac8ae24cab29b8c93b9271ad999ef07aeab98f
[ 0.0001742483291309327, 0.00017261823813896626, 0.00017048658628482372, 0.00017299133469350636, 0.0000015274225688699516 ]
{ "id": 2, "code_window": [ "import { Component, ComponentInterface, Element, Event, EventEmitter, Host, Method, Prop, h } from '@stencil/core';\n", "\n", "import { config } from '../../global/config';\n", "import { getIonMode } from '../../global/ionic-global';\n", "import { Animation, AnimationBuilder, ComponentProps, ComponentRef, FrameworkDelegate, Gesture, OverlayEventDetail, OverlayInterface } from '../../interface';\n" ], "labels": [ "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { Component, ComponentInterface, Element, Event, EventEmitter, Host, Method, Prop, h, writeTask } from '@stencil/core';\n" ], "file_path": "core/src/components/modal/modal.tsx", "type": "replace", "edit_start_line_idx": 0 }
# ion-reorder-group The reorder group is a wrapper component for items using the `ion-reorder` component. See the [Reorder documentation](../reorder/) for further information about the anchor component that is used to drag items within the `ion-reorder-group`. Once the user drags an item and drops it in a new position, the `ionItemReorder` event is dispatched. A handler for it should be implemented that calls the `complete()` method. The `detail` property of the `ionItemReorder` event includes all of the relevant information about the reorder operation, including the `from` and `to` indexes. In the context of reordering, an item moves `from` an index `to` a new index. <!-- Auto Generated Below --> ## Usage ### Angular ```html <!-- The reorder gesture is disabled by default, enable it to drag and drop items --> <ion-reorder-group (ionItemReorder)="doReorder($event)" disabled="false"> <!-- Default reorder icon, end aligned items --> <ion-item> <ion-label> Item 1 </ion-label> <ion-reorder slot="end"></ion-reorder> </ion-item> <ion-item> <ion-label> Item 2 </ion-label> <ion-reorder slot="end"></ion-reorder> </ion-item> <!-- Default reorder icon, start aligned items --> <ion-item> <ion-reorder slot="start"></ion-reorder> <ion-label> Item 3 </ion-label> </ion-item> <ion-item> <ion-reorder slot="start"></ion-reorder> <ion-label> Item 4 </ion-label> </ion-item> <!-- Custom reorder icon end items --> <ion-item> <ion-label> Item 5 </ion-label> <ion-reorder slot="end"> <ion-icon name="pizza"></ion-icon> </ion-reorder> </ion-item> <ion-item> <ion-label> Item 6 </ion-label> <ion-reorder slot="end"> <ion-icon name="pizza"></ion-icon> </ion-reorder> </ion-item> <!-- Items wrapped in a reorder, entire item can be dragged --> <ion-reorder> <ion-item> <ion-label> Item 7 </ion-label> </ion-item> </ion-reorder> <ion-reorder> <ion-item> <ion-label> Item 8 </ion-label> </ion-item> </ion-reorder> </ion-reorder-group> ``` ```javascript import { Component, ViewChild } from '@angular/core'; import { IonReorderGroup } from '@ionic/angular'; @Component({ selector: 'reorder-group-example', templateUrl: 'reorder-group-example.html', styleUrls: ['./reorder-group-example.css'] }) export class ReorderGroupExample { @ViewChild(IonReorderGroup) reorderGroup: IonReorderGroup; constructor() {} doReorder(ev: any) { // The `from` and `to` properties contain the index of the item // when the drag started and ended, respectively console.log('Dragged from index', ev.detail.from, 'to', ev.detail.to); // Finish the reorder and position the item in the DOM based on // where the gesture ended. This method can also be called directly // by the reorder group ev.detail.complete(); } toggleReorderGroup() { this.reorderGroup.disabled = !this.reorderGroup.disabled; } } ``` #### Updating Data ```javascript import { Component, ViewChild } from '@angular/core'; import { IonReorderGroup } from '@ionic/angular'; @Component({ selector: 'reorder-group-example', templateUrl: 'reorder-group-example.html', styleUrls: ['./reorder-group-example.css'] }) export class ReorderGroupExample { items = [1, 2, 3, 4, 5]; @ViewChild(IonReorderGroup) reorderGroup: IonReorderGroup; constructor() {} doReorder(ev: any) { // Before complete is called with the items they will remain in the // order before the drag console.log('Before complete', this.items); // Finish the reorder and position the item in the DOM based on // where the gesture ended. Update the items variable to the // new order of items this.items = ev.detail.complete(this.items); // After complete is called the items will be in the new order console.log('After complete', this.items); } } ``` ### Javascript ```html <!-- The reorder gesture is disabled by default, enable it to drag and drop items --> <ion-reorder-group disabled="false"> <!-- Default reorder icon, end aligned items --> <ion-item> <ion-label> Item 1 </ion-label> <ion-reorder slot="end"></ion-reorder> </ion-item> <ion-item> <ion-label> Item 2 </ion-label> <ion-reorder slot="end"></ion-reorder> </ion-item> <!-- Default reorder icon, start aligned items --> <ion-item> <ion-reorder slot="start"></ion-reorder> <ion-label> Item 3 </ion-label> </ion-item> <ion-item> <ion-reorder slot="start"></ion-reorder> <ion-label> Item 4 </ion-label> </ion-item> <!-- Custom reorder icon end items --> <ion-item> <ion-label> Item 5 </ion-label> <ion-reorder slot="end"> <ion-icon name="pizza"></ion-icon> </ion-reorder> </ion-item> <ion-item> <ion-label> Item 6 </ion-label> <ion-reorder slot="end"> <ion-icon name="pizza"></ion-icon> </ion-reorder> </ion-item> <!-- Items wrapped in a reorder, entire item can be dragged --> <ion-reorder> <ion-item> <ion-label> Item 7 </ion-label> </ion-item> </ion-reorder> <ion-reorder> <ion-item> <ion-label> Item 8 </ion-label> </ion-item> </ion-reorder> </ion-reorder-group> ``` ```javascript const reorderGroup = document.querySelector('ion-reorder-group'); reorderGroup.addEventListener('ionItemReorder', ({detail}) => { // The `from` and `to` properties contain the index of the item // when the drag started and ended, respectively console.log('Dragged from index', detail.from, 'to', detail.to); // Finish the reorder and position the item in the DOM based on // where the gesture ended. This method can also be called directly // by the reorder group detail.complete(); }); ``` #### Updating Data ```javascript const items = [1, 2, 3, 4, 5]; const reorderGroup = document.querySelector('ion-reorder-group'); reorderGroup.addEventListener('ionItemReorder', ({detail}) => { // Before complete is called with the items they will remain in the // order before the drag console.log('Before complete', items); // Finish the reorder and position the item in the DOM based on // where the gesture ended. Update the items variable to the // new order of items items = detail.complete(items); // After complete is called the items will be in the new order console.log('After complete', items); }); ``` ### React ```tsx import React from 'react'; import { IonItem, IonLabel, IonReorder, IonReorderGroup, IonIcon, IonContent } from '@ionic/react'; import { ItemReorderEventDetail } from '@ionic/core'; import { pizza } from 'ionicons/icons'; function doReorder(event: CustomEvent<ItemReorderEventDetail>) { // The `from` and `to` properties contain the index of the item // when the drag started and ended, respectively console.log('Dragged from index', event.detail.from, 'to', event.detail.to); // Finish the reorder and position the item in the DOM based on // where the gesture ended. This method can also be called directly // by the reorder group event.detail.complete(); } export const ReorderGroupExample: React.FC = () => ( <IonContent> {/*-- The reorder gesture is disabled by default, enable it to drag and drop items --*/} <IonReorderGroup disabled={false} onIonItemReorder={doReorder}> {/*-- Default reorder icon, end aligned items --*/} <IonItem> <IonLabel>Item 1</IonLabel> <IonReorder slot="end" /> </IonItem> <IonItem> <IonLabel>Item 2</IonLabel> <IonReorder slot="end" /> </IonItem> {/*-- Default reorder icon, start aligned items --*/} <IonItem> <IonReorder slot="start" /> <IonLabel>Item 3</IonLabel> </IonItem> <IonItem> <IonReorder slot="start" /> <IonLabel>Item 4</IonLabel> </IonItem> {/*-- Custom reorder icon end items --*/} <IonItem> <IonLabel>Item 5</IonLabel> <IonReorder slot="end"> <IonIcon icon={pizza} /> </IonReorder> </IonItem> <IonItem> <IonLabel>Item 6</IonLabel> <IonReorder slot="end"> <IonIcon icon={pizza} /> </IonReorder> </IonItem> {/*-- Items wrapped in a reorder, entire item can be dragged --*/} <IonReorder> <IonItem> <IonLabel>Item 7</IonLabel> </IonItem> </IonReorder> <IonReorder> <IonItem> <IonLabel>Item 8</IonLabel> </IonItem> </IonReorder> </IonReorderGroup> </IonContent> ); ``` #### Updating Data ```tsx const items = [1, 2, 3, 4, 5]; function doReorder(event: CustomEvent) { // Before complete is called with the items they will remain in the // order before the drag console.log('Before complete', this.items); // Finish the reorder and position the item in the DOM based on // where the gesture ended. Update the items variable to the // new order of items this.items = event.detail.complete(this.items); // After complete is called the items will be in the new order console.log('After complete', this.items); } ``` ### Vue ```html <template> <!-- The reorder gesture is disabled by default, enable it to drag and drop items --> <ion-reorder-group @ionItemReorder="doReorder($event)" disabled="false"> <!-- Default reorder icon, end aligned items --> <ion-item> <ion-label> Item 1 </ion-label> <ion-reorder slot="end"></ion-reorder> </ion-item> <ion-item> <ion-label> Item 2 </ion-label> <ion-reorder slot="end"></ion-reorder> </ion-item> <!-- Default reorder icon, start aligned items --> <ion-item> <ion-reorder slot="start"></ion-reorder> <ion-label> Item 3 </ion-label> </ion-item> <ion-item> <ion-reorder slot="start"></ion-reorder> <ion-label> Item 4 </ion-label> </ion-item> <!-- Custom reorder icon end items --> <ion-item> <ion-label> Item 5 </ion-label> <ion-reorder slot="end"> <ion-icon name="pizza"></ion-icon> </ion-reorder> </ion-item> <ion-item> <ion-label> Item 6 </ion-label> <ion-reorder slot="end"> <ion-icon name="pizza"></ion-icon> </ion-reorder> </ion-item> <!-- Items wrapped in a reorder, entire item can be dragged --> <ion-reorder> <ion-item> <ion-label> Item 7 </ion-label> </ion-item> </ion-reorder> <ion-reorder> <ion-item> <ion-label> Item 8 </ion-label> </ion-item> </ion-reorder> </ion-reorder-group> </template> <script lang="ts"> import { Component, Vue } from 'vue-property-decorator'; @Component() export default class Example extends Vue { doReorder(event) { // The `from` and `to` properties contain the index of the item // when the drag started and ended, respectively console.log('Dragged from index', event.detail.from, 'to', event.detail.to); // Finish the reorder and position the item in the DOM based on // where the gesture ended. This method can also be called directly // by the reorder group event.detail.complete(); } } </script> ``` #### Updating Data ```html <script lang="ts"> import { Component, Vue } from 'vue-property-decorator'; @Component() export default class Example extends Vue { items = [1, 2, 3, 4, 5]; doReorder(event) { // Before complete is called with the items they will remain in the // order before the drag console.log('Before complete', this.items); // Finish the reorder and position the item in the DOM based on // where the gesture ended. Update the items variable to the // new order of items this.items = event.detail.complete(this.items); // After complete is called the items will be in the new order console.log('After complete', this.items); } } </script> ``` ## Properties | Property | Attribute | Description | Type | Default | | ---------- | ---------- | -------------------------------------- | --------- | ------- | | `disabled` | `disabled` | If `true`, the reorder will be hidden. | `boolean` | `true` | ## Events | Event | Description | Type | | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------- | | `ionItemReorder` | Event that needs to be listened to in order to complete the reorder action. Once the event has been emitted, the `complete()` method then needs to be called in order to finalize the reorder action. | `CustomEvent<ItemReorderEventDetail>` | ## Methods ### `complete(listOrReorder?: boolean | any[] | undefined) => Promise<any>` Completes the reorder operation. Must be called by the `ionItemReorder` event. If a list of items is passed, the list will be reordered and returned in the proper order. If no parameters are passed or if `true` is passed in, the reorder will complete and the item will remain in the position it was dragged to. If `false` is passed, the reorder will complete and the item will bounce back to its original position. #### Returns Type: `Promise<any>` ---------------------------------------------- *Built with [StencilJS](https://stenciljs.com/)*
core/src/components/reorder-group/readme.md
0
https://github.com/ionic-team/ionic-framework/commit/14ac8ae24cab29b8c93b9271ad999ef07aeab98f
[ 0.0002379234356340021, 0.00017426062549930066, 0.00016400098684243858, 0.00017356581520289183, 0.00001038825030263979 ]
{ "id": 2, "code_window": [ "import { Component, ComponentInterface, Element, Event, EventEmitter, Host, Method, Prop, h } from '@stencil/core';\n", "\n", "import { config } from '../../global/config';\n", "import { getIonMode } from '../../global/ionic-global';\n", "import { Animation, AnimationBuilder, ComponentProps, ComponentRef, FrameworkDelegate, Gesture, OverlayEventDetail, OverlayInterface } from '../../interface';\n" ], "labels": [ "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { Component, ComponentInterface, Element, Event, EventEmitter, Host, Method, Prop, h, writeTask } from '@stencil/core';\n" ], "file_path": "core/src/components/modal/modal.tsx", "type": "replace", "edit_start_line_idx": 0 }
```html <ion-tabs> <ion-tab-bar slot="bottom"> <ion-tab-button tab="schedule" href="/app/tabs/(schedule:schedule)"> <ion-icon name="calendar"></ion-icon> <ion-label>Schedule</ion-label> </ion-tab-button> <ion-tab-button tab="speakers" href="/app/tabs/(speakers:speakers)"> <ion-icon name="person-circle"></ion-icon> <ion-label>Speakers</ion-label> </ion-tab-button> <ion-tab-button tab="map" href="/app/tabs/(map:map)"> <ion-icon name="map"></ion-icon> <ion-label>Map</ion-label> </ion-tab-button> <ion-tab-button tab="about" href="/app/tabs/(about:about)"> <ion-icon name="information-circle"></ion-icon> <ion-label>About</ion-label> </ion-tab-button> </ion-tab-bar> <ion-tab tab="schedule"> <ion-router-outlet name="schedule"></ion-router-outlet> </ion-tab> <ion-tab tab="speakers"> <ion-router-outlet name="speakers"></ion-router-outlet> </ion-tab> <ion-tab tab="map"> <ion-router-outlet name="map"></ion-router-outlet> </ion-tab> <ion-tab tab="about"> <ion-router-outlet name="about"></ion-router-outlet> </ion-tab> </ion-tabs> ```
core/src/components/tab-button/usage/javascript.md
0
https://github.com/ionic-team/ionic-framework/commit/14ac8ae24cab29b8c93b9271ad999ef07aeab98f
[ 0.0001754482218530029, 0.00017363298684358597, 0.00017053763440344483, 0.00017396743351127952, 0.0000016479634723509662 ]
{ "id": 3, "code_window": [ " modal: this.el\n", " };\n", " this.usersElement = await attachComponent(this.delegate, container, this.component, ['ion-page'], componentProps);\n", " await deepReady(this.usersElement);\n", " await present(this, 'modalEnter', iosEnterAnimation, mdEnterAnimation, this.presentingElement);\n", "\n", " const mode = getIonMode(this);\n", " if (this.swipeToClose && mode === 'ios') {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " writeTask(() => this.el.classList.add('show-modal'));\n", "\n" ], "file_path": "core/src/components/modal/modal.tsx", "type": "add", "edit_start_line_idx": 146 }
import { Component, ComponentInterface, Element, Event, EventEmitter, Host, Method, Prop, h } from '@stencil/core'; import { config } from '../../global/config'; import { getIonMode } from '../../global/ionic-global'; import { Animation, AnimationBuilder, ComponentProps, ComponentRef, FrameworkDelegate, Gesture, OverlayEventDetail, OverlayInterface } from '../../interface'; import { attachComponent, detachComponent } from '../../utils/framework-delegate'; import { BACKDROP, activeAnimations, dismiss, eventMethod, prepareOverlay, present } from '../../utils/overlays'; import { getClassMap } from '../../utils/theme'; import { deepReady } from '../../utils/transition'; import { iosEnterAnimation } from './animations/ios.enter'; import { iosLeaveAnimation } from './animations/ios.leave'; import { mdEnterAnimation } from './animations/md.enter'; import { mdLeaveAnimation } from './animations/md.leave'; import { createSwipeToCloseGesture } from './gestures/swipe-to-close'; /** * @virtualProp {"ios" | "md"} mode - The mode determines which platform styles to use. */ @Component({ tag: 'ion-modal', styleUrls: { ios: 'modal.ios.scss', md: 'modal.md.scss' }, scoped: true }) export class Modal implements ComponentInterface, OverlayInterface { private gesture?: Gesture; // Reference to the user's provided modal content private usersElement?: HTMLElement; // Whether or not modal is being dismissed via gesture private gestureAnimationDismissing = false; presented = false; animation?: Animation; mode = getIonMode(this); @Element() el!: HTMLIonModalElement; /** @internal */ @Prop() overlayIndex!: number; /** @internal */ @Prop() delegate?: FrameworkDelegate; /** * If `true`, the keyboard will be automatically dismissed when the overlay is presented. */ @Prop() keyboardClose = true; /** * Animation to use when the modal is presented. */ @Prop() enterAnimation?: AnimationBuilder; /** * Animation to use when the modal is dismissed. */ @Prop() leaveAnimation?: AnimationBuilder; /** * The component to display inside of the modal. */ @Prop() component!: ComponentRef; /** * The data to pass to the modal component. */ @Prop() componentProps?: ComponentProps; /** * Additional classes to apply for custom CSS. If multiple classes are * provided they should be separated by spaces. */ @Prop() cssClass?: string | string[]; /** * If `true`, the modal will be dismissed when the backdrop is clicked. */ @Prop() backdropDismiss = true; /** * If `true`, a backdrop will be displayed behind the modal. */ @Prop() showBackdrop = true; /** * If `true`, the modal will animate. */ @Prop() animated = true; /** * If `true`, the modal can be swiped to dismiss. Only applies in iOS mode. */ @Prop() swipeToClose = false; /** * The element that presented the modal. This is used for card presentation effects * and for stacking multiple modals on top of each other. Only applies in iOS mode. */ @Prop() presentingElement?: HTMLElement; /** * Emitted after the modal has presented. */ @Event({ eventName: 'ionModalDidPresent' }) didPresent!: EventEmitter<void>; /** * Emitted before the modal has presented. */ @Event({ eventName: 'ionModalWillPresent' }) willPresent!: EventEmitter<void>; /** * Emitted before the modal has dismissed. */ @Event({ eventName: 'ionModalWillDismiss' }) willDismiss!: EventEmitter<OverlayEventDetail>; /** * Emitted after the modal has dismissed. */ @Event({ eventName: 'ionModalDidDismiss' }) didDismiss!: EventEmitter<OverlayEventDetail>; constructor() { prepareOverlay(this.el); } /** * Present the modal overlay after it has been created. */ @Method() async present(): Promise<void> { if (this.presented) { return; } const container = this.el.querySelector(`.modal-wrapper`); if (!container) { throw new Error('container is undefined'); } const componentProps = { ...this.componentProps, modal: this.el }; this.usersElement = await attachComponent(this.delegate, container, this.component, ['ion-page'], componentProps); await deepReady(this.usersElement); await present(this, 'modalEnter', iosEnterAnimation, mdEnterAnimation, this.presentingElement); const mode = getIonMode(this); if (this.swipeToClose && mode === 'ios') { // All of the elements needed for the swipe gesture // should be in the DOM and referenced by now, except // for the presenting el const animationBuilder = this.leaveAnimation || config.get('modalLeave', iosLeaveAnimation); const ani = this.animation = animationBuilder(this.el, this.presentingElement); this.gesture = createSwipeToCloseGesture( this.el, ani, () => { /** * While the gesture animation is finishing * it is possible for a user to tap the backdrop. * This would result in the dismiss animation * being played again. Typically this is avoided * by setting `presented = false` on the overlay * component; however, we cannot do that here as * that would prevent the element from being * removed from the DOM. */ this.gestureAnimationDismissing = true; this.animation!.onFinish(async () => { await this.dismiss(undefined, 'gesture'); this.gestureAnimationDismissing = false; }); }, ); this.gesture.enable(true); } } /** * Dismiss the modal overlay after it has been presented. * * @param data Any data to emit in the dismiss events. * @param role The role of the element that is dismissing the modal. For example, 'cancel' or 'backdrop'. */ @Method() async dismiss(data?: any, role?: string): Promise<boolean> { if (this.gestureAnimationDismissing && role !== 'gesture') { return false; } const enteringAnimation = activeAnimations.get(this) || []; const dismissed = await dismiss(this, data, role, 'modalLeave', iosLeaveAnimation, mdLeaveAnimation, this.presentingElement); if (dismissed) { await detachComponent(this.delegate, this.usersElement); if (this.animation) { this.animation.destroy(); } enteringAnimation.forEach(ani => ani.destroy()); } this.animation = undefined; return dismissed; } /** * Returns a promise that resolves when the modal did dismiss. */ @Method() onDidDismiss(): Promise<OverlayEventDetail> { return eventMethod(this.el, 'ionModalDidDismiss'); } /** * Returns a promise that resolves when the modal will dismiss. */ @Method() onWillDismiss(): Promise<OverlayEventDetail> { return eventMethod(this.el, 'ionModalWillDismiss'); } private onBackdropTap = () => { this.dismiss(undefined, BACKDROP); } private onDismiss = (ev: UIEvent) => { ev.stopPropagation(); ev.preventDefault(); this.dismiss(); } private onLifecycle = (modalEvent: CustomEvent) => { const el = this.usersElement; const name = LIFECYCLE_MAP[modalEvent.type]; if (el && name) { const ev = new CustomEvent(name, { bubbles: false, cancelable: false, detail: modalEvent.detail }); el.dispatchEvent(ev); } } render() { const mode = getIonMode(this); return ( <Host no-router aria-modal="true" class={{ [mode]: true, [`modal-card`]: this.presentingElement !== undefined && mode === 'ios', ...getClassMap(this.cssClass) }} style={{ zIndex: `${20000 + this.overlayIndex}`, }} onIonBackdropTap={this.onBackdropTap} onIonDismiss={this.onDismiss} onIonModalDidPresent={this.onLifecycle} onIonModalWillPresent={this.onLifecycle} onIonModalWillDismiss={this.onLifecycle} onIonModalDidDismiss={this.onLifecycle} > <ion-backdrop visible={this.showBackdrop} tappable={this.backdropDismiss}/> <div role="dialog" class="modal-wrapper" > </div> </Host> ); } } const LIFECYCLE_MAP: any = { 'ionModalDidPresent': 'ionViewDidEnter', 'ionModalWillPresent': 'ionViewWillEnter', 'ionModalWillDismiss': 'ionViewWillLeave', 'ionModalDidDismiss': 'ionViewDidLeave', };
core/src/components/modal/modal.tsx
1
https://github.com/ionic-team/ionic-framework/commit/14ac8ae24cab29b8c93b9271ad999ef07aeab98f
[ 0.9983158111572266, 0.0740082785487175, 0.00016606759163551033, 0.00017939620011020452, 0.25153377652168274 ]
{ "id": 3, "code_window": [ " modal: this.el\n", " };\n", " this.usersElement = await attachComponent(this.delegate, container, this.component, ['ion-page'], componentProps);\n", " await deepReady(this.usersElement);\n", " await present(this, 'modalEnter', iosEnterAnimation, mdEnterAnimation, this.presentingElement);\n", "\n", " const mode = getIonMode(this);\n", " if (this.swipeToClose && mode === 'ios') {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " writeTask(() => this.el.classList.add('show-modal'));\n", "\n" ], "file_path": "core/src/components/modal/modal.tsx", "type": "add", "edit_start_line_idx": 146 }
import { newE2EPage } from '@stencil/core/testing'; test('tabs: basic', async () => { const page = await newE2EPage({ url: '/src/components/tabs/test/basic?ionic:_testing=true' }); let compare = await page.compareScreenshot(); expect(compare).toMatchScreenshot(); const button2 = await page.find('.e2eTabTwoButton'); await button2.click(); compare = await page.compareScreenshot(`tab two`); expect(compare).toMatchScreenshot(); const button3 = await page.find('.e2eTabThreeButton'); await button3.click(); compare = await page.compareScreenshot(`tab three, disabled`); expect(compare).toMatchScreenshot(); const button4 = await page.find('.e2eTabFourButton'); await button4.click(); compare = await page.compareScreenshot(`tab four`); expect(compare).toMatchScreenshot(); });
core/src/components/tabs/test/basic/e2e.ts
0
https://github.com/ionic-team/ionic-framework/commit/14ac8ae24cab29b8c93b9271ad999ef07aeab98f
[ 0.00017674395348876715, 0.00017650453082751483, 0.0001761614839779213, 0.00017660818411968648, 2.4882950810933835e-7 ]
{ "id": 3, "code_window": [ " modal: this.el\n", " };\n", " this.usersElement = await attachComponent(this.delegate, container, this.component, ['ion-page'], componentProps);\n", " await deepReady(this.usersElement);\n", " await present(this, 'modalEnter', iosEnterAnimation, mdEnterAnimation, this.presentingElement);\n", "\n", " const mode = getIonMode(this);\n", " if (this.swipeToClose && mode === 'ios') {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " writeTask(() => this.el.classList.add('show-modal'));\n", "\n" ], "file_path": "core/src/components/modal/modal.tsx", "type": "add", "edit_start_line_idx": 146 }
<!DOCTYPE html> <html dir="ltr"> <head> <meta charset="UTF-8"> <title>Header - Translucent</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link href="../../../../../css/ionic.bundle.css" rel="stylesheet"> <link href="../../../../../scripts/testing/styles.css" rel="stylesheet"> <script src="../../../../../scripts/testing/scripts.js"></script> <script nomodule src="../../../../../dist/ionic/ionic.js"></script> <script type="module" src="../../../../../dist/ionic/ionic.esm.js"></script></head> <body> <ion-app> <ion-content fullscreen> <ion-grid> <ion-row> <ion-col size="6"> <f class="red"></f> </ion-col> <ion-col size="6"> <f class="green"></f> </ion-col> <ion-col size="6"> <f class="blue"></f> </ion-col> <ion-col size="6"> <f class="yellow"></f> </ion-col> <ion-col size="6"> <f class="pink"></f> </ion-col> <ion-col size="6"> <f class="purple"></f> </ion-col> <ion-col size="6"> <f class="black"></f> </ion-col> <ion-col size="6"> <f class="orange"></f> </ion-col> </ion-row> </ion-grid> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vitae lobortis felis, eu sodales enim. Nam risus nibh, placerat at rutrum ac, vehicula vel velit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum quis elementum ligula, ac aliquet nulla. Mauris non placerat mauris. Aenean dignissim lacinia porttitor. Praesent fringilla at est et ullamcorper. In ac ante ac massa porta venenatis ut id nibh. Fusce felis neque, aliquet in velit vitae, venenatis euismod libero. Donec vulputate, urna sed sagittis tempor, mi arcu tristique lacus, eget fringilla urna sem eget felis. Fusce dignissim lacus a scelerisque vehicula. Nulla nec enim nunc. Quisque nec dui eu nibh pulvinar bibendum quis ut nunc. Duis ex odio, sollicitudin ac mollis nec, fringilla non lacus. Maecenas sed tincidunt urna. Nunc feugiat maximus venenatis. Donec porttitor, felis eget porttitor tempor, quam nulla dapibus nisl, sit amet posuere sapien sapien malesuada tortor. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Quisque luctus, sapien nec tincidunt efficitur, nibh turpis faucibus felis, in sodales massa augue nec erat. Morbi sollicitudin nisi ex, et gravida nisi euismod eu. Suspendisse hendrerit dapibus orci, non viverra neque vestibulum id. Quisque vitae interdum ligula, quis consectetur nibh. Phasellus in mi at erat ultrices semper. Fusce sollicitudin at dolor ac lobortis. Morbi sit amet sem quis nulla pellentesque imperdiet. Nullam eu sem a enim maximus eleifend non vulputate leo. Proin quis congue lacus. Pellentesque placerat, quam at tempus pulvinar, nisl ligula tempor risus, quis pretium arcu odio et nulla. Nullam mollis consequat pharetra. Phasellus dictum velit sed purus mattis maximus. In molestie eget massa ut dignissim. In a interdum elit. In finibus nibh a mauris lobortis aliquet. Proin rutrum varius consequat. In mollis dapibus nisl, eu finibus urna viverra ac. Quisque scelerisque nisl eu suscipit consectetur. </p> <ion-grid> <ion-row> <ion-col size="6"> <f class="red"></f> </ion-col> <ion-col size="6"> <f class="green"></f> </ion-col> <ion-col size="6"> <f class="blue"></f> </ion-col> <ion-col size="6"> <f class="yellow"></f> </ion-col> <ion-col size="6"> <f class="pink"></f> </ion-col> <ion-col size="6"> <f class="purple"></f> </ion-col> <ion-col size="6"> <f class="black"></f> </ion-col> <ion-col size="6"> <f class="orange"></f> </ion-col> </ion-row> </ion-grid> </ion-content> <ion-footer translucent> <ion-toolbar> <ion-title>Footer - Translucent</ion-title> </ion-toolbar> <ion-toolbar color="primary"> <ion-title>Primary - Translucent</ion-title> </ion-toolbar> <ion-toolbar color="secondary"> <ion-title>Secondary - Translucent</ion-title> </ion-toolbar> <ion-toolbar color="tertiary"> <ion-title>Tertiary - Translucent</ion-title> </ion-toolbar> <ion-toolbar color="success"> <ion-title>Success - Translucent</ion-title> </ion-toolbar> <ion-toolbar color="warning"> <ion-title>Warning - Translucent</ion-title> </ion-toolbar> <ion-toolbar color="danger"> <ion-title>Danger - Translucent</ion-title> </ion-toolbar> <ion-toolbar color="light"> <ion-title>Light - Translucent</ion-title> </ion-toolbar> <ion-toolbar color="medium"> <ion-title>Medium - Translucent</ion-title> </ion-toolbar> </ion-footer> </ion-app> <style> f { display: block; height: 200px; } .red { background-color: #ea445a; } .green { background-color: #76d672; } .blue { background-color: #3478f6; } .yellow { background-color: #ffff80; } .pink { background-color: #ff6b86; } .purple { background-color: #7e34f6; } .black { background-color: #000; } .orange { background-color: #f69234; } </style> </body> </html>
core/src/components/footer/test/translucent/index.html
0
https://github.com/ionic-team/ionic-framework/commit/14ac8ae24cab29b8c93b9271ad999ef07aeab98f
[ 0.00017719702736940235, 0.000168990038218908, 0.00016411721298936754, 0.0001679034176049754, 0.00000403065087084542 ]
{ "id": 3, "code_window": [ " modal: this.el\n", " };\n", " this.usersElement = await attachComponent(this.delegate, container, this.component, ['ion-page'], componentProps);\n", " await deepReady(this.usersElement);\n", " await present(this, 'modalEnter', iosEnterAnimation, mdEnterAnimation, this.presentingElement);\n", "\n", " const mode = getIonMode(this);\n", " if (this.swipeToClose && mode === 'ios') {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\n", " writeTask(() => this.el.classList.add('show-modal'));\n", "\n" ], "file_path": "core/src/components/modal/modal.tsx", "type": "add", "edit_start_line_idx": 146 }
```html <ion-tabs> <ion-tab-bar slot="bottom"> <ion-tab-button tab="schedule"> <ion-icon name="calendar"></ion-icon> <ion-label>Schedule</ion-label> </ion-tab-button> <ion-tab-button tab="speakers"> <ion-icon name="person-circle"></ion-icon> <ion-label>Speakers</ion-label> </ion-tab-button> <ion-tab-button tab="map"> <ion-icon name="map"></ion-icon> <ion-label>Map</ion-label> </ion-tab-button> <ion-tab-button tab="about"> <ion-icon name="information-circle"></ion-icon> <ion-label>About</ion-label> </ion-tab-button> </ion-tab-bar> </ion-tabs> ```
core/src/components/tab-button/usage/angular.md
0
https://github.com/ionic-team/ionic-framework/commit/14ac8ae24cab29b8c93b9271ad999ef07aeab98f
[ 0.0001650862250244245, 0.00016431575932074338, 0.0001634866785025224, 0.00016437435988336802, 6.543257313751383e-7 ]
{ "id": 0, "code_window": [ "export const BaseTransition = BaseTransitionImpl as unknown as {\n", " new (): {\n", " $props: BaseTransitionProps<any>\n", " }\n", "}\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " $slots: {\n", " default(): VNode[]\n", " }\n" ], "file_path": "packages/runtime-core/src/components/BaseTransition.ts", "type": "add", "edit_start_line_idx": 285 }
import { ConcreteComponent, getCurrentInstance, SetupContext, ComponentInternalInstance, currentInstance, getComponentName, ComponentOptions } from '../component' import { VNode, cloneVNode, isVNode, VNodeProps, invokeVNodeHook, isSameVNodeType } from '../vnode' import { warn } from '../warning' import { onBeforeUnmount, injectHook, onUnmounted, onMounted, onUpdated } from '../apiLifecycle' import { isString, isArray, isRegExp, ShapeFlags, remove, invokeArrayFns } from '@vue/shared' import { watch } from '../apiWatch' import { RendererInternals, queuePostRenderEffect, MoveType, RendererElement, RendererNode } from '../renderer' import { setTransitionHooks } from './BaseTransition' import { ComponentRenderContext } from '../componentPublicInstance' import { devtoolsComponentAdded } from '../devtools' import { isAsyncWrapper } from '../apiAsyncComponent' import { isSuspense } from './Suspense' import { LifecycleHooks } from '../enums' type MatchPattern = string | RegExp | (string | RegExp)[] export interface KeepAliveProps { include?: MatchPattern exclude?: MatchPattern max?: number | string } type CacheKey = string | number | symbol | ConcreteComponent type Cache = Map<CacheKey, VNode> type Keys = Set<CacheKey> export interface KeepAliveContext extends ComponentRenderContext { renderer: RendererInternals activate: ( vnode: VNode, container: RendererElement, anchor: RendererNode | null, isSVG: boolean, optimized: boolean ) => void deactivate: (vnode: VNode) => void } export const isKeepAlive = (vnode: VNode): boolean => (vnode.type as any).__isKeepAlive const KeepAliveImpl: ComponentOptions = { name: `KeepAlive`, // Marker for special handling inside the renderer. We are not using a === // check directly on KeepAlive in the renderer, because importing it directly // would prevent it from being tree-shaken. __isKeepAlive: true, props: { include: [String, RegExp, Array], exclude: [String, RegExp, Array], max: [String, Number] }, setup(props: KeepAliveProps, { slots }: SetupContext) { const instance = getCurrentInstance()! // KeepAlive communicates with the instantiated renderer via the // ctx where the renderer passes in its internals, // and the KeepAlive instance exposes activate/deactivate implementations. // The whole point of this is to avoid importing KeepAlive directly in the // renderer to facilitate tree-shaking. const sharedContext = instance.ctx as KeepAliveContext // if the internal renderer is not registered, it indicates that this is server-side rendering, // for KeepAlive, we just need to render its children if (__SSR__ && !sharedContext.renderer) { return () => { const children = slots.default && slots.default() return children && children.length === 1 ? children[0] : children } } const cache: Cache = new Map() const keys: Keys = new Set() let current: VNode | null = null if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) { ;(instance as any).__v_cache = cache } const parentSuspense = instance.suspense const { renderer: { p: patch, m: move, um: _unmount, o: { createElement } } } = sharedContext const storageContainer = createElement('div') sharedContext.activate = (vnode, container, anchor, isSVG, optimized) => { const instance = vnode.component! move(vnode, container, anchor, MoveType.ENTER, parentSuspense) // in case props have changed patch( instance.vnode, vnode, container, anchor, instance, parentSuspense, isSVG, vnode.slotScopeIds, optimized ) queuePostRenderEffect(() => { instance.isDeactivated = false if (instance.a) { invokeArrayFns(instance.a) } const vnodeHook = vnode.props && vnode.props.onVnodeMounted if (vnodeHook) { invokeVNodeHook(vnodeHook, instance.parent, vnode) } }, parentSuspense) if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) { // Update components tree devtoolsComponentAdded(instance) } } sharedContext.deactivate = (vnode: VNode) => { const instance = vnode.component! move(vnode, storageContainer, null, MoveType.LEAVE, parentSuspense) queuePostRenderEffect(() => { if (instance.da) { invokeArrayFns(instance.da) } const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted if (vnodeHook) { invokeVNodeHook(vnodeHook, instance.parent, vnode) } instance.isDeactivated = true }, parentSuspense) if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) { // Update components tree devtoolsComponentAdded(instance) } } function unmount(vnode: VNode) { // reset the shapeFlag so it can be properly unmounted resetShapeFlag(vnode) _unmount(vnode, instance, parentSuspense, true) } function pruneCache(filter?: (name: string) => boolean) { cache.forEach((vnode, key) => { const name = getComponentName(vnode.type as ConcreteComponent) if (name && (!filter || !filter(name))) { pruneCacheEntry(key) } }) } function pruneCacheEntry(key: CacheKey) { const cached = cache.get(key) as VNode if (!current || !isSameVNodeType(cached, current)) { unmount(cached) } else if (current) { // current active instance should no longer be kept-alive. // we can't unmount it now but it might be later, so reset its flag now. resetShapeFlag(current) } cache.delete(key) keys.delete(key) } // prune cache on include/exclude prop change watch( () => [props.include, props.exclude], ([include, exclude]) => { include && pruneCache(name => matches(include, name)) exclude && pruneCache(name => !matches(exclude, name)) }, // prune post-render after `current` has been updated { flush: 'post', deep: true } ) // cache sub tree after render let pendingCacheKey: CacheKey | null = null const cacheSubtree = () => { // fix #1621, the pendingCacheKey could be 0 if (pendingCacheKey != null) { cache.set(pendingCacheKey, getInnerChild(instance.subTree)) } } onMounted(cacheSubtree) onUpdated(cacheSubtree) onBeforeUnmount(() => { cache.forEach(cached => { const { subTree, suspense } = instance const vnode = getInnerChild(subTree) if (cached.type === vnode.type && cached.key === vnode.key) { // current instance will be unmounted as part of keep-alive's unmount resetShapeFlag(vnode) // but invoke its deactivated hook here const da = vnode.component!.da da && queuePostRenderEffect(da, suspense) return } unmount(cached) }) }) return () => { pendingCacheKey = null if (!slots.default) { return null } const children = slots.default() const rawVNode = children[0] if (children.length > 1) { if (__DEV__) { warn(`KeepAlive should contain exactly one component child.`) } current = null return children } else if ( !isVNode(rawVNode) || (!(rawVNode.shapeFlag & ShapeFlags.STATEFUL_COMPONENT) && !(rawVNode.shapeFlag & ShapeFlags.SUSPENSE)) ) { current = null return rawVNode } let vnode = getInnerChild(rawVNode) const comp = vnode.type as ConcreteComponent // for async components, name check should be based in its loaded // inner component if available const name = getComponentName( isAsyncWrapper(vnode) ? (vnode.type as ComponentOptions).__asyncResolved || {} : comp ) const { include, exclude, max } = props if ( (include && (!name || !matches(include, name))) || (exclude && name && matches(exclude, name)) ) { current = vnode return rawVNode } const key = vnode.key == null ? comp : vnode.key const cachedVNode = cache.get(key) // clone vnode if it's reused because we are going to mutate it if (vnode.el) { vnode = cloneVNode(vnode) if (rawVNode.shapeFlag & ShapeFlags.SUSPENSE) { rawVNode.ssContent = vnode } } // #1513 it's possible for the returned vnode to be cloned due to attr // fallthrough or scopeId, so the vnode here may not be the final vnode // that is mounted. Instead of caching it directly, we store the pending // key and cache `instance.subTree` (the normalized vnode) in // beforeMount/beforeUpdate hooks. pendingCacheKey = key if (cachedVNode) { // copy over mounted state vnode.el = cachedVNode.el vnode.component = cachedVNode.component if (vnode.transition) { // recursively update transition hooks on subTree setTransitionHooks(vnode, vnode.transition!) } // avoid vnode being mounted as fresh vnode.shapeFlag |= ShapeFlags.COMPONENT_KEPT_ALIVE // make this key the freshest keys.delete(key) keys.add(key) } else { keys.add(key) // prune oldest entry if (max && keys.size > parseInt(max as string, 10)) { pruneCacheEntry(keys.values().next().value) } } // avoid vnode being unmounted vnode.shapeFlag |= ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE current = vnode return isSuspense(rawVNode.type) ? rawVNode : vnode } } } if (__COMPAT__) { KeepAliveImpl.__isBuildIn = true } // 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 { __isKeepAlive: true new (): { $props: VNodeProps & KeepAliveProps } } function matches(pattern: MatchPattern, name: string): boolean { if (isArray(pattern)) { return pattern.some((p: string | RegExp) => matches(p, name)) } else if (isString(pattern)) { return pattern.split(',').includes(name) } else if (isRegExp(pattern)) { return pattern.test(name) } /* istanbul ignore next */ return false } export function onActivated( hook: Function, target?: ComponentInternalInstance | null ) { registerKeepAliveHook(hook, LifecycleHooks.ACTIVATED, target) } export function onDeactivated( hook: Function, target?: ComponentInternalInstance | null ) { registerKeepAliveHook(hook, LifecycleHooks.DEACTIVATED, target) } function registerKeepAliveHook( hook: Function & { __wdc?: Function }, type: LifecycleHooks, target: ComponentInternalInstance | null = currentInstance ) { // cache the deactivate branch check wrapper for injected hooks so the same // hook can be properly deduped by the scheduler. "__wdc" stands for "with // deactivation check". const wrappedHook = hook.__wdc || (hook.__wdc = () => { // only fire the hook if the target instance is NOT in a deactivated branch. let current: ComponentInternalInstance | null = target while (current) { if (current.isDeactivated) { return } current = current.parent } return hook() }) injectHook(type, wrappedHook, target) // In addition to registering it on the target instance, we walk up the parent // chain and register it on all ancestor instances that are keep-alive roots. // This avoids the need to walk the entire component tree when invoking these // hooks, and more importantly, avoids the need to track child components in // arrays. if (target) { let current = target.parent while (current && current.parent) { if (isKeepAlive(current.parent.vnode)) { injectToKeepAliveRoot(wrappedHook, type, target, current) } current = current.parent } } } function injectToKeepAliveRoot( hook: Function & { __weh?: Function }, type: LifecycleHooks, target: ComponentInternalInstance, keepAliveRoot: ComponentInternalInstance ) { // injectHook wraps the original for error handling, so make sure to remove // the wrapped version. const injected = injectHook(type, hook, keepAliveRoot, true /* prepend */) onUnmounted(() => { remove(keepAliveRoot[type]!, injected) }, target) } function resetShapeFlag(vnode: VNode) { // bitwise operations to remove keep alive flags vnode.shapeFlag &= ~ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE vnode.shapeFlag &= ~ShapeFlags.COMPONENT_KEPT_ALIVE } function getInnerChild(vnode: VNode) { return vnode.shapeFlag & ShapeFlags.SUSPENSE ? vnode.ssContent! : vnode }
packages/runtime-core/src/components/KeepAlive.ts
1
https://github.com/vuejs/core/commit/3cb4dc9e5538e1c2bde9fa691b001615a848c546
[ 0.0005289276596158743, 0.00020155958191026002, 0.00016368493379559368, 0.00017171599029097706, 0.00008459028322249651 ]
{ "id": 0, "code_window": [ "export const BaseTransition = BaseTransitionImpl as unknown as {\n", " new (): {\n", " $props: BaseTransitionProps<any>\n", " }\n", "}\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " $slots: {\n", " default(): VNode[]\n", " }\n" ], "file_path": "packages/runtime-core/src/components/BaseTransition.ts", "type": "add", "edit_start_line_idx": 285 }
import { compile, CompilerError } from '../../src' describe('compiler: ignore side effect tags', () => { it('should ignore script', () => { let err: CompilerError | undefined const { code } = compile(`<script>console.log(1)</script>`, { onError(e) { err = e } }) expect(code).not.toMatch('script') expect(err).toBeDefined() expect(err!.message).toMatch(`Tags with side effect`) }) it('should ignore style', () => { let err: CompilerError | undefined const { code } = compile(`<style>h1 { color: red }</style>`, { onError(e) { err = e } }) expect(code).not.toMatch('style') expect(err).toBeDefined() expect(err!.message).toMatch(`Tags with side effect`) }) })
packages/compiler-dom/__tests__/transforms/ignoreSideEffectTags.spec.ts
0
https://github.com/vuejs/core/commit/3cb4dc9e5538e1c2bde9fa691b001615a848c546
[ 0.00017382118676323444, 0.0001732081436784938, 0.00017228942306246608, 0.00017351385031361133, 6.616459131691954e-7 ]
{ "id": 0, "code_window": [ "export const BaseTransition = BaseTransitionImpl as unknown as {\n", " new (): {\n", " $props: BaseTransitionProps<any>\n", " }\n", "}\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " $slots: {\n", " default(): VNode[]\n", " }\n" ], "file_path": "packages/runtime-core/src/components/BaseTransition.ts", "type": "add", "edit_start_line_idx": 285 }
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html exports[`SFC analyze <script> bindings > auto name inference > basic 1`] = ` "const a = 1 export default { __name: 'FooBar', setup(__props, { expose: __expose }) { __expose(); return { a } } }" `; exports[`SFC analyze <script> bindings > auto name inference > do not overwrite manual name (call) 1`] = ` "import { defineComponent } from 'vue' const __default__ = defineComponent({ name: 'Baz' }) export default /*#__PURE__*/Object.assign(__default__, { setup(__props, { expose: __expose }) { __expose(); const a = 1 return { a, defineComponent } } })" `; exports[`SFC analyze <script> bindings > auto name inference > do not overwrite manual name (object) 1`] = ` "const __default__ = { name: 'Baz' } export default /*#__PURE__*/Object.assign(__default__, { setup(__props, { expose: __expose }) { __expose(); const a = 1 return { a } } })" `; exports[`SFC compile <script setup> > <script> and <script setup> co-usage > export call expression as default 1`] = ` "function fn() { return \\"hello, world\\"; } const __default__ = fn(); export default /*#__PURE__*/Object.assign(__default__, { setup(__props, { expose: __expose }) { __expose(); console.log('foo') return { fn } } })" `; exports[`SFC compile <script setup> > <script> and <script setup> co-usage > script first 1`] = ` "import { x } from './x' export const n = 1 const __default__ = {} export default /*#__PURE__*/Object.assign(__default__, { setup(__props, { expose: __expose }) { __expose(); x() return { n, get x() { return x } } } })" `; exports[`SFC compile <script setup> > <script> and <script setup> co-usage > script setup first 1`] = ` "import { x } from './x' export const n = 1 const __default__ = {} export default /*#__PURE__*/Object.assign(__default__, { setup(__props, { expose: __expose }) { __expose(); x() return { n, get x() { return x } } } })" `; exports[`SFC compile <script setup> > <script> and <script setup> co-usage > script setup first, lang="ts", script block content export default 1`] = ` "import { defineComponent as _defineComponent } from 'vue' import { x } from './x' const __default__ = { name: \\"test\\" } export default /*#__PURE__*/_defineComponent({ ...__default__, setup(__props, { expose: __expose }) { __expose(); x() return { get x() { return x } } } })" `; exports[`SFC compile <script setup> > <script> and <script setup> co-usage > script setup first, named default export 1`] = ` "import { x } from './x' export const n = 1 const def = {} const __default__ = def export default /*#__PURE__*/Object.assign(__default__, { setup(__props, { expose: __expose }) { __expose(); x() return { n, def, get x() { return x } } } })" `; exports[`SFC compile <script setup> > <script> and <script setup> co-usage > spaces in ExportDefaultDeclaration node > with many spaces and newline 1`] = ` "import { x } from './x' export const n = 1 const __default__ = { some:'option' } export default /*#__PURE__*/Object.assign(__default__, { setup(__props, { expose: __expose }) { __expose(); x() return { n, get x() { return x } } } })" `; exports[`SFC compile <script setup> > <script> and <script setup> co-usage > spaces in ExportDefaultDeclaration node > with minimal spaces 1`] = ` "import { x } from './x' export const n = 1 const __default__ = { some:'option' } export default /*#__PURE__*/Object.assign(__default__, { setup(__props, { expose: __expose }) { __expose(); x() return { n, get x() { return x } } } })" `; exports[`SFC compile <script setup> > async/await detection > expression statement 1`] = ` "import { withAsyncContext as _withAsyncContext } from 'vue' export default { async setup(__props, { expose: __expose }) { __expose(); let __temp, __restore ;( ([__temp,__restore] = _withAsyncContext(() => foo)), await __temp, __restore() ) return { } } }" `; exports[`SFC compile <script setup> > async/await detection > multiple \`if for\` nested statements 1`] = ` "import { withAsyncContext as _withAsyncContext } from 'vue' export default { async setup(__props, { expose: __expose }) { __expose(); let __temp, __restore if (ok) { for (let a of [1,2,3]) { ( ([__temp,__restore] = _withAsyncContext(() => a)), await __temp, __restore() ) } for (let a of [1,2,3]) { ( ([__temp,__restore] = _withAsyncContext(() => a)), await __temp, __restore() ) ;( ([__temp,__restore] = _withAsyncContext(() => a)), await __temp, __restore() ) } } return { } } }" `; exports[`SFC compile <script setup> > async/await detection > multiple \`if while\` nested statements 1`] = ` "import { withAsyncContext as _withAsyncContext } from 'vue' export default { async setup(__props, { expose: __expose }) { __expose(); let __temp, __restore if (ok) { while (d) { ( ([__temp,__restore] = _withAsyncContext(() => 5)), await __temp, __restore() ) } while (d) { ( ([__temp,__restore] = _withAsyncContext(() => 5)), await __temp, __restore() ) ;( ([__temp,__restore] = _withAsyncContext(() => 6)), await __temp, __restore() ) if (c) { let f = 10 10 + ( ([__temp,__restore] = _withAsyncContext(() => 7)), __temp = await __temp, __restore(), __temp ) } else { ( ([__temp,__restore] = _withAsyncContext(() => 8)), await __temp, __restore() ) ;( ([__temp,__restore] = _withAsyncContext(() => 9)), await __temp, __restore() ) } } } return { } } }" `; exports[`SFC compile <script setup> > async/await detection > multiple \`if\` nested statements 1`] = ` "import { withAsyncContext as _withAsyncContext } from 'vue' export default { async setup(__props, { expose: __expose }) { __expose(); let __temp, __restore if (ok) { let a = 'foo' ;( ([__temp,__restore] = _withAsyncContext(() => 0)), __temp = await __temp, __restore(), __temp ) + ( ([__temp,__restore] = _withAsyncContext(() => 1)), __temp = await __temp, __restore(), __temp ) ;( ([__temp,__restore] = _withAsyncContext(() => 2)), await __temp, __restore() ) } else if (a) { ( ([__temp,__restore] = _withAsyncContext(() => 10)), await __temp, __restore() ) if (b) { ( ([__temp,__restore] = _withAsyncContext(() => 0)), __temp = await __temp, __restore(), __temp ) + ( ([__temp,__restore] = _withAsyncContext(() => 1)), __temp = await __temp, __restore(), __temp ) } else { let a = 'foo' ;( ([__temp,__restore] = _withAsyncContext(() => 2)), await __temp, __restore() ) } if (b) { ( ([__temp,__restore] = _withAsyncContext(() => 3)), await __temp, __restore() ) ;( ([__temp,__restore] = _withAsyncContext(() => 4)), await __temp, __restore() ) } } else { ( ([__temp,__restore] = _withAsyncContext(() => 5)), await __temp, __restore() ) } return { } } }" `; exports[`SFC compile <script setup> > async/await detection > nested await 1`] = ` "import { withAsyncContext as _withAsyncContext } from 'vue' export default { async setup(__props, { expose: __expose }) { __expose(); let __temp, __restore ;( ([__temp,__restore] = _withAsyncContext(async () => (( ([__temp,__restore] = _withAsyncContext(() => foo)), __temp = await __temp, __restore(), __temp )))), await __temp, __restore() ) return { } } }" `; exports[`SFC compile <script setup> > async/await detection > nested await 2`] = ` "import { withAsyncContext as _withAsyncContext } from 'vue' export default { async setup(__props, { expose: __expose }) { __expose(); let __temp, __restore ;( ([__temp,__restore] = _withAsyncContext(async () => ((( ([__temp,__restore] = _withAsyncContext(() => foo)), __temp = await __temp, __restore(), __temp ))))), await __temp, __restore() ) return { } } }" `; exports[`SFC compile <script setup> > async/await detection > nested await 3`] = ` "import { withAsyncContext as _withAsyncContext } from 'vue' export default { async setup(__props, { expose: __expose }) { __expose(); let __temp, __restore ;( ([__temp,__restore] = _withAsyncContext(async () => (( ([__temp,__restore] = _withAsyncContext(async () => (( ([__temp,__restore] = _withAsyncContext(() => foo)), __temp = await __temp, __restore(), __temp )))), __temp = await __temp, __restore(), __temp )))), await __temp, __restore() ) return { } } }" `; exports[`SFC compile <script setup> > async/await detection > nested leading await in expression statement 1`] = ` "import { withAsyncContext as _withAsyncContext } from 'vue' export default { async setup(__props, { expose: __expose }) { __expose(); let __temp, __restore foo() ;( ([__temp,__restore] = _withAsyncContext(() => 1)), __temp = await __temp, __restore(), __temp ) + ( ([__temp,__restore] = _withAsyncContext(() => 2)), __temp = await __temp, __restore(), __temp ) return { } } }" `; exports[`SFC compile <script setup> > async/await detection > nested statements 1`] = ` "import { withAsyncContext as _withAsyncContext } from 'vue' export default { async setup(__props, { expose: __expose }) { __expose(); let __temp, __restore if (ok) { ( ([__temp,__restore] = _withAsyncContext(() => foo)), await __temp, __restore() ) } else { ( ([__temp,__restore] = _withAsyncContext(() => bar)), await __temp, __restore() ) } return { } } }" `; exports[`SFC compile <script setup> > async/await detection > ref 1`] = ` "import { withAsyncContext as _withAsyncContext, ref as _ref } from 'vue' export default { async setup(__props, { expose: __expose }) { __expose(); let __temp, __restore let a = _ref(1 + (( ([__temp,__restore] = _withAsyncContext(() => foo)), __temp = await __temp, __restore(), __temp ))) return { a } } }" `; exports[`SFC compile <script setup> > async/await detection > should ignore await inside functions 1`] = ` "export default { setup(__props, { expose: __expose }) { __expose(); async function foo() { await bar } return { foo } } }" `; exports[`SFC compile <script setup> > async/await detection > should ignore await inside functions 2`] = ` "export default { setup(__props, { expose: __expose }) { __expose(); const foo = async () => { await bar } return { foo } } }" `; exports[`SFC compile <script setup> > async/await detection > should ignore await inside functions 3`] = ` "export default { setup(__props, { expose: __expose }) { __expose(); const obj = { async method() { await bar }} return { obj } } }" `; exports[`SFC compile <script setup> > async/await detection > should ignore await inside functions 4`] = ` "export default { setup(__props, { expose: __expose }) { __expose(); const cls = class Foo { async method() { await bar }} return { cls } } }" `; exports[`SFC compile <script setup> > async/await detection > single line conditions 1`] = ` "import { withAsyncContext as _withAsyncContext } from 'vue' export default { async setup(__props, { expose: __expose }) { __expose(); let __temp, __restore if (false) ( ([__temp,__restore] = _withAsyncContext(() => foo())), await __temp, __restore() ) return { } } }" `; exports[`SFC compile <script setup> > async/await detection > variable 1`] = ` "import { withAsyncContext as _withAsyncContext } from 'vue' export default { async setup(__props, { expose: __expose }) { __expose(); let __temp, __restore const a = 1 + (( ([__temp,__restore] = _withAsyncContext(() => foo)), __temp = await __temp, __restore(), __temp )) return { a } } }" `; exports[`SFC compile <script setup> > binding analysis for destructure 1`] = ` "export default { setup(__props, { expose: __expose }) { __expose(); const { foo, b: bar, ['x' + 'y']: baz, x: { y, zz: { z }}} = {} return { foo, bar, baz, y, z } } }" `; exports[`SFC compile <script setup> > defineProps/defineEmits in multi-variable declaration (full removal) 1`] = ` "export default { props: ['item'], emits: ['a'], setup(__props, { expose: __expose, emit }) { __expose(); const props = __props; return { props, emit } } }" `; exports[`SFC compile <script setup> > defineProps/defineEmits in multi-variable declaration 1`] = ` "export default { props: ['item'], emits: ['a'], setup(__props, { expose: __expose, emit }) { __expose(); const props = __props; const a = 1; return { props, a, emit } } }" `; exports[`SFC compile <script setup> > defineProps/defineEmits in multi-variable declaration fix #6757 1`] = ` "export default { props: ['item'], emits: ['a'], setup(__props, { expose: __expose, emit }) { __expose(); const props = __props; const a = 1; return { a, props, emit } } }" `; exports[`SFC compile <script setup> > defineProps/defineEmits in multi-variable declaration fix #7422 1`] = ` "export default { props: ['item'], emits: ['foo'], setup(__props, { expose: __expose, emit: emits }) { __expose(); const props = __props; const a = 0, b = 0; return { props, emits, a, b } } }" `; exports[`SFC compile <script setup> > dev mode import usage check > TS annotations 1`] = ` "import { defineComponent as _defineComponent } from 'vue' import { Foo, Bar, Baz, Qux, Fred } from './x' const a = 1 export default /*#__PURE__*/_defineComponent({ setup(__props, { expose: __expose }) { __expose(); function b() {} return { a, b, get Baz() { return Baz } } } })" `; exports[`SFC compile <script setup> > dev mode import usage check > attribute expressions 1`] = ` "import { defineComponent as _defineComponent } from 'vue' import { bar, baz } from './x' const cond = true export default /*#__PURE__*/_defineComponent({ setup(__props, { expose: __expose }) { __expose(); return { cond, get bar() { return bar }, get baz() { return baz } } } })" `; exports[`SFC compile <script setup> > dev mode import usage check > components 1`] = ` "import { defineComponent as _defineComponent } from 'vue' import { FooBar, FooBaz, FooQux, foo } from './x' const fooBar: FooBar = 1 export default /*#__PURE__*/_defineComponent({ setup(__props, { expose: __expose }) { __expose(); return { fooBar, get FooBaz() { return FooBaz }, get FooQux() { return FooQux }, get foo() { return foo } } } })" `; exports[`SFC compile <script setup> > dev mode import usage check > directive 1`] = ` "import { defineComponent as _defineComponent } from 'vue' import { vMyDir } from './x' export default /*#__PURE__*/_defineComponent({ setup(__props, { expose: __expose }) { __expose(); return { get vMyDir() { return vMyDir } } } })" `; exports[`SFC compile <script setup> > dev mode import usage check > js template string interpolations 1`] = ` "import { defineComponent as _defineComponent } from 'vue' import { VAR, VAR2, VAR3 } from './x' export default /*#__PURE__*/_defineComponent({ setup(__props, { expose: __expose }) { __expose(); return { get VAR() { return VAR }, get VAR3() { return VAR3 } } } })" `; exports[`SFC compile <script setup> > dev mode import usage check > last tag 1`] = ` "import { defineComponent as _defineComponent } from 'vue' import { FooBaz, Last } from './x' export default /*#__PURE__*/_defineComponent({ setup(__props, { expose: __expose }) { __expose(); return { get FooBaz() { return FooBaz }, get Last() { return Last } } } })" `; exports[`SFC compile <script setup> > dev mode import usage check > vue interpolations 1`] = ` "import { defineComponent as _defineComponent } from 'vue' import { x, y, z, x$y } from './x' export default /*#__PURE__*/_defineComponent({ setup(__props, { expose: __expose }) { __expose(); return { get x() { return x }, get z() { return z }, get x$y() { return x$y } } } })" `; exports[`SFC compile <script setup> > errors > should allow defineProps/Emit() referencing imported binding 1`] = ` "import { bar } from './bar' export default { props: { foo: { default: () => bar } }, emits: { foo: () => bar > 1 }, setup(__props, { expose: __expose }) { __expose(); return { get bar() { return bar } } } }" `; exports[`SFC compile <script setup> > errors > should allow defineProps/Emit() referencing scope var 1`] = ` "const bar = 1 export default { props: { foo: { default: bar => bar + 1 } }, emits: { foo: bar => bar > 1 }, setup(__props, { expose: __expose }) { __expose(); return { bar } } }" `; exports[`SFC compile <script setup> > imports > dedupe between user & helper 1`] = ` "import { ref as _ref } from 'vue' import { ref } from 'vue' export default { setup(__props, { expose: __expose }) { __expose(); let foo = _ref(1) return { foo, ref } } }" `; exports[`SFC compile <script setup> > imports > import dedupe between <script> and <script setup> 1`] = ` "import { x } from './x' export default { setup(__props, { expose: __expose }) { __expose(); x() return { get x() { return x } } } }" `; exports[`SFC compile <script setup> > imports > should allow defineProps/Emit at the start of imports 1`] = ` "import { ref } from 'vue' export default { props: ['foo'], emits: ['bar'], setup(__props, { expose: __expose }) { __expose(); const r = ref(0) return { r, ref } } }" `; exports[`SFC compile <script setup> > imports > should extract comment for import or type declarations 1`] = ` "import a from 'a' // comment import b from 'b' export default { setup(__props, { expose: __expose }) { __expose(); return { get a() { return a }, get b() { return b } } } }" `; exports[`SFC compile <script setup> > imports > should hoist and expose imports 1`] = ` "import { ref } from 'vue' import 'foo/css' export default { setup(__props, { expose: __expose }) { __expose(); return { ref } } }" `; exports[`SFC compile <script setup> > imports > should support module string names syntax 1`] = ` "import { \\"😏\\" as foo } from './foo' export default { setup(__props, { expose: __expose }) { __expose(); return { get foo() { return foo } } } }" `; exports[`SFC compile <script setup> > inlineTemplate mode > avoid unref() when necessary 1`] = ` "import { unref as _unref, toDisplayString as _toDisplayString, createTextVNode as _createTextVNode, withCtx as _withCtx, createVNode as _createVNode, createElementVNode as _createElementVNode, Fragment as _Fragment, openBlock as _openBlock, createElementBlock as _createElementBlock } from \\"vue\\" import { ref } from 'vue' import Foo, { bar } from './Foo.vue' import other from './util' import * as tree from './tree' export default { setup(__props) { const count = ref(0) const constant = {} const maybe = foo() let lett = 1 function fn() {} return (_ctx, _cache) => { return (_openBlock(), _createElementBlock(_Fragment, null, [ _createVNode(Foo, null, { default: _withCtx(() => [ _createTextVNode(_toDisplayString(_unref(bar)), 1 /* TEXT */) ]), _: 1 /* STABLE */ }), _createElementVNode(\\"div\\", { onClick: fn }, _toDisplayString(count.value) + \\" \\" + _toDisplayString(constant) + \\" \\" + _toDisplayString(_unref(maybe)) + \\" \\" + _toDisplayString(_unref(lett)) + \\" \\" + _toDisplayString(_unref(other)), 1 /* TEXT */), _createTextVNode(\\" \\" + _toDisplayString(tree.foo()), 1 /* TEXT */) ], 64 /* STABLE_FRAGMENT */)) } } }" `; exports[`SFC compile <script setup> > inlineTemplate mode > referencing scope components and directives 1`] = ` "import { unref as _unref, createElementVNode as _createElementVNode, withDirectives as _withDirectives, createVNode as _createVNode, Fragment as _Fragment, openBlock as _openBlock, createElementBlock as _createElementBlock } from \\"vue\\" import ChildComp from './Child.vue' import SomeOtherComp from './Other.vue' import vMyDir from './my-dir' export default { setup(__props) { return (_ctx, _cache) => { return (_openBlock(), _createElementBlock(_Fragment, null, [ _withDirectives(_createElementVNode(\\"div\\", null, null, 512 /* NEED_PATCH */), [ [_unref(vMyDir)] ]), _createVNode(ChildComp), _createVNode(SomeOtherComp) ], 64 /* STABLE_FRAGMENT */)) } } }" `; exports[`SFC compile <script setup> > inlineTemplate mode > should work 1`] = ` "import { toDisplayString as _toDisplayString, createElementVNode as _createElementVNode, Fragment as _Fragment, openBlock as _openBlock, createElementBlock as _createElementBlock } from \\"vue\\" const _hoisted_1 = /*#__PURE__*/_createElementVNode(\\"div\\", null, \\"static\\", -1 /* HOISTED */) import { ref } from 'vue' export default { setup(__props) { const count = ref(0) return (_ctx, _cache) => { return (_openBlock(), _createElementBlock(_Fragment, null, [ _createElementVNode(\\"div\\", null, _toDisplayString(count.value), 1 /* TEXT */), _hoisted_1 ], 64 /* STABLE_FRAGMENT */)) } } }" `; exports[`SFC compile <script setup> > inlineTemplate mode > ssr codegen 1`] = ` "import { ssrRenderAttrs as _ssrRenderAttrs, ssrInterpolate as _ssrInterpolate } from \\"vue/server-renderer\\" import { ref } from 'vue' export default { __ssrInlineRender: true, setup(__props) { const count = ref(0) return (_ctx, _push, _parent, _attrs) => { const _cssVars = { style: { \\"--xxxxxxxx-count\\": (count.value) }} _push(\`<!--[--><div\${ _ssrRenderAttrs(_cssVars) }>\${ _ssrInterpolate(count.value) }</div><div\${ _ssrRenderAttrs(_cssVars) }>static</div><!--]-->\`) } } }" `; exports[`SFC compile <script setup> > inlineTemplate mode > template assignment expression codegen 1`] = ` "import { createElementVNode as _createElementVNode, isRef as _isRef, unref as _unref, Fragment as _Fragment, openBlock as _openBlock, createElementBlock as _createElementBlock } from \\"vue\\" import { ref } from 'vue' export default { setup(__props) { const count = ref(0) const maybe = foo() let lett = 1 let v = ref(1) return (_ctx, _cache) => { return (_openBlock(), _createElementBlock(_Fragment, null, [ _createElementVNode(\\"div\\", { onClick: _cache[0] || (_cache[0] = $event => (count.value = 1)) }), _createElementVNode(\\"div\\", { onClick: _cache[1] || (_cache[1] = $event => (maybe.value = count.value)) }), _createElementVNode(\\"div\\", { onClick: _cache[2] || (_cache[2] = $event => (_isRef(lett) ? lett.value = count.value : lett = count.value)) }), _createElementVNode(\\"div\\", { onClick: _cache[3] || (_cache[3] = $event => (_isRef(v) ? v.value += 1 : v += 1)) }), _createElementVNode(\\"div\\", { onClick: _cache[4] || (_cache[4] = $event => (_isRef(v) ? v.value -= 1 : v -= 1)) }), _createElementVNode(\\"div\\", { onClick: _cache[5] || (_cache[5] = () => { let a = '' + _unref(lett) _isRef(v) ? v.value = a : v = a }) }), _createElementVNode(\\"div\\", { onClick: _cache[6] || (_cache[6] = () => { // nested scopes (()=>{ let x = _ctx.a (()=>{ let z = x let z2 = z }) let lz = _ctx.z }) _isRef(v) ? v.value = _ctx.a : v = _ctx.a }) }) ], 64 /* STABLE_FRAGMENT */)) } } }" `; exports[`SFC compile <script setup> > inlineTemplate mode > template destructure assignment codegen 1`] = ` "import { createElementVNode as _createElementVNode, Fragment as _Fragment, openBlock as _openBlock, createElementBlock as _createElementBlock } from \\"vue\\" import { ref } from 'vue' export default { setup(__props) { const val = {} const count = ref(0) const maybe = foo() let lett = 1 return (_ctx, _cache) => { return (_openBlock(), _createElementBlock(_Fragment, null, [ _createElementVNode(\\"div\\", { onClick: _cache[0] || (_cache[0] = $event => (({ count: count.value } = val))) }), _createElementVNode(\\"div\\", { onClick: _cache[1] || (_cache[1] = $event => ([maybe.value] = val)) }), _createElementVNode(\\"div\\", { onClick: _cache[2] || (_cache[2] = $event => (({ lett: lett } = val))) }) ], 64 /* STABLE_FRAGMENT */)) } } }" `; exports[`SFC compile <script setup> > inlineTemplate mode > template update expression codegen 1`] = ` "import { createElementVNode as _createElementVNode, isRef as _isRef, Fragment as _Fragment, openBlock as _openBlock, createElementBlock as _createElementBlock } from \\"vue\\" import { ref } from 'vue' export default { setup(__props) { const count = ref(0) const maybe = foo() let lett = 1 return (_ctx, _cache) => { return (_openBlock(), _createElementBlock(_Fragment, null, [ _createElementVNode(\\"div\\", { onClick: _cache[0] || (_cache[0] = $event => (count.value++)) }), _createElementVNode(\\"div\\", { onClick: _cache[1] || (_cache[1] = $event => (--count.value)) }), _createElementVNode(\\"div\\", { onClick: _cache[2] || (_cache[2] = $event => (maybe.value++)) }), _createElementVNode(\\"div\\", { onClick: _cache[3] || (_cache[3] = $event => (--maybe.value)) }), _createElementVNode(\\"div\\", { onClick: _cache[4] || (_cache[4] = $event => (_isRef(lett) ? lett.value++ : lett++)) }), _createElementVNode(\\"div\\", { onClick: _cache[5] || (_cache[5] = $event => (_isRef(lett) ? --lett.value : --lett)) }) ], 64 /* STABLE_FRAGMENT */)) } } }" `; exports[`SFC compile <script setup> > inlineTemplate mode > v-model codegen 1`] = ` "import { vModelText as _vModelText, createElementVNode as _createElementVNode, withDirectives as _withDirectives, unref as _unref, isRef as _isRef, Fragment as _Fragment, openBlock as _openBlock, createElementBlock as _createElementBlock } from \\"vue\\" import { ref } from 'vue' export default { setup(__props) { const count = ref(0) const maybe = foo() let lett = 1 return (_ctx, _cache) => { return (_openBlock(), _createElementBlock(_Fragment, null, [ _withDirectives(_createElementVNode(\\"input\\", { \\"onUpdate:modelValue\\": _cache[0] || (_cache[0] = $event => ((count).value = $event)) }, null, 512 /* NEED_PATCH */), [ [_vModelText, count.value] ]), _withDirectives(_createElementVNode(\\"input\\", { \\"onUpdate:modelValue\\": _cache[1] || (_cache[1] = $event => (_isRef(maybe) ? (maybe).value = $event : null)) }, null, 512 /* NEED_PATCH */), [ [_vModelText, _unref(maybe)] ]), _withDirectives(_createElementVNode(\\"input\\", { \\"onUpdate:modelValue\\": _cache[2] || (_cache[2] = $event => (_isRef(lett) ? (lett).value = $event : lett = $event)) }, null, 512 /* NEED_PATCH */), [ [_vModelText, _unref(lett)] ]) ], 64 /* STABLE_FRAGMENT */)) } } }" `; exports[`SFC compile <script setup> > inlineTemplate mode > with defineExpose() 1`] = ` "export default { setup(__props, { expose: __expose }) { const count = ref(0) __expose({ count }) return () => {} } }" `; exports[`SFC compile <script setup> > should compile JS syntax 1`] = ` "const a = 1 const b = 2 export default { setup(__props, { expose: __expose }) { __expose(); return { a, b } } }" `; exports[`SFC compile <script setup> > should expose top level declarations 1`] = ` "import { x } from './x' import { xx } from './x' let aa = 1 const bb = 2 function cc() {} class dd {} export default { setup(__props, { expose: __expose }) { __expose(); let a = 1 const b = 2 function c() {} class d {} return { get aa() { return aa }, set aa(v) { aa = v }, bb, cc, dd, get a() { return a }, set a(v) { a = v }, b, c, d, get xx() { return xx }, get x() { return x } } } }" `; exports[`SFC compile <script setup> > with TypeScript > const Enum 1`] = ` "import { defineComponent as _defineComponent } from 'vue' const enum Foo { A = 123 } export default /*#__PURE__*/_defineComponent({ setup(__props, { expose: __expose }) { __expose(); return { Foo } } })" `; exports[`SFC compile <script setup> > with TypeScript > hoist type declarations 1`] = ` "import { defineComponent as _defineComponent } from 'vue' export interface Foo {} type Bar = {} export default /*#__PURE__*/_defineComponent({ setup(__props, { expose: __expose }) { __expose(); return { } } })" `; exports[`SFC compile <script setup> > with TypeScript > import type 1`] = ` "import { defineComponent as _defineComponent } from 'vue' import type { Foo } from './main.ts' import { type Bar, Baz } from './main.ts' export default /*#__PURE__*/_defineComponent({ setup(__props, { expose: __expose }) { __expose(); return { get Baz() { return Baz } } } })" `; exports[`SFC compile <script setup> > with TypeScript > runtime Enum 1`] = ` "import { defineComponent as _defineComponent } from 'vue' enum Foo { A = 123 } export default /*#__PURE__*/_defineComponent({ setup(__props, { expose: __expose }) { __expose(); return { Foo } } })" `; exports[`SFC compile <script setup> > with TypeScript > runtime Enum in normal script 1`] = ` "import { defineComponent as _defineComponent } from 'vue' export enum D { D = \\"D\\" } const enum C { C = \\"C\\" } enum B { B = \\"B\\" } export default /*#__PURE__*/_defineComponent({ setup(__props, { expose: __expose }) { __expose(); enum Foo { A = 123 } return { D, C, B, Foo } } })" `; exports[`SFC genDefaultAs > <script setup> only 1`] = ` "const a = 1 const _sfc_ = { setup(__props, { expose: __expose }) { __expose(); return { a } } }" `; exports[`SFC genDefaultAs > <script setup> only w/ ts 1`] = ` "import { defineComponent as _defineComponent } from 'vue' const a = 1 const _sfc_ = /*#__PURE__*/_defineComponent({ setup(__props, { expose: __expose }) { __expose(); return { a } } })" `; exports[`SFC genDefaultAs > <script> + <script setup> 1`] = ` "const __default__ = {} const _sfc_ = /*#__PURE__*/Object.assign(__default__, { setup(__props, { expose: __expose }) { __expose(); const a = 1 return { a } } })" `; exports[`SFC genDefaultAs > <script> + <script setup> 2`] = ` "const __default__ = {} const _sfc_ = /*#__PURE__*/Object.assign(__default__, { setup(__props, { expose: __expose }) { __expose(); const a = 1 return { a } } })" `; exports[`SFC genDefaultAs > <script> + <script setup> w/ ts 1`] = ` "import { defineComponent as _defineComponent } from 'vue' const __default__ = {} const _sfc_ = /*#__PURE__*/_defineComponent({ ...__default__, setup(__props, { expose: __expose }) { __expose(); const a = 1 return { a } } })" `; exports[`SFC genDefaultAs > normal <script> only 1`] = ` " const _sfc_ = {} " `; exports[`SFC genDefaultAs > normal <script> w/ cssVars 1`] = ` " const _sfc_ = {} import { useCssVars as _useCssVars } from 'vue' const __injectCSSVars__ = () => { _useCssVars(_ctx => ({ \\"xxxxxxxx-x\\": (_ctx.x) }))} const __setup__ = _sfc_.setup _sfc_.setup = __setup__ ? (props, ctx) => { __injectCSSVars__();return __setup__(props, ctx) } : __injectCSSVars__ " `;
packages/compiler-sfc/__tests__/__snapshots__/compileScript.spec.ts.snap
0
https://github.com/vuejs/core/commit/3cb4dc9e5538e1c2bde9fa691b001615a848c546
[ 0.00043638868373818696, 0.00017700044554658234, 0.00016483658691868186, 0.000170610161148943, 0.000027720656362362206 ]
{ "id": 0, "code_window": [ "export const BaseTransition = BaseTransitionImpl as unknown as {\n", " new (): {\n", " $props: BaseTransitionProps<any>\n", " }\n", "}\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " $slots: {\n", " default(): VNode[]\n", " }\n" ], "file_path": "packages/runtime-core/src/components/BaseTransition.ts", "type": "add", "edit_start_line_idx": 285 }
import { vi } from 'vitest' import { reactive, effect, toRaw, isReactive } from '../../src' describe('reactivity/collections', () => { function coverCollectionFn(collection: Map<any, any>, fnName: string) { const spy = vi.fn() let proxy = reactive(collection) ;(collection as any)[fnName] = spy return [proxy as any, spy] } describe('Map', () => { test('instanceof', () => { const original = new Map() const observed = reactive(original) expect(isReactive(observed)).toBe(true) expect(original instanceof Map).toBe(true) expect(observed instanceof Map).toBe(true) }) it('should observe mutations', () => { let dummy const map = reactive(new Map()) effect(() => { dummy = map.get('key') }) expect(dummy).toBe(undefined) map.set('key', 'value') expect(dummy).toBe('value') map.set('key', 'value2') expect(dummy).toBe('value2') map.delete('key') expect(dummy).toBe(undefined) }) it('should observe mutations with observed value as key', () => { let dummy const key = reactive({}) const value = reactive({}) const map = reactive(new Map()) effect(() => { dummy = map.get(key) }) expect(dummy).toBe(undefined) map.set(key, value) expect(dummy).toBe(value) map.delete(key) expect(dummy).toBe(undefined) }) it('should observe size mutations', () => { let dummy const map = reactive(new Map()) effect(() => (dummy = map.size)) expect(dummy).toBe(0) map.set('key1', 'value') map.set('key2', 'value2') expect(dummy).toBe(2) map.delete('key1') expect(dummy).toBe(1) map.clear() expect(dummy).toBe(0) }) it('should observe for of iteration', () => { let dummy const map = reactive(new Map()) effect(() => { dummy = 0 // eslint-disable-next-line no-unused-vars for (let [key, num] of map) { key dummy += num } }) expect(dummy).toBe(0) map.set('key1', 3) expect(dummy).toBe(3) map.set('key2', 2) expect(dummy).toBe(5) // iteration should track mutation of existing entries (#709) map.set('key1', 4) expect(dummy).toBe(6) map.delete('key1') expect(dummy).toBe(2) map.clear() expect(dummy).toBe(0) }) it('should observe forEach iteration', () => { let dummy: any const map = reactive(new Map()) effect(() => { dummy = 0 map.forEach((num: any) => (dummy += num)) }) expect(dummy).toBe(0) map.set('key1', 3) expect(dummy).toBe(3) map.set('key2', 2) expect(dummy).toBe(5) // iteration should track mutation of existing entries (#709) map.set('key1', 4) expect(dummy).toBe(6) map.delete('key1') expect(dummy).toBe(2) map.clear() expect(dummy).toBe(0) }) it('should observe keys iteration', () => { let dummy const map = reactive(new Map()) effect(() => { dummy = 0 for (let key of map.keys()) { dummy += key } }) expect(dummy).toBe(0) map.set(3, 3) expect(dummy).toBe(3) map.set(2, 2) expect(dummy).toBe(5) map.delete(3) expect(dummy).toBe(2) map.clear() expect(dummy).toBe(0) }) it('should observe values iteration', () => { let dummy const map = reactive(new Map()) effect(() => { dummy = 0 for (let num of map.values()) { dummy += num } }) expect(dummy).toBe(0) map.set('key1', 3) expect(dummy).toBe(3) map.set('key2', 2) expect(dummy).toBe(5) // iteration should track mutation of existing entries (#709) map.set('key1', 4) expect(dummy).toBe(6) map.delete('key1') expect(dummy).toBe(2) map.clear() expect(dummy).toBe(0) }) it('should observe entries iteration', () => { let dummy let dummy2 const map = reactive(new Map()) effect(() => { dummy = '' dummy2 = 0 // eslint-disable-next-line no-unused-vars for (let [key, num] of map.entries()) { dummy += key dummy2 += num } }) expect(dummy).toBe('') expect(dummy2).toBe(0) map.set('key1', 3) expect(dummy).toBe('key1') expect(dummy2).toBe(3) map.set('key2', 2) expect(dummy).toBe('key1key2') expect(dummy2).toBe(5) // iteration should track mutation of existing entries (#709) map.set('key1', 4) expect(dummy).toBe('key1key2') expect(dummy2).toBe(6) map.delete('key1') expect(dummy).toBe('key2') expect(dummy2).toBe(2) map.clear() expect(dummy).toBe('') expect(dummy2).toBe(0) }) it('should be triggered by clearing', () => { let dummy const map = reactive(new Map()) effect(() => (dummy = map.get('key'))) expect(dummy).toBe(undefined) map.set('key', 3) expect(dummy).toBe(3) map.clear() expect(dummy).toBe(undefined) }) it('should not observe custom property mutations', () => { let dummy const map: any = reactive(new Map()) effect(() => (dummy = map.customProp)) expect(dummy).toBe(undefined) map.customProp = 'Hello World' expect(dummy).toBe(undefined) }) it('should not observe non value changing mutations', () => { let dummy const map = reactive(new Map()) const mapSpy = vi.fn(() => (dummy = map.get('key'))) effect(mapSpy) expect(dummy).toBe(undefined) expect(mapSpy).toHaveBeenCalledTimes(1) map.set('key', undefined) expect(dummy).toBe(undefined) expect(mapSpy).toHaveBeenCalledTimes(2) map.set('key', 'value') expect(dummy).toBe('value') expect(mapSpy).toHaveBeenCalledTimes(3) map.set('key', 'value') expect(dummy).toBe('value') expect(mapSpy).toHaveBeenCalledTimes(3) map.delete('key') expect(dummy).toBe(undefined) expect(mapSpy).toHaveBeenCalledTimes(4) map.delete('key') expect(dummy).toBe(undefined) expect(mapSpy).toHaveBeenCalledTimes(4) map.clear() expect(dummy).toBe(undefined) expect(mapSpy).toHaveBeenCalledTimes(4) }) it('should not observe raw data', () => { let dummy const map = reactive(new Map()) effect(() => (dummy = toRaw(map).get('key'))) expect(dummy).toBe(undefined) map.set('key', 'Hello') expect(dummy).toBe(undefined) map.delete('key') expect(dummy).toBe(undefined) }) it('should not pollute original Map with Proxies', () => { const map = new Map() const observed = reactive(map) const value = reactive({}) observed.set('key', value) expect(map.get('key')).not.toBe(value) expect(map.get('key')).toBe(toRaw(value)) }) it('should return observable versions of contained values', () => { const observed = reactive(new Map()) const value = {} observed.set('key', value) const wrapped = observed.get('key') expect(isReactive(wrapped)).toBe(true) expect(toRaw(wrapped)).toBe(value) }) it('should observed nested data', () => { const observed = reactive(new Map()) observed.set('key', { a: 1 }) let dummy effect(() => { dummy = observed.get('key').a }) observed.get('key').a = 2 expect(dummy).toBe(2) }) it('should observe nested values in iterations (forEach)', () => { const map = reactive(new Map([[1, { foo: 1 }]])) let dummy: any effect(() => { dummy = 0 map.forEach(value => { expect(isReactive(value)).toBe(true) dummy += value.foo }) }) expect(dummy).toBe(1) map.get(1)!.foo++ expect(dummy).toBe(2) }) it('should observe nested values in iterations (values)', () => { const map = reactive(new Map([[1, { foo: 1 }]])) let dummy: any effect(() => { dummy = 0 for (const value of map.values()) { expect(isReactive(value)).toBe(true) dummy += value.foo } }) expect(dummy).toBe(1) map.get(1)!.foo++ expect(dummy).toBe(2) }) it('should observe nested values in iterations (entries)', () => { const key = {} const map = reactive(new Map([[key, { foo: 1 }]])) let dummy: any effect(() => { dummy = 0 for (const [key, value] of map.entries()) { key expect(isReactive(key)).toBe(true) expect(isReactive(value)).toBe(true) dummy += value.foo } }) expect(dummy).toBe(1) map.get(key)!.foo++ expect(dummy).toBe(2) }) it('should observe nested values in iterations (for...of)', () => { const key = {} const map = reactive(new Map([[key, { foo: 1 }]])) let dummy: any effect(() => { dummy = 0 for (const [key, value] of map) { key expect(isReactive(key)).toBe(true) expect(isReactive(value)).toBe(true) dummy += value.foo } }) expect(dummy).toBe(1) map.get(key)!.foo++ expect(dummy).toBe(2) }) it('should not be trigger when the value and the old value both are NaN', () => { const map = reactive(new Map([['foo', NaN]])) const mapSpy = vi.fn(() => map.get('foo')) effect(mapSpy) map.set('foo', NaN) expect(mapSpy).toHaveBeenCalledTimes(1) }) it('should work with reactive keys in raw map', () => { const raw = new Map() const key = reactive({}) raw.set(key, 1) const map = reactive(raw) expect(map.has(key)).toBe(true) expect(map.get(key)).toBe(1) expect(map.delete(key)).toBe(true) expect(map.has(key)).toBe(false) expect(map.get(key)).toBeUndefined() }) it('should track set of reactive keys in raw map', () => { const raw = new Map() const key = reactive({}) raw.set(key, 1) const map = reactive(raw) let dummy effect(() => { dummy = map.get(key) }) expect(dummy).toBe(1) map.set(key, 2) expect(dummy).toBe(2) }) it('should track deletion of reactive keys in raw map', () => { const raw = new Map() const key = reactive({}) raw.set(key, 1) const map = reactive(raw) let dummy effect(() => { dummy = map.has(key) }) expect(dummy).toBe(true) map.delete(key) expect(dummy).toBe(false) }) it('should warn when both raw and reactive versions of the same object is used as key', () => { const raw = new Map() const rawKey = {} const key = reactive(rawKey) raw.set(rawKey, 1) raw.set(key, 1) const map = reactive(raw) map.set(key, 2) expect( `Reactive Map contains both the raw and reactive` ).toHaveBeenWarned() }) // #877 it('should not trigger key iteration when setting existing keys', () => { const map = reactive(new Map()) const spy = vi.fn() effect(() => { const keys = [] for (const key of map.keys()) { keys.push(key) } spy(keys) }) expect(spy).toHaveBeenCalledTimes(1) expect(spy.mock.calls[0][0]).toMatchObject([]) map.set('a', 0) expect(spy).toHaveBeenCalledTimes(2) expect(spy.mock.calls[1][0]).toMatchObject(['a']) map.set('b', 0) expect(spy).toHaveBeenCalledTimes(3) expect(spy.mock.calls[2][0]).toMatchObject(['a', 'b']) // keys didn't change, should not trigger map.set('b', 1) expect(spy).toHaveBeenCalledTimes(3) }) it('should trigger Map.has only once for non-reactive keys', () => { const [proxy, spy] = coverCollectionFn(new Map(), 'has') proxy.has('k') expect(spy).toBeCalledTimes(1) }) it('should trigger Map.set only once for non-reactive keys', () => { const [proxy, spy] = coverCollectionFn(new Map(), 'set') proxy.set('k', 'v') expect(spy).toBeCalledTimes(1) }) it('should trigger Map.delete only once for non-reactive keys', () => { const [proxy, spy] = coverCollectionFn(new Map(), 'delete') proxy.delete('foo') expect(spy).toBeCalledTimes(1) }) it('should trigger Map.clear only once for non-reactive keys', () => { const [proxy, spy] = coverCollectionFn(new Map(), 'clear') proxy.clear() expect(spy).toBeCalledTimes(1) }) it('should return proxy from Map.set call', () => { const map = reactive(new Map()) const result = map.set('a', 'a') expect(result).toBe(map) }) }) })
packages/reactivity/__tests__/collections/Map.spec.ts
0
https://github.com/vuejs/core/commit/3cb4dc9e5538e1c2bde9fa691b001615a848c546
[ 0.00018116207502316684, 0.00017328331887256354, 0.0001673953956924379, 0.00017256001592613757, 0.000002895930947488523 ]
{ "id": 1, "code_window": [ "// also to avoid inline import() in generated d.ts files\n", "export const KeepAlive = KeepAliveImpl as any as {\n", " __isKeepAlive: true\n", " new (): {\n", " $props: VNodeProps & KeepAliveProps\n", " }\n", "}\n", "\n", "function matches(pattern: MatchPattern, name: string): boolean {\n", " if (isArray(pattern)) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " $slots: {\n", " default(): VNode[]\n", " }\n" ], "file_path": "packages/runtime-core/src/components/KeepAlive.ts", "type": "add", "edit_start_line_idx": 346 }
import { VNode, normalizeVNode, VNodeProps, isSameVNodeType, openBlock, closeBlock, currentBlock, Comment, createVNode, isBlockTreeEnabled } from '../vnode' import { isFunction, isArray, ShapeFlags, toNumber } from '@vue/shared' import { ComponentInternalInstance, handleSetupResult } from '../component' import { Slots } from '../componentSlots' import { RendererInternals, MoveType, SetupRenderEffectFn, RendererNode, RendererElement } from '../renderer' import { queuePostFlushCb } from '../scheduler' import { filterSingleRoot, updateHOCHostEl } from '../componentRenderUtils' import { pushWarningContext, popWarningContext, warn, assertNumber } from '../warning' import { handleError, ErrorCodes } from '../errorHandling' export interface SuspenseProps { onResolve?: () => void onPending?: () => void onFallback?: () => void timeout?: string | number /** * Allow suspense to be captured by parent suspense * * @default false */ suspensible?: boolean } export const isSuspense = (type: any): boolean => type.__isSuspense // Suspense exposes a component-like API, and is treated like a component // in the compiler, but internally it's a special built-in type that hooks // directly into the renderer. export const SuspenseImpl = { name: 'Suspense', // In order to make Suspense tree-shakable, we need to avoid importing it // directly in the renderer. The renderer checks for the __isSuspense flag // on a vnode's type and calls the `process` method, passing in renderer // internals. __isSuspense: true, process( n1: VNode | null, n2: VNode, container: RendererElement, anchor: RendererNode | null, parentComponent: ComponentInternalInstance | null, parentSuspense: SuspenseBoundary | null, isSVG: boolean, slotScopeIds: string[] | null, optimized: boolean, // platform-specific impl passed from renderer rendererInternals: RendererInternals ) { if (n1 == null) { mountSuspense( n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals ) } else { patchSuspense( n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, rendererInternals ) } }, hydrate: hydrateSuspense, create: createSuspenseBoundary, normalize: normalizeSuspenseChildren } // Force-casted public typing for h and TSX props inference export const Suspense = (__FEATURE_SUSPENSE__ ? SuspenseImpl : null) as unknown as { __isSuspense: true new (): { $props: VNodeProps & SuspenseProps } } function triggerEvent( vnode: VNode, name: 'onResolve' | 'onPending' | 'onFallback' ) { const eventListener = vnode.props && vnode.props[name] if (isFunction(eventListener)) { eventListener() } } function mountSuspense( vnode: VNode, container: RendererElement, anchor: RendererNode | null, parentComponent: ComponentInternalInstance | null, parentSuspense: SuspenseBoundary | null, isSVG: boolean, slotScopeIds: string[] | null, optimized: boolean, rendererInternals: RendererInternals ) { const { p: patch, o: { createElement } } = rendererInternals const hiddenContainer = createElement('div') const suspense = (vnode.suspense = createSuspenseBoundary( vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals )) // start mounting the content subtree in an off-dom container patch( null, (suspense.pendingBranch = vnode.ssContent!), hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds ) // now check if we have encountered any async deps if (suspense.deps > 0) { // has async // invoke @fallback event triggerEvent(vnode, 'onPending') triggerEvent(vnode, 'onFallback') // mount the fallback tree patch( null, vnode.ssFallback!, container, anchor, parentComponent, null, // fallback tree will not have suspense context isSVG, slotScopeIds ) setActiveBranch(suspense, vnode.ssFallback!) } else { // Suspense has no async deps. Just resolve. suspense.resolve() } } function patchSuspense( n1: VNode, n2: VNode, container: RendererElement, anchor: RendererNode | null, parentComponent: ComponentInternalInstance | null, isSVG: boolean, slotScopeIds: string[] | null, optimized: boolean, { p: patch, um: unmount, o: { createElement } }: RendererInternals ) { const suspense = (n2.suspense = n1.suspense)! suspense.vnode = n2 n2.el = n1.el const newBranch = n2.ssContent! const newFallback = n2.ssFallback! const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense if (pendingBranch) { suspense.pendingBranch = newBranch if (isSameVNodeType(newBranch, pendingBranch)) { // same root type but content may have changed. patch( pendingBranch, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized ) if (suspense.deps <= 0) { suspense.resolve() } else if (isInFallback) { patch( activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context isSVG, slotScopeIds, optimized ) setActiveBranch(suspense, newFallback) } } else { // toggled before pending tree is resolved suspense.pendingId++ if (isHydrating) { // if toggled before hydration is finished, the current DOM tree is // no longer valid. set it as the active branch so it will be unmounted // when resolved suspense.isHydrating = false suspense.activeBranch = pendingBranch } else { unmount(pendingBranch, parentComponent, suspense) } // increment pending ID. this is used to invalidate async callbacks // reset suspense state suspense.deps = 0 // discard effects from pending branch suspense.effects.length = 0 // discard previous container suspense.hiddenContainer = createElement('div') if (isInFallback) { // already in fallback state patch( null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized ) if (suspense.deps <= 0) { suspense.resolve() } else { patch( activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context isSVG, slotScopeIds, optimized ) setActiveBranch(suspense, newFallback) } } else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) { // toggled "back" to current active branch patch( activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized ) // force resolve suspense.resolve(true) } else { // switched to a 3rd branch patch( null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized ) if (suspense.deps <= 0) { suspense.resolve() } } } } else { if (activeBranch && isSameVNodeType(newBranch, activeBranch)) { // root did not change, just normal patch patch( activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized ) setActiveBranch(suspense, newBranch) } else { // root node toggled // invoke @pending event triggerEvent(n2, 'onPending') // mount pending branch in off-dom container suspense.pendingBranch = newBranch suspense.pendingId++ patch( null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized ) if (suspense.deps <= 0) { // incoming branch has no async deps, resolve now. suspense.resolve() } else { const { timeout, pendingId } = suspense if (timeout > 0) { setTimeout(() => { if (suspense.pendingId === pendingId) { suspense.fallback(newFallback) } }, timeout) } else if (timeout === 0) { suspense.fallback(newFallback) } } } } } export interface SuspenseBoundary { vnode: VNode<RendererNode, RendererElement, SuspenseProps> parent: SuspenseBoundary | null parentComponent: ComponentInternalInstance | null isSVG: boolean container: RendererElement hiddenContainer: RendererElement anchor: RendererNode | null activeBranch: VNode | null pendingBranch: VNode | null deps: number pendingId: number timeout: number isInFallback: boolean isHydrating: boolean isUnmounted: boolean effects: Function[] resolve(force?: boolean): void fallback(fallbackVNode: VNode): void move( container: RendererElement, anchor: RendererNode | null, type: MoveType ): void next(): RendererNode | null registerDep( instance: ComponentInternalInstance, setupRenderEffect: SetupRenderEffectFn ): void unmount(parentSuspense: SuspenseBoundary | null, doRemove?: boolean): void } let hasWarned = false function createSuspenseBoundary( vnode: VNode, parentSuspense: SuspenseBoundary | null, parentComponent: ComponentInternalInstance | null, container: RendererElement, hiddenContainer: RendererElement, anchor: RendererNode | null, isSVG: boolean, slotScopeIds: string[] | null, optimized: boolean, rendererInternals: RendererInternals, isHydrating = false ): SuspenseBoundary { /* istanbul ignore if */ if (__DEV__ && !__TEST__ && !hasWarned) { hasWarned = true // @ts-ignore `console.info` cannot be null error console[console.info ? 'info' : 'log']( `<Suspense> is an experimental feature and its API will likely change.` ) } const { p: patch, m: move, um: unmount, n: next, o: { parentNode, remove } } = rendererInternals // if set `suspensible: true`, set the current suspense as a dep of parent suspense let parentSuspenseId: number | undefined const isSuspensible = vnode.props?.suspensible != null && vnode.props.suspensible !== false if (isSuspensible) { if (parentSuspense?.pendingBranch) { parentSuspenseId = parentSuspense?.pendingId parentSuspense.deps++ } } const timeout = vnode.props ? toNumber(vnode.props.timeout) : undefined if (__DEV__) { assertNumber(timeout, `Suspense timeout`) } const suspense: SuspenseBoundary = { vnode, parent: parentSuspense, parentComponent, isSVG, container, hiddenContainer, anchor, deps: 0, pendingId: 0, timeout: typeof timeout === 'number' ? timeout : -1, activeBranch: null, pendingBranch: null, isInFallback: true, isHydrating, isUnmounted: false, effects: [], resolve(resume = false) { if (__DEV__) { if (!resume && !suspense.pendingBranch) { throw new Error( `suspense.resolve() is called without a pending branch.` ) } if (suspense.isUnmounted) { throw new Error( `suspense.resolve() is called on an already unmounted suspense boundary.` ) } } const { vnode, activeBranch, pendingBranch, pendingId, effects, parentComponent, container } = suspense if (suspense.isHydrating) { suspense.isHydrating = false } else if (!resume) { const delayEnter = activeBranch && pendingBranch!.transition && pendingBranch!.transition.mode === 'out-in' if (delayEnter) { activeBranch!.transition!.afterLeave = () => { if (pendingId === suspense.pendingId) { move(pendingBranch!, container, anchor, MoveType.ENTER) } } } // this is initial anchor on mount let { anchor } = suspense // unmount current active tree if (activeBranch) { // if the fallback tree was mounted, it may have been moved // as part of a parent suspense. get the latest anchor for insertion anchor = next(activeBranch) unmount(activeBranch, parentComponent, suspense, true) } if (!delayEnter) { // move content from off-dom container to actual container move(pendingBranch!, container, anchor, MoveType.ENTER) } } setActiveBranch(suspense, pendingBranch!) suspense.pendingBranch = null suspense.isInFallback = false // flush buffered effects // check if there is a pending parent suspense let parent = suspense.parent let hasUnresolvedAncestor = false while (parent) { if (parent.pendingBranch) { // found a pending parent suspense, merge buffered post jobs // into that parent parent.effects.push(...effects) hasUnresolvedAncestor = true break } parent = parent.parent } // no pending parent suspense, flush all jobs if (!hasUnresolvedAncestor) { queuePostFlushCb(effects) } suspense.effects = [] // resolve parent suspense if all async deps are resolved if (isSuspensible) { if ( parentSuspense && parentSuspense.pendingBranch && parentSuspenseId === parentSuspense.pendingId ) { parentSuspense.deps-- if (parentSuspense.deps === 0) { parentSuspense.resolve() } } } // invoke @resolve event triggerEvent(vnode, 'onResolve') }, fallback(fallbackVNode) { if (!suspense.pendingBranch) { return } const { vnode, activeBranch, parentComponent, container, isSVG } = suspense // invoke @fallback event triggerEvent(vnode, 'onFallback') const anchor = next(activeBranch!) const mountFallback = () => { if (!suspense.isInFallback) { return } // mount the fallback tree patch( null, fallbackVNode, container, anchor, parentComponent, null, // fallback tree will not have suspense context isSVG, slotScopeIds, optimized ) setActiveBranch(suspense, fallbackVNode) } const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === 'out-in' if (delayEnter) { activeBranch!.transition!.afterLeave = mountFallback } suspense.isInFallback = true // unmount current active branch unmount( activeBranch!, parentComponent, null, // no suspense so unmount hooks fire now true // shouldRemove ) if (!delayEnter) { mountFallback() } }, move(container, anchor, type) { suspense.activeBranch && move(suspense.activeBranch, container, anchor, type) suspense.container = container }, next() { return suspense.activeBranch && next(suspense.activeBranch) }, registerDep(instance, setupRenderEffect) { const isInPendingSuspense = !!suspense.pendingBranch if (isInPendingSuspense) { suspense.deps++ } const hydratedEl = instance.vnode.el instance .asyncDep!.catch(err => { handleError(err, instance, ErrorCodes.SETUP_FUNCTION) }) .then(asyncSetupResult => { // retry when the setup() promise resolves. // component may have been unmounted before resolve. if ( instance.isUnmounted || suspense.isUnmounted || suspense.pendingId !== instance.suspenseId ) { return } // retry from this component instance.asyncResolved = true const { vnode } = instance if (__DEV__) { pushWarningContext(vnode) } handleSetupResult(instance, asyncSetupResult, false) if (hydratedEl) { // vnode may have been replaced if an update happened before the // async dep is resolved. vnode.el = hydratedEl } const placeholder = !hydratedEl && instance.subTree.el setupRenderEffect( instance, vnode, // component may have been moved before resolve. // if this is not a hydration, instance.subTree will be the comment // placeholder. parentNode(hydratedEl || instance.subTree.el!)!, // anchor will not be used if this is hydration, so only need to // consider the comment placeholder case. hydratedEl ? null : next(instance.subTree), suspense, isSVG, optimized ) if (placeholder) { remove(placeholder) } updateHOCHostEl(instance, vnode.el) if (__DEV__) { popWarningContext() } // only decrease deps count if suspense is not already resolved if (isInPendingSuspense && --suspense.deps === 0) { suspense.resolve() } }) }, unmount(parentSuspense, doRemove) { suspense.isUnmounted = true if (suspense.activeBranch) { unmount( suspense.activeBranch, parentComponent, parentSuspense, doRemove ) } if (suspense.pendingBranch) { unmount( suspense.pendingBranch, parentComponent, parentSuspense, doRemove ) } } } return suspense } function hydrateSuspense( node: Node, vnode: VNode, parentComponent: ComponentInternalInstance | null, parentSuspense: SuspenseBoundary | null, isSVG: boolean, slotScopeIds: string[] | null, optimized: boolean, rendererInternals: RendererInternals, hydrateNode: ( node: Node, vnode: VNode, parentComponent: ComponentInternalInstance | null, parentSuspense: SuspenseBoundary | null, slotScopeIds: string[] | null, optimized: boolean ) => Node | null ): Node | null { /* eslint-disable no-restricted-globals */ const suspense = (vnode.suspense = createSuspenseBoundary( vnode, parentSuspense, parentComponent, node.parentNode!, document.createElement('div'), null, isSVG, slotScopeIds, optimized, rendererInternals, true /* hydrating */ )) // there are two possible scenarios for server-rendered suspense: // - success: ssr content should be fully resolved // - failure: ssr content should be the fallback branch. // however, on the client we don't really know if it has failed or not // attempt to hydrate the DOM assuming it has succeeded, but we still // need to construct a suspense boundary first const result = hydrateNode( node, (suspense.pendingBranch = vnode.ssContent!), parentComponent, suspense, slotScopeIds, optimized ) if (suspense.deps === 0) { suspense.resolve() } return result /* eslint-enable no-restricted-globals */ } function normalizeSuspenseChildren(vnode: VNode) { const { shapeFlag, children } = vnode const isSlotChildren = shapeFlag & ShapeFlags.SLOTS_CHILDREN vnode.ssContent = normalizeSuspenseSlot( isSlotChildren ? (children as Slots).default : children ) vnode.ssFallback = isSlotChildren ? normalizeSuspenseSlot((children as Slots).fallback) : createVNode(Comment) } function normalizeSuspenseSlot(s: any) { let block: VNode[] | null | undefined if (isFunction(s)) { const trackBlock = isBlockTreeEnabled && s._c if (trackBlock) { // disableTracking: false // allow block tracking for compiled slots // (see ./componentRenderContext.ts) s._d = false openBlock() } s = s() if (trackBlock) { s._d = true block = currentBlock closeBlock() } } if (isArray(s)) { const singleChild = filterSingleRoot(s) if (__DEV__ && !singleChild) { warn(`<Suspense> slots expect a single root node.`) } s = singleChild } s = normalizeVNode(s) if (block && !s.dynamicChildren) { s.dynamicChildren = block.filter(c => c !== s) } return s } export function queueEffectWithSuspense( fn: Function | Function[], suspense: SuspenseBoundary | null ): void { if (suspense && suspense.pendingBranch) { if (isArray(fn)) { suspense.effects.push(...fn) } else { suspense.effects.push(fn) } } else { queuePostFlushCb(fn) } } function setActiveBranch(suspense: SuspenseBoundary, branch: VNode) { suspense.activeBranch = branch const { vnode, parentComponent } = suspense const el = (vnode.el = branch.el) // in case suspense is the root node of a component, // recursively update the HOC el if (parentComponent && parentComponent.subTree === vnode) { parentComponent.vnode.el = el updateHOCHostEl(parentComponent, el) } }
packages/runtime-core/src/components/Suspense.ts
1
https://github.com/vuejs/core/commit/3cb4dc9e5538e1c2bde9fa691b001615a848c546
[ 0.000856323167681694, 0.00019150263688061386, 0.00016026302182581276, 0.0001746643683873117, 0.00010136527998838574 ]
{ "id": 1, "code_window": [ "// also to avoid inline import() in generated d.ts files\n", "export const KeepAlive = KeepAliveImpl as any as {\n", " __isKeepAlive: true\n", " new (): {\n", " $props: VNodeProps & KeepAliveProps\n", " }\n", "}\n", "\n", "function matches(pattern: MatchPattern, name: string): boolean {\n", " if (isArray(pattern)) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " $slots: {\n", " default(): VNode[]\n", " }\n" ], "file_path": "packages/runtime-core/src/components/KeepAlive.ts", "type": "add", "edit_start_line_idx": 346 }
import { isArray } from '@vue/shared' import { TestElement } from './nodeOps' export function triggerEvent( el: TestElement, event: string, payload: any[] = [] ) { const { eventListeners } = el if (eventListeners) { const listener = eventListeners[event] if (listener) { if (isArray(listener)) { for (let i = 0; i < listener.length; i++) { listener[i](...payload) } } else { listener(...payload) } } } }
packages/runtime-test/src/triggerEvent.ts
0
https://github.com/vuejs/core/commit/3cb4dc9e5538e1c2bde9fa691b001615a848c546
[ 0.0001938546192832291, 0.00018014131637755781, 0.00017168019257951528, 0.00017488918092567474, 0.00000978485604719026 ]
{ "id": 1, "code_window": [ "// also to avoid inline import() in generated d.ts files\n", "export const KeepAlive = KeepAliveImpl as any as {\n", " __isKeepAlive: true\n", " new (): {\n", " $props: VNodeProps & KeepAliveProps\n", " }\n", "}\n", "\n", "function matches(pattern: MatchPattern, name: string): boolean {\n", " if (isArray(pattern)) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " $slots: {\n", " default(): VNode[]\n", " }\n" ], "file_path": "packages/runtime-core/src/components/KeepAlive.ts", "type": "add", "edit_start_line_idx": 346 }
<script src="../../dist/vue.global.js"></script> <script> const { ref, reactive, computed, createApp } = Vue // math helper... function valueToPoint (value, index, total) { var x = 0 var y = -value * 0.8 var angle = Math.PI * 2 / total * index var cos = Math.cos(angle) var sin = Math.sin(angle) var tx = x * cos - y * sin + 100 var ty = x * sin + y * cos + 100 return { x: tx, y: ty } } const AxisLabel = { template: '<text :x="point.x" :y="point.y">{{stat.label}}</text>', props: { stat: Object, index: Number, total: Number }, setup(props) { return { point: computed(() => valueToPoint( +props.stat.value + 10, props.index, props.total )) } } } </script> <!-- template for the polygraph component. --> <script type="text/x-template" id="polygraph-template"> <g> <polygon :points="points"></polygon> <circle cx="100" cy="100" r="80"></circle> <axis-label v-for="(stat, index) in stats" :stat="stat" :index="index" :total="stats.length"> </axis-label> </g> </script> <script> const Polygraph = { props: ['stats'], template: '#polygraph-template', setup(props) { return { points: computed(() => { const total = props.stats.length return props.stats.map((stat, i) => { const point = valueToPoint(stat.value, i, total) return point.x + ',' + point.y }).join(' ') }) } }, components: { AxisLabel } } </script> <!-- demo root element --> <div id="demo"> <!-- Use the polygraph component --> <svg width="200" height="200"> <polygraph :stats="stats"></polygraph> </svg> <!-- controls --> <div v-for="stat in stats"> <label>{{stat.label}}</label> <input type="range" v-model="stat.value" min="0" max="100"> <span>{{stat.value}}</span> <button @click="remove(stat)" class="remove">X</button> </div> <form id="add"> <input name="newlabel" v-model="newLabel"> <button @click="add">Add a Stat</button> </form> <pre id="raw">{{ stats }}</pre> </div> <script> const globalStats = [ { label: 'A', value: 100 }, { label: 'B', value: 100 }, { label: 'C', value: 100 }, { label: 'D', value: 100 }, { label: 'E', value: 100 }, { label: 'F', value: 100 } ] createApp({ components: { Polygraph }, setup() { const newLabel = ref('') const stats = reactive(globalStats) function add(e) { e.preventDefault() if (!newLabel.value) return stats.push({ label: newLabel.value, value: 100 }) newLabel.value = '' } function remove(stat) { if (stats.length > 3) { stats.splice(stats.indexOf(stat), 1) } else { alert('Can\'t delete more!') } } return { newLabel, stats, add, remove } } }).mount('#demo') </script> <style> body { font-family: Helvetica Neue, Arial, sans-serif; } polygon { fill: #42b983; opacity: .75; } circle { fill: transparent; stroke: #999; } text { font-family: Helvetica Neue, Arial, sans-serif; font-size: 10px; fill: #666; } label { display: inline-block; margin-left: 10px; width: 20px; } #raw { position: absolute; top: 0; left: 300px; } </style>
packages/vue/examples/composition/svg.html
0
https://github.com/vuejs/core/commit/3cb4dc9e5538e1c2bde9fa691b001615a848c546
[ 0.000179727328941226, 0.00017480392125435174, 0.0001656767854001373, 0.0001761083403835073, 0.000003731634933501482 ]
{ "id": 1, "code_window": [ "// also to avoid inline import() in generated d.ts files\n", "export const KeepAlive = KeepAliveImpl as any as {\n", " __isKeepAlive: true\n", " new (): {\n", " $props: VNodeProps & KeepAliveProps\n", " }\n", "}\n", "\n", "function matches(pattern: MatchPattern, name: string): boolean {\n", " if (isArray(pattern)) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " $slots: {\n", " default(): VNode[]\n", " }\n" ], "file_path": "packages/runtime-core/src/components/KeepAlive.ts", "type": "add", "edit_start_line_idx": 346 }
import { DirectiveTransform, DirectiveTransformResult } from '../transform' import { createCompoundExpression, createObjectProperty, createSimpleExpression, DirectiveNode, ElementTypes, ExpressionNode, NodeTypes, SimpleExpressionNode } from '../ast' import { camelize, toHandlerKey } from '@vue/shared' import { createCompilerError, ErrorCodes } from '../errors' import { processExpression } from './transformExpression' import { validateBrowserExpression } from '../validateExpression' import { hasScopeRef, isMemberExpression } from '../utils' import { TO_HANDLER_KEY } from '../runtimeHelpers' const fnExpRE = /^\s*([\w$_]+|(async\s*)?\([^)]*?\))\s*(:[^=]+)?=>|^\s*(async\s+)?function(?:\s+[\w$]+)?\s*\(/ export interface VOnDirectiveNode extends DirectiveNode { // v-on without arg is handled directly in ./transformElements.ts due to it affecting // codegen for the entire props object. This transform here is only for v-on // *with* args. arg: ExpressionNode // exp is guaranteed to be a simple expression here because v-on w/ arg is // skipped by transformExpression as a special case. exp: SimpleExpressionNode | undefined } export const transformOn: DirectiveTransform = ( dir, node, context, augmentor ) => { const { loc, modifiers, arg } = dir as VOnDirectiveNode if (!dir.exp && !modifiers.length) { context.onError(createCompilerError(ErrorCodes.X_V_ON_NO_EXPRESSION, loc)) } let eventName: ExpressionNode if (arg.type === NodeTypes.SIMPLE_EXPRESSION) { if (arg.isStatic) { let rawName = arg.content if (__DEV__ && rawName.startsWith('vnode')) { context.onWarn( createCompilerError(ErrorCodes.DEPRECATION_VNODE_HOOKS, arg.loc) ) } if (rawName.startsWith('vue:')) { rawName = `vnode-${rawName.slice(4)}` } const eventString = node.tagType !== ElementTypes.ELEMENT || rawName.startsWith('vnode') || !/[A-Z]/.test(rawName) ? // for non-element and vnode lifecycle event listeners, auto convert // it to camelCase. See issue #2249 toHandlerKey(camelize(rawName)) : // preserve case for plain element listeners that have uppercase // letters, as these may be custom elements' custom events `on:${rawName}` eventName = createSimpleExpression(eventString, true, arg.loc) } else { // #2388 eventName = createCompoundExpression([ `${context.helperString(TO_HANDLER_KEY)}(`, arg, `)` ]) } } else { // already a compound expression. eventName = arg eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`) eventName.children.push(`)`) } // handler processing let exp: ExpressionNode | undefined = dir.exp as | SimpleExpressionNode | undefined if (exp && !exp.content.trim()) { exp = undefined } let shouldCache: boolean = context.cacheHandlers && !exp && !context.inVOnce if (exp) { const isMemberExp = isMemberExpression(exp.content, context) const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content)) const hasMultipleStatements = exp.content.includes(`;`) // process the expression since it's been skipped if (!__BROWSER__ && context.prefixIdentifiers) { isInlineStatement && context.addIdentifiers(`$event`) exp = dir.exp = processExpression( exp, context, false, hasMultipleStatements ) isInlineStatement && context.removeIdentifiers(`$event`) // with scope analysis, the function is hoistable if it has no reference // to scope variables. shouldCache = context.cacheHandlers && // unnecessary to cache inside v-once !context.inVOnce && // runtime constants don't need to be cached // (this is analyzed by compileScript in SFC <script setup>) !(exp.type === NodeTypes.SIMPLE_EXPRESSION && exp.constType > 0) && // #1541 bail if this is a member exp handler passed to a component - // we need to use the original function to preserve arity, // e.g. <transition> relies on checking cb.length to determine // transition end handling. Inline function is ok since its arity // is preserved even when cached. !(isMemberExp && node.tagType === ElementTypes.COMPONENT) && // bail if the function references closure variables (v-for, v-slot) // it must be passed fresh to avoid stale values. !hasScopeRef(exp, context.identifiers) // If the expression is optimizable and is a member expression pointing // to a function, turn it into invocation (and wrap in an arrow function // below) so that it always accesses the latest value when called - thus // avoiding the need to be patched. if (shouldCache && isMemberExp) { if (exp.type === NodeTypes.SIMPLE_EXPRESSION) { exp.content = `${exp.content} && ${exp.content}(...args)` } else { exp.children = [...exp.children, ` && `, ...exp.children, `(...args)`] } } } if (__DEV__ && __BROWSER__) { validateBrowserExpression( exp as SimpleExpressionNode, context, false, hasMultipleStatements ) } if (isInlineStatement || (shouldCache && isMemberExp)) { // wrap inline statement in a function expression exp = createCompoundExpression([ `${ isInlineStatement ? !__BROWSER__ && context.isTS ? `($event: any)` : `$event` : `${ !__BROWSER__ && context.isTS ? `\n//@ts-ignore\n` : `` }(...args)` } => ${hasMultipleStatements ? `{` : `(`}`, exp, hasMultipleStatements ? `}` : `)` ]) } } let ret: DirectiveTransformResult = { props: [ createObjectProperty( eventName, exp || createSimpleExpression(`() => {}`, false, loc) ) ] } // apply extended compiler augmentor if (augmentor) { ret = augmentor(ret) } if (shouldCache) { // cache handlers so that it's always the same handler being passed down. // this avoids unnecessary re-renders when users use inline handlers on // components. ret.props[0].value = context.cache(ret.props[0].value) } // mark the key as handler for props normalization check ret.props.forEach(p => (p.key.isHandlerKey = true)) return ret }
packages/compiler-core/src/transforms/vOn.ts
0
https://github.com/vuejs/core/commit/3cb4dc9e5538e1c2bde9fa691b001615a848c546
[ 0.002069731242954731, 0.00028484268113970757, 0.0001660998968873173, 0.00017308951646555215, 0.0004231599741615355 ]
{ "id": 2, "code_window": [ " ? SuspenseImpl\n", " : null) as unknown as {\n", " __isSuspense: true\n", " new (): { $props: VNodeProps & SuspenseProps }\n", "}\n", "\n", "function triggerEvent(\n", " vnode: VNode,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " new (): {\n", " $props: VNodeProps & SuspenseProps\n", " $slots: {\n", " default(): VNode[]\n", " fallback(): VNode[]\n", " }\n", " }\n" ], "file_path": "packages/runtime-core/src/components/Suspense.ts", "type": "replace", "edit_start_line_idx": 106 }
import { VNode, normalizeVNode, VNodeProps, isSameVNodeType, openBlock, closeBlock, currentBlock, Comment, createVNode, isBlockTreeEnabled } from '../vnode' import { isFunction, isArray, ShapeFlags, toNumber } from '@vue/shared' import { ComponentInternalInstance, handleSetupResult } from '../component' import { Slots } from '../componentSlots' import { RendererInternals, MoveType, SetupRenderEffectFn, RendererNode, RendererElement } from '../renderer' import { queuePostFlushCb } from '../scheduler' import { filterSingleRoot, updateHOCHostEl } from '../componentRenderUtils' import { pushWarningContext, popWarningContext, warn, assertNumber } from '../warning' import { handleError, ErrorCodes } from '../errorHandling' export interface SuspenseProps { onResolve?: () => void onPending?: () => void onFallback?: () => void timeout?: string | number /** * Allow suspense to be captured by parent suspense * * @default false */ suspensible?: boolean } export const isSuspense = (type: any): boolean => type.__isSuspense // Suspense exposes a component-like API, and is treated like a component // in the compiler, but internally it's a special built-in type that hooks // directly into the renderer. export const SuspenseImpl = { name: 'Suspense', // In order to make Suspense tree-shakable, we need to avoid importing it // directly in the renderer. The renderer checks for the __isSuspense flag // on a vnode's type and calls the `process` method, passing in renderer // internals. __isSuspense: true, process( n1: VNode | null, n2: VNode, container: RendererElement, anchor: RendererNode | null, parentComponent: ComponentInternalInstance | null, parentSuspense: SuspenseBoundary | null, isSVG: boolean, slotScopeIds: string[] | null, optimized: boolean, // platform-specific impl passed from renderer rendererInternals: RendererInternals ) { if (n1 == null) { mountSuspense( n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals ) } else { patchSuspense( n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, rendererInternals ) } }, hydrate: hydrateSuspense, create: createSuspenseBoundary, normalize: normalizeSuspenseChildren } // Force-casted public typing for h and TSX props inference export const Suspense = (__FEATURE_SUSPENSE__ ? SuspenseImpl : null) as unknown as { __isSuspense: true new (): { $props: VNodeProps & SuspenseProps } } function triggerEvent( vnode: VNode, name: 'onResolve' | 'onPending' | 'onFallback' ) { const eventListener = vnode.props && vnode.props[name] if (isFunction(eventListener)) { eventListener() } } function mountSuspense( vnode: VNode, container: RendererElement, anchor: RendererNode | null, parentComponent: ComponentInternalInstance | null, parentSuspense: SuspenseBoundary | null, isSVG: boolean, slotScopeIds: string[] | null, optimized: boolean, rendererInternals: RendererInternals ) { const { p: patch, o: { createElement } } = rendererInternals const hiddenContainer = createElement('div') const suspense = (vnode.suspense = createSuspenseBoundary( vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals )) // start mounting the content subtree in an off-dom container patch( null, (suspense.pendingBranch = vnode.ssContent!), hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds ) // now check if we have encountered any async deps if (suspense.deps > 0) { // has async // invoke @fallback event triggerEvent(vnode, 'onPending') triggerEvent(vnode, 'onFallback') // mount the fallback tree patch( null, vnode.ssFallback!, container, anchor, parentComponent, null, // fallback tree will not have suspense context isSVG, slotScopeIds ) setActiveBranch(suspense, vnode.ssFallback!) } else { // Suspense has no async deps. Just resolve. suspense.resolve() } } function patchSuspense( n1: VNode, n2: VNode, container: RendererElement, anchor: RendererNode | null, parentComponent: ComponentInternalInstance | null, isSVG: boolean, slotScopeIds: string[] | null, optimized: boolean, { p: patch, um: unmount, o: { createElement } }: RendererInternals ) { const suspense = (n2.suspense = n1.suspense)! suspense.vnode = n2 n2.el = n1.el const newBranch = n2.ssContent! const newFallback = n2.ssFallback! const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense if (pendingBranch) { suspense.pendingBranch = newBranch if (isSameVNodeType(newBranch, pendingBranch)) { // same root type but content may have changed. patch( pendingBranch, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized ) if (suspense.deps <= 0) { suspense.resolve() } else if (isInFallback) { patch( activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context isSVG, slotScopeIds, optimized ) setActiveBranch(suspense, newFallback) } } else { // toggled before pending tree is resolved suspense.pendingId++ if (isHydrating) { // if toggled before hydration is finished, the current DOM tree is // no longer valid. set it as the active branch so it will be unmounted // when resolved suspense.isHydrating = false suspense.activeBranch = pendingBranch } else { unmount(pendingBranch, parentComponent, suspense) } // increment pending ID. this is used to invalidate async callbacks // reset suspense state suspense.deps = 0 // discard effects from pending branch suspense.effects.length = 0 // discard previous container suspense.hiddenContainer = createElement('div') if (isInFallback) { // already in fallback state patch( null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized ) if (suspense.deps <= 0) { suspense.resolve() } else { patch( activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context isSVG, slotScopeIds, optimized ) setActiveBranch(suspense, newFallback) } } else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) { // toggled "back" to current active branch patch( activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized ) // force resolve suspense.resolve(true) } else { // switched to a 3rd branch patch( null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized ) if (suspense.deps <= 0) { suspense.resolve() } } } } else { if (activeBranch && isSameVNodeType(newBranch, activeBranch)) { // root did not change, just normal patch patch( activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized ) setActiveBranch(suspense, newBranch) } else { // root node toggled // invoke @pending event triggerEvent(n2, 'onPending') // mount pending branch in off-dom container suspense.pendingBranch = newBranch suspense.pendingId++ patch( null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized ) if (suspense.deps <= 0) { // incoming branch has no async deps, resolve now. suspense.resolve() } else { const { timeout, pendingId } = suspense if (timeout > 0) { setTimeout(() => { if (suspense.pendingId === pendingId) { suspense.fallback(newFallback) } }, timeout) } else if (timeout === 0) { suspense.fallback(newFallback) } } } } } export interface SuspenseBoundary { vnode: VNode<RendererNode, RendererElement, SuspenseProps> parent: SuspenseBoundary | null parentComponent: ComponentInternalInstance | null isSVG: boolean container: RendererElement hiddenContainer: RendererElement anchor: RendererNode | null activeBranch: VNode | null pendingBranch: VNode | null deps: number pendingId: number timeout: number isInFallback: boolean isHydrating: boolean isUnmounted: boolean effects: Function[] resolve(force?: boolean): void fallback(fallbackVNode: VNode): void move( container: RendererElement, anchor: RendererNode | null, type: MoveType ): void next(): RendererNode | null registerDep( instance: ComponentInternalInstance, setupRenderEffect: SetupRenderEffectFn ): void unmount(parentSuspense: SuspenseBoundary | null, doRemove?: boolean): void } let hasWarned = false function createSuspenseBoundary( vnode: VNode, parentSuspense: SuspenseBoundary | null, parentComponent: ComponentInternalInstance | null, container: RendererElement, hiddenContainer: RendererElement, anchor: RendererNode | null, isSVG: boolean, slotScopeIds: string[] | null, optimized: boolean, rendererInternals: RendererInternals, isHydrating = false ): SuspenseBoundary { /* istanbul ignore if */ if (__DEV__ && !__TEST__ && !hasWarned) { hasWarned = true // @ts-ignore `console.info` cannot be null error console[console.info ? 'info' : 'log']( `<Suspense> is an experimental feature and its API will likely change.` ) } const { p: patch, m: move, um: unmount, n: next, o: { parentNode, remove } } = rendererInternals // if set `suspensible: true`, set the current suspense as a dep of parent suspense let parentSuspenseId: number | undefined const isSuspensible = vnode.props?.suspensible != null && vnode.props.suspensible !== false if (isSuspensible) { if (parentSuspense?.pendingBranch) { parentSuspenseId = parentSuspense?.pendingId parentSuspense.deps++ } } const timeout = vnode.props ? toNumber(vnode.props.timeout) : undefined if (__DEV__) { assertNumber(timeout, `Suspense timeout`) } const suspense: SuspenseBoundary = { vnode, parent: parentSuspense, parentComponent, isSVG, container, hiddenContainer, anchor, deps: 0, pendingId: 0, timeout: typeof timeout === 'number' ? timeout : -1, activeBranch: null, pendingBranch: null, isInFallback: true, isHydrating, isUnmounted: false, effects: [], resolve(resume = false) { if (__DEV__) { if (!resume && !suspense.pendingBranch) { throw new Error( `suspense.resolve() is called without a pending branch.` ) } if (suspense.isUnmounted) { throw new Error( `suspense.resolve() is called on an already unmounted suspense boundary.` ) } } const { vnode, activeBranch, pendingBranch, pendingId, effects, parentComponent, container } = suspense if (suspense.isHydrating) { suspense.isHydrating = false } else if (!resume) { const delayEnter = activeBranch && pendingBranch!.transition && pendingBranch!.transition.mode === 'out-in' if (delayEnter) { activeBranch!.transition!.afterLeave = () => { if (pendingId === suspense.pendingId) { move(pendingBranch!, container, anchor, MoveType.ENTER) } } } // this is initial anchor on mount let { anchor } = suspense // unmount current active tree if (activeBranch) { // if the fallback tree was mounted, it may have been moved // as part of a parent suspense. get the latest anchor for insertion anchor = next(activeBranch) unmount(activeBranch, parentComponent, suspense, true) } if (!delayEnter) { // move content from off-dom container to actual container move(pendingBranch!, container, anchor, MoveType.ENTER) } } setActiveBranch(suspense, pendingBranch!) suspense.pendingBranch = null suspense.isInFallback = false // flush buffered effects // check if there is a pending parent suspense let parent = suspense.parent let hasUnresolvedAncestor = false while (parent) { if (parent.pendingBranch) { // found a pending parent suspense, merge buffered post jobs // into that parent parent.effects.push(...effects) hasUnresolvedAncestor = true break } parent = parent.parent } // no pending parent suspense, flush all jobs if (!hasUnresolvedAncestor) { queuePostFlushCb(effects) } suspense.effects = [] // resolve parent suspense if all async deps are resolved if (isSuspensible) { if ( parentSuspense && parentSuspense.pendingBranch && parentSuspenseId === parentSuspense.pendingId ) { parentSuspense.deps-- if (parentSuspense.deps === 0) { parentSuspense.resolve() } } } // invoke @resolve event triggerEvent(vnode, 'onResolve') }, fallback(fallbackVNode) { if (!suspense.pendingBranch) { return } const { vnode, activeBranch, parentComponent, container, isSVG } = suspense // invoke @fallback event triggerEvent(vnode, 'onFallback') const anchor = next(activeBranch!) const mountFallback = () => { if (!suspense.isInFallback) { return } // mount the fallback tree patch( null, fallbackVNode, container, anchor, parentComponent, null, // fallback tree will not have suspense context isSVG, slotScopeIds, optimized ) setActiveBranch(suspense, fallbackVNode) } const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === 'out-in' if (delayEnter) { activeBranch!.transition!.afterLeave = mountFallback } suspense.isInFallback = true // unmount current active branch unmount( activeBranch!, parentComponent, null, // no suspense so unmount hooks fire now true // shouldRemove ) if (!delayEnter) { mountFallback() } }, move(container, anchor, type) { suspense.activeBranch && move(suspense.activeBranch, container, anchor, type) suspense.container = container }, next() { return suspense.activeBranch && next(suspense.activeBranch) }, registerDep(instance, setupRenderEffect) { const isInPendingSuspense = !!suspense.pendingBranch if (isInPendingSuspense) { suspense.deps++ } const hydratedEl = instance.vnode.el instance .asyncDep!.catch(err => { handleError(err, instance, ErrorCodes.SETUP_FUNCTION) }) .then(asyncSetupResult => { // retry when the setup() promise resolves. // component may have been unmounted before resolve. if ( instance.isUnmounted || suspense.isUnmounted || suspense.pendingId !== instance.suspenseId ) { return } // retry from this component instance.asyncResolved = true const { vnode } = instance if (__DEV__) { pushWarningContext(vnode) } handleSetupResult(instance, asyncSetupResult, false) if (hydratedEl) { // vnode may have been replaced if an update happened before the // async dep is resolved. vnode.el = hydratedEl } const placeholder = !hydratedEl && instance.subTree.el setupRenderEffect( instance, vnode, // component may have been moved before resolve. // if this is not a hydration, instance.subTree will be the comment // placeholder. parentNode(hydratedEl || instance.subTree.el!)!, // anchor will not be used if this is hydration, so only need to // consider the comment placeholder case. hydratedEl ? null : next(instance.subTree), suspense, isSVG, optimized ) if (placeholder) { remove(placeholder) } updateHOCHostEl(instance, vnode.el) if (__DEV__) { popWarningContext() } // only decrease deps count if suspense is not already resolved if (isInPendingSuspense && --suspense.deps === 0) { suspense.resolve() } }) }, unmount(parentSuspense, doRemove) { suspense.isUnmounted = true if (suspense.activeBranch) { unmount( suspense.activeBranch, parentComponent, parentSuspense, doRemove ) } if (suspense.pendingBranch) { unmount( suspense.pendingBranch, parentComponent, parentSuspense, doRemove ) } } } return suspense } function hydrateSuspense( node: Node, vnode: VNode, parentComponent: ComponentInternalInstance | null, parentSuspense: SuspenseBoundary | null, isSVG: boolean, slotScopeIds: string[] | null, optimized: boolean, rendererInternals: RendererInternals, hydrateNode: ( node: Node, vnode: VNode, parentComponent: ComponentInternalInstance | null, parentSuspense: SuspenseBoundary | null, slotScopeIds: string[] | null, optimized: boolean ) => Node | null ): Node | null { /* eslint-disable no-restricted-globals */ const suspense = (vnode.suspense = createSuspenseBoundary( vnode, parentSuspense, parentComponent, node.parentNode!, document.createElement('div'), null, isSVG, slotScopeIds, optimized, rendererInternals, true /* hydrating */ )) // there are two possible scenarios for server-rendered suspense: // - success: ssr content should be fully resolved // - failure: ssr content should be the fallback branch. // however, on the client we don't really know if it has failed or not // attempt to hydrate the DOM assuming it has succeeded, but we still // need to construct a suspense boundary first const result = hydrateNode( node, (suspense.pendingBranch = vnode.ssContent!), parentComponent, suspense, slotScopeIds, optimized ) if (suspense.deps === 0) { suspense.resolve() } return result /* eslint-enable no-restricted-globals */ } function normalizeSuspenseChildren(vnode: VNode) { const { shapeFlag, children } = vnode const isSlotChildren = shapeFlag & ShapeFlags.SLOTS_CHILDREN vnode.ssContent = normalizeSuspenseSlot( isSlotChildren ? (children as Slots).default : children ) vnode.ssFallback = isSlotChildren ? normalizeSuspenseSlot((children as Slots).fallback) : createVNode(Comment) } function normalizeSuspenseSlot(s: any) { let block: VNode[] | null | undefined if (isFunction(s)) { const trackBlock = isBlockTreeEnabled && s._c if (trackBlock) { // disableTracking: false // allow block tracking for compiled slots // (see ./componentRenderContext.ts) s._d = false openBlock() } s = s() if (trackBlock) { s._d = true block = currentBlock closeBlock() } } if (isArray(s)) { const singleChild = filterSingleRoot(s) if (__DEV__ && !singleChild) { warn(`<Suspense> slots expect a single root node.`) } s = singleChild } s = normalizeVNode(s) if (block && !s.dynamicChildren) { s.dynamicChildren = block.filter(c => c !== s) } return s } export function queueEffectWithSuspense( fn: Function | Function[], suspense: SuspenseBoundary | null ): void { if (suspense && suspense.pendingBranch) { if (isArray(fn)) { suspense.effects.push(...fn) } else { suspense.effects.push(fn) } } else { queuePostFlushCb(fn) } } function setActiveBranch(suspense: SuspenseBoundary, branch: VNode) { suspense.activeBranch = branch const { vnode, parentComponent } = suspense const el = (vnode.el = branch.el) // in case suspense is the root node of a component, // recursively update the HOC el if (parentComponent && parentComponent.subTree === vnode) { parentComponent.vnode.el = el updateHOCHostEl(parentComponent, el) } }
packages/runtime-core/src/components/Suspense.ts
1
https://github.com/vuejs/core/commit/3cb4dc9e5538e1c2bde9fa691b001615a848c546
[ 0.9990941286087036, 0.09922659397125244, 0.00016680061526130885, 0.0004805903590749949, 0.2924593389034271 ]
{ "id": 2, "code_window": [ " ? SuspenseImpl\n", " : null) as unknown as {\n", " __isSuspense: true\n", " new (): { $props: VNodeProps & SuspenseProps }\n", "}\n", "\n", "function triggerEvent(\n", " vnode: VNode,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " new (): {\n", " $props: VNodeProps & SuspenseProps\n", " $slots: {\n", " default(): VNode[]\n", " fallback(): VNode[]\n", " }\n", " }\n" ], "file_path": "packages/runtime-core/src/components/Suspense.ts", "type": "replace", "edit_start_line_idx": 106 }
import { isPlainObject } from '@vue/shared' import { DeprecationTypes, warnDeprecation } from './compatConfig' export function deepMergeData(to: any, from: any) { for (const key in from) { const toVal = to[key] const fromVal = from[key] if (key in to && isPlainObject(toVal) && isPlainObject(fromVal)) { __DEV__ && warnDeprecation(DeprecationTypes.OPTIONS_DATA_MERGE, null, key) deepMergeData(toVal, fromVal) } else { to[key] = fromVal } } return to }
packages/runtime-core/src/compat/data.ts
0
https://github.com/vuejs/core/commit/3cb4dc9e5538e1c2bde9fa691b001615a848c546
[ 0.00017492038023192436, 0.00017444690456613898, 0.0001739734289003536, 0.00017444690456613898, 4.7347566578537226e-7 ]
{ "id": 2, "code_window": [ " ? SuspenseImpl\n", " : null) as unknown as {\n", " __isSuspense: true\n", " new (): { $props: VNodeProps & SuspenseProps }\n", "}\n", "\n", "function triggerEvent(\n", " vnode: VNode,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " new (): {\n", " $props: VNodeProps & SuspenseProps\n", " $slots: {\n", " default(): VNode[]\n", " fallback(): VNode[]\n", " }\n", " }\n" ], "file_path": "packages/runtime-core/src/components/Suspense.ts", "type": "replace", "edit_start_line_idx": 106 }
import { ComponentOptionsMixin, ComponentOptionsWithArrayProps, ComponentOptionsWithObjectProps, ComponentOptionsWithoutProps, ComponentPropsOptions, ComponentPublicInstance, ComputedOptions, EmitsOptions, MethodOptions, RenderFunction, SetupContext, ComponentInternalInstance, VNode, RootHydrateFunction, ExtractPropTypes, createVNode, defineComponent, nextTick, warn, ConcreteComponent, ComponentOptions, ComponentInjectOptions, SlotsType } from '@vue/runtime-core' import { camelize, extend, hyphenate, isArray, toNumber } from '@vue/shared' import { hydrate, render } from '.' export type VueElementConstructor<P = {}> = { new (initialProps?: Record<string, any>): VueElement & P } // defineCustomElement provides the same type inference as defineComponent // so most of the following overloads should be kept in sync w/ defineComponent. // overload 1: direct setup function export function defineCustomElement<Props, RawBindings = object>( setup: ( props: Readonly<Props>, ctx: SetupContext ) => RawBindings | RenderFunction ): VueElementConstructor<Props> // overload 2: object format with no props export function defineCustomElement< Props = {}, RawBindings = {}, D = {}, C extends ComputedOptions = {}, M extends MethodOptions = {}, Mixin extends ComponentOptionsMixin = ComponentOptionsMixin, Extends extends ComponentOptionsMixin = ComponentOptionsMixin, E extends EmitsOptions = EmitsOptions, EE extends string = string, I extends ComponentInjectOptions = {}, II extends string = string, S extends SlotsType = {} >( options: ComponentOptionsWithoutProps< Props, RawBindings, D, C, M, Mixin, Extends, E, EE, I, II, S > & { styles?: string[] } ): VueElementConstructor<Props> // overload 3: object format with array props declaration export function defineCustomElement< PropNames extends string, RawBindings, D, C extends ComputedOptions = {}, M extends MethodOptions = {}, Mixin extends ComponentOptionsMixin = ComponentOptionsMixin, Extends extends ComponentOptionsMixin = ComponentOptionsMixin, E extends EmitsOptions = Record<string, any>, EE extends string = string, I extends ComponentInjectOptions = {}, II extends string = string, S extends SlotsType = {} >( options: ComponentOptionsWithArrayProps< PropNames, RawBindings, D, C, M, Mixin, Extends, E, EE, I, II, S > & { styles?: string[] } ): VueElementConstructor<{ [K in PropNames]: any }> // overload 4: object format with object props declaration export function defineCustomElement< PropsOptions extends Readonly<ComponentPropsOptions>, RawBindings, D, C extends ComputedOptions = {}, M extends MethodOptions = {}, Mixin extends ComponentOptionsMixin = ComponentOptionsMixin, Extends extends ComponentOptionsMixin = ComponentOptionsMixin, E extends EmitsOptions = Record<string, any>, EE extends string = string, I extends ComponentInjectOptions = {}, II extends string = string, S extends SlotsType = {} >( options: ComponentOptionsWithObjectProps< PropsOptions, RawBindings, D, C, M, Mixin, Extends, E, EE, I, II, S > & { styles?: string[] } ): VueElementConstructor<ExtractPropTypes<PropsOptions>> // overload 5: defining a custom element from the returned value of // `defineComponent` export function defineCustomElement(options: { new (...args: any[]): ComponentPublicInstance }): VueElementConstructor export function defineCustomElement( options: any, hydrate?: RootHydrateFunction ): VueElementConstructor { const Comp = defineComponent(options) as any class VueCustomElement extends VueElement { static def = Comp constructor(initialProps?: Record<string, any>) { super(Comp, initialProps, hydrate) } } return VueCustomElement } export const defineSSRCustomElement = ((options: any) => { // @ts-ignore return defineCustomElement(options, hydrate) }) as typeof defineCustomElement const BaseClass = ( typeof HTMLElement !== 'undefined' ? HTMLElement : class {} ) as typeof HTMLElement type InnerComponentDef = ConcreteComponent & { styles?: string[] } export class VueElement extends BaseClass { /** * @internal */ _instance: ComponentInternalInstance | null = null private _connected = false private _resolved = false private _numberProps: Record<string, true> | null = null private _styles?: HTMLStyleElement[] constructor( private _def: InnerComponentDef, private _props: Record<string, any> = {}, hydrate?: RootHydrateFunction ) { super() if (this.shadowRoot && hydrate) { hydrate(this._createVNode(), this.shadowRoot) } else { if (__DEV__ && this.shadowRoot) { warn( `Custom element has pre-rendered declarative shadow root but is not ` + `defined as hydratable. Use \`defineSSRCustomElement\`.` ) } this.attachShadow({ mode: 'open' }) if (!(this._def as ComponentOptions).__asyncLoader) { // for sync component defs we can immediately resolve props this._resolveProps(this._def) } } } connectedCallback() { this._connected = true if (!this._instance) { if (this._resolved) { this._update() } else { this._resolveDef() } } } disconnectedCallback() { this._connected = false nextTick(() => { if (!this._connected) { render(null, this.shadowRoot!) this._instance = null } }) } /** * resolve inner component definition (handle possible async component) */ private _resolveDef() { this._resolved = true // set initial attrs for (let i = 0; i < this.attributes.length; i++) { this._setAttr(this.attributes[i].name) } // watch future attr changes new MutationObserver(mutations => { for (const m of mutations) { this._setAttr(m.attributeName!) } }).observe(this, { attributes: true }) const resolve = (def: InnerComponentDef, isAsync = false) => { const { props, styles } = def // cast Number-type props set before resolve let numberProps if (props && !isArray(props)) { for (const key in props) { const opt = props[key] if (opt === Number || (opt && opt.type === Number)) { if (key in this._props) { this._props[key] = toNumber(this._props[key]) } ;(numberProps || (numberProps = Object.create(null)))[ camelize(key) ] = true } } } this._numberProps = numberProps if (isAsync) { // defining getter/setters on prototype // for sync defs, this already happened in the constructor this._resolveProps(def) } // apply CSS this._applyStyles(styles) // initial render this._update() } const asyncDef = (this._def as ComponentOptions).__asyncLoader if (asyncDef) { asyncDef().then(def => resolve(def, true)) } else { resolve(this._def) } } private _resolveProps(def: InnerComponentDef) { const { props } = def const declaredPropKeys = isArray(props) ? props : Object.keys(props || {}) // check if there are props set pre-upgrade or connect for (const key of Object.keys(this)) { if (key[0] !== '_' && declaredPropKeys.includes(key)) { this._setProp(key, this[key as keyof this], true, false) } } // defining getter/setters on prototype for (const key of declaredPropKeys.map(camelize)) { Object.defineProperty(this, key, { get() { return this._getProp(key) }, set(val) { this._setProp(key, val) } }) } } protected _setAttr(key: string) { let value = this.getAttribute(key) const camelKey = camelize(key) if (this._numberProps && this._numberProps[camelKey]) { value = toNumber(value) } this._setProp(camelKey, value, false) } /** * @internal */ protected _getProp(key: string) { return this._props[key] } /** * @internal */ protected _setProp( key: string, val: any, shouldReflect = true, shouldUpdate = true ) { if (val !== this._props[key]) { this._props[key] = val if (shouldUpdate && this._instance) { this._update() } // reflect if (shouldReflect) { if (val === true) { this.setAttribute(hyphenate(key), '') } else if (typeof val === 'string' || typeof val === 'number') { this.setAttribute(hyphenate(key), val + '') } else if (!val) { this.removeAttribute(hyphenate(key)) } } } } private _update() { render(this._createVNode(), this.shadowRoot!) } private _createVNode(): VNode<any, any> { const vnode = createVNode(this._def, extend({}, this._props)) if (!this._instance) { vnode.ce = instance => { this._instance = instance instance.isCE = true // HMR if (__DEV__) { instance.ceReload = newStyles => { // always reset styles if (this._styles) { this._styles.forEach(s => this.shadowRoot!.removeChild(s)) this._styles.length = 0 } this._applyStyles(newStyles) this._instance = null this._update() } } const dispatch = (event: string, args: any[]) => { this.dispatchEvent( new CustomEvent(event, { detail: args }) ) } // intercept emit instance.emit = (event: string, ...args: any[]) => { // dispatch both the raw and hyphenated versions of an event // to match Vue behavior dispatch(event, args) if (hyphenate(event) !== event) { dispatch(hyphenate(event), args) } } // locate nearest Vue custom element parent for provide/inject let parent: Node | null = this while ( (parent = parent && (parent.parentNode || (parent as ShadowRoot).host)) ) { if (parent instanceof VueElement) { instance.parent = parent._instance instance.provides = parent._instance!.provides break } } } } return vnode } private _applyStyles(styles: string[] | undefined) { if (styles) { styles.forEach(css => { const s = document.createElement('style') s.textContent = css this.shadowRoot!.appendChild(s) // record for HMR if (__DEV__) { ;(this._styles || (this._styles = [])).push(s) } }) } } }
packages/runtime-dom/src/apiCustomElement.ts
0
https://github.com/vuejs/core/commit/3cb4dc9e5538e1c2bde9fa691b001615a848c546
[ 0.0034855948761105537, 0.0002649401139933616, 0.00016212384798564017, 0.00017140393902081996, 0.0005008797743357718 ]
{ "id": 2, "code_window": [ " ? SuspenseImpl\n", " : null) as unknown as {\n", " __isSuspense: true\n", " new (): { $props: VNodeProps & SuspenseProps }\n", "}\n", "\n", "function triggerEvent(\n", " vnode: VNode,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " new (): {\n", " $props: VNodeProps & SuspenseProps\n", " $slots: {\n", " default(): VNode[]\n", " fallback(): VNode[]\n", " }\n", " }\n" ], "file_path": "packages/runtime-core/src/components/Suspense.ts", "type": "replace", "edit_start_line_idx": 106 }
import path from 'path' import { ConstantTypes, createSimpleExpression, ExpressionNode, NodeTransform, NodeTypes, SimpleExpressionNode, SourceLocation, TransformContext } from '@vue/compiler-core' import { isRelativeUrl, parseUrl, isExternalUrl, isDataUrl } from './templateUtils' import { isArray } from '@vue/shared' export interface AssetURLTagConfig { [name: string]: string[] } export interface AssetURLOptions { /** * If base is provided, instead of transforming relative asset urls into * imports, they will be directly rewritten to absolute urls. */ base?: string | null /** * If true, also processes absolute urls. */ includeAbsolute?: boolean tags?: AssetURLTagConfig } export const defaultAssetUrlOptions: Required<AssetURLOptions> = { base: null, includeAbsolute: false, tags: { video: ['src', 'poster'], source: ['src'], img: ['src'], image: ['xlink:href', 'href'], use: ['xlink:href', 'href'] } } export const normalizeOptions = ( options: AssetURLOptions | AssetURLTagConfig ): Required<AssetURLOptions> => { if (Object.keys(options).some(key => isArray((options as any)[key]))) { // legacy option format which directly passes in tags config return { ...defaultAssetUrlOptions, tags: options as any } } return { ...defaultAssetUrlOptions, ...options } } export const createAssetUrlTransformWithOptions = ( options: Required<AssetURLOptions> ): NodeTransform => { return (node, context) => (transformAssetUrl as Function)(node, context, options) } /** * A `@vue/compiler-core` plugin that transforms relative asset urls into * either imports or absolute urls. * * ``` js * // Before * createVNode('img', { src: './logo.png' }) * * // After * import _imports_0 from './logo.png' * createVNode('img', { src: _imports_0 }) * ``` */ export const transformAssetUrl: NodeTransform = ( node, context, options: AssetURLOptions = defaultAssetUrlOptions ) => { if (node.type === NodeTypes.ELEMENT) { if (!node.props.length) { return } const tags = options.tags || defaultAssetUrlOptions.tags const attrs = tags[node.tag] const wildCardAttrs = tags['*'] if (!attrs && !wildCardAttrs) { return } const assetAttrs = (attrs || []).concat(wildCardAttrs || []) node.props.forEach((attr, index) => { if ( attr.type !== NodeTypes.ATTRIBUTE || !assetAttrs.includes(attr.name) || !attr.value || isExternalUrl(attr.value.content) || isDataUrl(attr.value.content) || attr.value.content[0] === '#' || (!options.includeAbsolute && !isRelativeUrl(attr.value.content)) ) { return } const url = parseUrl(attr.value.content) if (options.base && attr.value.content[0] === '.') { // explicit base - directly rewrite relative urls into absolute url // to avoid generating extra imports // Allow for full hostnames provided in options.base const base = parseUrl(options.base) const protocol = base.protocol || '' const host = base.host ? protocol + '//' + base.host : '' const basePath = base.path || '/' // when packaged in the browser, path will be using the posix- // only version provided by rollup-plugin-node-builtins. attr.value.content = host + (path.posix || path).join(basePath, url.path + (url.hash || '')) return } // otherwise, transform the url into an import. // this assumes a bundler will resolve the import into the correct // absolute url (e.g. webpack file-loader) const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context) node.props[index] = { type: NodeTypes.DIRECTIVE, name: 'bind', arg: createSimpleExpression(attr.name, true, attr.loc), exp, modifiers: [], loc: attr.loc } }) } } function getImportsExpressionExp( path: string | null, hash: string | null, loc: SourceLocation, context: TransformContext ): ExpressionNode { if (path) { let name: string let exp: SimpleExpressionNode const existingIndex = context.imports.findIndex(i => i.path === path) if (existingIndex > -1) { name = `_imports_${existingIndex}` exp = context.imports[existingIndex].exp as SimpleExpressionNode } else { name = `_imports_${context.imports.length}` exp = createSimpleExpression( name, false, loc, ConstantTypes.CAN_STRINGIFY ) context.imports.push({ exp, path }) } if (!hash) { return exp } const hashExp = `${name} + '${hash}'` const finalExp = createSimpleExpression( hashExp, false, loc, ConstantTypes.CAN_STRINGIFY ) if (!context.hoistStatic) { return finalExp } const existingHoistIndex = context.hoists.findIndex(h => { return ( h && h.type === NodeTypes.SIMPLE_EXPRESSION && !h.isStatic && h.content === hashExp ) }) if (existingHoistIndex > -1) { return createSimpleExpression( `_hoisted_${existingHoistIndex + 1}`, false, loc, ConstantTypes.CAN_STRINGIFY ) } return context.hoist(finalExp) } else { return createSimpleExpression(`''`, false, loc, ConstantTypes.CAN_STRINGIFY) } }
packages/compiler-sfc/src/template/transformAssetUrl.ts
0
https://github.com/vuejs/core/commit/3cb4dc9e5538e1c2bde9fa691b001615a848c546
[ 0.000980609329417348, 0.00021339398517739028, 0.00016461779887322336, 0.00017422495875507593, 0.00016796406998764724 ]
{ "id": 3, "code_window": [ "}\n", "\n", "// Force-casted public typing for h and TSX props inference\n", "export const Teleport = TeleportImpl as unknown as {\n", " __isTeleport: true\n", " new (): { $props: VNodeProps & TeleportProps }\n", "}\n", "\n", "function updateCssVars(vnode: VNode) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " new(): {\n", " $props: VNodeProps & TeleportProps\n", " $slots: {\n", " default(): VNode[]\n", " }\n", " }\n" ], "file_path": "packages/runtime-core/src/components/Teleport.ts", "type": "replace", "edit_start_line_idx": 395 }
import { ConcreteComponent, getCurrentInstance, SetupContext, ComponentInternalInstance, currentInstance, getComponentName, ComponentOptions } from '../component' import { VNode, cloneVNode, isVNode, VNodeProps, invokeVNodeHook, isSameVNodeType } from '../vnode' import { warn } from '../warning' import { onBeforeUnmount, injectHook, onUnmounted, onMounted, onUpdated } from '../apiLifecycle' import { isString, isArray, isRegExp, ShapeFlags, remove, invokeArrayFns } from '@vue/shared' import { watch } from '../apiWatch' import { RendererInternals, queuePostRenderEffect, MoveType, RendererElement, RendererNode } from '../renderer' import { setTransitionHooks } from './BaseTransition' import { ComponentRenderContext } from '../componentPublicInstance' import { devtoolsComponentAdded } from '../devtools' import { isAsyncWrapper } from '../apiAsyncComponent' import { isSuspense } from './Suspense' import { LifecycleHooks } from '../enums' type MatchPattern = string | RegExp | (string | RegExp)[] export interface KeepAliveProps { include?: MatchPattern exclude?: MatchPattern max?: number | string } type CacheKey = string | number | symbol | ConcreteComponent type Cache = Map<CacheKey, VNode> type Keys = Set<CacheKey> export interface KeepAliveContext extends ComponentRenderContext { renderer: RendererInternals activate: ( vnode: VNode, container: RendererElement, anchor: RendererNode | null, isSVG: boolean, optimized: boolean ) => void deactivate: (vnode: VNode) => void } export const isKeepAlive = (vnode: VNode): boolean => (vnode.type as any).__isKeepAlive const KeepAliveImpl: ComponentOptions = { name: `KeepAlive`, // Marker for special handling inside the renderer. We are not using a === // check directly on KeepAlive in the renderer, because importing it directly // would prevent it from being tree-shaken. __isKeepAlive: true, props: { include: [String, RegExp, Array], exclude: [String, RegExp, Array], max: [String, Number] }, setup(props: KeepAliveProps, { slots }: SetupContext) { const instance = getCurrentInstance()! // KeepAlive communicates with the instantiated renderer via the // ctx where the renderer passes in its internals, // and the KeepAlive instance exposes activate/deactivate implementations. // The whole point of this is to avoid importing KeepAlive directly in the // renderer to facilitate tree-shaking. const sharedContext = instance.ctx as KeepAliveContext // if the internal renderer is not registered, it indicates that this is server-side rendering, // for KeepAlive, we just need to render its children if (__SSR__ && !sharedContext.renderer) { return () => { const children = slots.default && slots.default() return children && children.length === 1 ? children[0] : children } } const cache: Cache = new Map() const keys: Keys = new Set() let current: VNode | null = null if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) { ;(instance as any).__v_cache = cache } const parentSuspense = instance.suspense const { renderer: { p: patch, m: move, um: _unmount, o: { createElement } } } = sharedContext const storageContainer = createElement('div') sharedContext.activate = (vnode, container, anchor, isSVG, optimized) => { const instance = vnode.component! move(vnode, container, anchor, MoveType.ENTER, parentSuspense) // in case props have changed patch( instance.vnode, vnode, container, anchor, instance, parentSuspense, isSVG, vnode.slotScopeIds, optimized ) queuePostRenderEffect(() => { instance.isDeactivated = false if (instance.a) { invokeArrayFns(instance.a) } const vnodeHook = vnode.props && vnode.props.onVnodeMounted if (vnodeHook) { invokeVNodeHook(vnodeHook, instance.parent, vnode) } }, parentSuspense) if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) { // Update components tree devtoolsComponentAdded(instance) } } sharedContext.deactivate = (vnode: VNode) => { const instance = vnode.component! move(vnode, storageContainer, null, MoveType.LEAVE, parentSuspense) queuePostRenderEffect(() => { if (instance.da) { invokeArrayFns(instance.da) } const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted if (vnodeHook) { invokeVNodeHook(vnodeHook, instance.parent, vnode) } instance.isDeactivated = true }, parentSuspense) if (__DEV__ || __FEATURE_PROD_DEVTOOLS__) { // Update components tree devtoolsComponentAdded(instance) } } function unmount(vnode: VNode) { // reset the shapeFlag so it can be properly unmounted resetShapeFlag(vnode) _unmount(vnode, instance, parentSuspense, true) } function pruneCache(filter?: (name: string) => boolean) { cache.forEach((vnode, key) => { const name = getComponentName(vnode.type as ConcreteComponent) if (name && (!filter || !filter(name))) { pruneCacheEntry(key) } }) } function pruneCacheEntry(key: CacheKey) { const cached = cache.get(key) as VNode if (!current || !isSameVNodeType(cached, current)) { unmount(cached) } else if (current) { // current active instance should no longer be kept-alive. // we can't unmount it now but it might be later, so reset its flag now. resetShapeFlag(current) } cache.delete(key) keys.delete(key) } // prune cache on include/exclude prop change watch( () => [props.include, props.exclude], ([include, exclude]) => { include && pruneCache(name => matches(include, name)) exclude && pruneCache(name => !matches(exclude, name)) }, // prune post-render after `current` has been updated { flush: 'post', deep: true } ) // cache sub tree after render let pendingCacheKey: CacheKey | null = null const cacheSubtree = () => { // fix #1621, the pendingCacheKey could be 0 if (pendingCacheKey != null) { cache.set(pendingCacheKey, getInnerChild(instance.subTree)) } } onMounted(cacheSubtree) onUpdated(cacheSubtree) onBeforeUnmount(() => { cache.forEach(cached => { const { subTree, suspense } = instance const vnode = getInnerChild(subTree) if (cached.type === vnode.type && cached.key === vnode.key) { // current instance will be unmounted as part of keep-alive's unmount resetShapeFlag(vnode) // but invoke its deactivated hook here const da = vnode.component!.da da && queuePostRenderEffect(da, suspense) return } unmount(cached) }) }) return () => { pendingCacheKey = null if (!slots.default) { return null } const children = slots.default() const rawVNode = children[0] if (children.length > 1) { if (__DEV__) { warn(`KeepAlive should contain exactly one component child.`) } current = null return children } else if ( !isVNode(rawVNode) || (!(rawVNode.shapeFlag & ShapeFlags.STATEFUL_COMPONENT) && !(rawVNode.shapeFlag & ShapeFlags.SUSPENSE)) ) { current = null return rawVNode } let vnode = getInnerChild(rawVNode) const comp = vnode.type as ConcreteComponent // for async components, name check should be based in its loaded // inner component if available const name = getComponentName( isAsyncWrapper(vnode) ? (vnode.type as ComponentOptions).__asyncResolved || {} : comp ) const { include, exclude, max } = props if ( (include && (!name || !matches(include, name))) || (exclude && name && matches(exclude, name)) ) { current = vnode return rawVNode } const key = vnode.key == null ? comp : vnode.key const cachedVNode = cache.get(key) // clone vnode if it's reused because we are going to mutate it if (vnode.el) { vnode = cloneVNode(vnode) if (rawVNode.shapeFlag & ShapeFlags.SUSPENSE) { rawVNode.ssContent = vnode } } // #1513 it's possible for the returned vnode to be cloned due to attr // fallthrough or scopeId, so the vnode here may not be the final vnode // that is mounted. Instead of caching it directly, we store the pending // key and cache `instance.subTree` (the normalized vnode) in // beforeMount/beforeUpdate hooks. pendingCacheKey = key if (cachedVNode) { // copy over mounted state vnode.el = cachedVNode.el vnode.component = cachedVNode.component if (vnode.transition) { // recursively update transition hooks on subTree setTransitionHooks(vnode, vnode.transition!) } // avoid vnode being mounted as fresh vnode.shapeFlag |= ShapeFlags.COMPONENT_KEPT_ALIVE // make this key the freshest keys.delete(key) keys.add(key) } else { keys.add(key) // prune oldest entry if (max && keys.size > parseInt(max as string, 10)) { pruneCacheEntry(keys.values().next().value) } } // avoid vnode being unmounted vnode.shapeFlag |= ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE current = vnode return isSuspense(rawVNode.type) ? rawVNode : vnode } } } if (__COMPAT__) { KeepAliveImpl.__isBuildIn = true } // 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 { __isKeepAlive: true new (): { $props: VNodeProps & KeepAliveProps } } function matches(pattern: MatchPattern, name: string): boolean { if (isArray(pattern)) { return pattern.some((p: string | RegExp) => matches(p, name)) } else if (isString(pattern)) { return pattern.split(',').includes(name) } else if (isRegExp(pattern)) { return pattern.test(name) } /* istanbul ignore next */ return false } export function onActivated( hook: Function, target?: ComponentInternalInstance | null ) { registerKeepAliveHook(hook, LifecycleHooks.ACTIVATED, target) } export function onDeactivated( hook: Function, target?: ComponentInternalInstance | null ) { registerKeepAliveHook(hook, LifecycleHooks.DEACTIVATED, target) } function registerKeepAliveHook( hook: Function & { __wdc?: Function }, type: LifecycleHooks, target: ComponentInternalInstance | null = currentInstance ) { // cache the deactivate branch check wrapper for injected hooks so the same // hook can be properly deduped by the scheduler. "__wdc" stands for "with // deactivation check". const wrappedHook = hook.__wdc || (hook.__wdc = () => { // only fire the hook if the target instance is NOT in a deactivated branch. let current: ComponentInternalInstance | null = target while (current) { if (current.isDeactivated) { return } current = current.parent } return hook() }) injectHook(type, wrappedHook, target) // In addition to registering it on the target instance, we walk up the parent // chain and register it on all ancestor instances that are keep-alive roots. // This avoids the need to walk the entire component tree when invoking these // hooks, and more importantly, avoids the need to track child components in // arrays. if (target) { let current = target.parent while (current && current.parent) { if (isKeepAlive(current.parent.vnode)) { injectToKeepAliveRoot(wrappedHook, type, target, current) } current = current.parent } } } function injectToKeepAliveRoot( hook: Function & { __weh?: Function }, type: LifecycleHooks, target: ComponentInternalInstance, keepAliveRoot: ComponentInternalInstance ) { // injectHook wraps the original for error handling, so make sure to remove // the wrapped version. const injected = injectHook(type, hook, keepAliveRoot, true /* prepend */) onUnmounted(() => { remove(keepAliveRoot[type]!, injected) }, target) } function resetShapeFlag(vnode: VNode) { // bitwise operations to remove keep alive flags vnode.shapeFlag &= ~ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE vnode.shapeFlag &= ~ShapeFlags.COMPONENT_KEPT_ALIVE } function getInnerChild(vnode: VNode) { return vnode.shapeFlag & ShapeFlags.SUSPENSE ? vnode.ssContent! : vnode }
packages/runtime-core/src/components/KeepAlive.ts
1
https://github.com/vuejs/core/commit/3cb4dc9e5538e1c2bde9fa691b001615a848c546
[ 0.009018778800964355, 0.0006580696790479124, 0.00016413505363743752, 0.0002057362871710211, 0.001371837453916669 ]
{ "id": 3, "code_window": [ "}\n", "\n", "// Force-casted public typing for h and TSX props inference\n", "export const Teleport = TeleportImpl as unknown as {\n", " __isTeleport: true\n", " new (): { $props: VNodeProps & TeleportProps }\n", "}\n", "\n", "function updateCssVars(vnode: VNode) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " new(): {\n", " $props: VNodeProps & TeleportProps\n", " $slots: {\n", " default(): VNode[]\n", " }\n", " }\n" ], "file_path": "packages/runtime-core/src/components/Teleport.ts", "type": "replace", "edit_start_line_idx": 395 }
import { Data } from '../component' import { Slots, RawSlots } from '../componentSlots' import { ContextualRenderFn, currentRenderingInstance } from '../componentRenderContext' import { Comment, isVNode, VNodeArrayChildren, openBlock, createBlock, Fragment, VNode } from '../vnode' import { PatchFlags, SlotFlags } from '@vue/shared' import { warn } from '../warning' import { createVNode } from '@vue/runtime-core' import { isAsyncWrapper } from '../apiAsyncComponent' /** * Compiler runtime helper for rendering `<slot/>` * @private */ export function renderSlot( slots: Slots, name: string, props: Data = {}, // this is not a user-facing function, so the fallback is always generated by // the compiler and guaranteed to be a function returning an array fallback?: () => VNodeArrayChildren, noSlotted?: boolean ): VNode { if ( currentRenderingInstance!.isCE || (currentRenderingInstance!.parent && isAsyncWrapper(currentRenderingInstance!.parent) && currentRenderingInstance!.parent.isCE) ) { if (name !== 'default') props.name = name return createVNode('slot', props, fallback && fallback()) } let slot = slots[name] if (__DEV__ && slot && slot.length > 1) { warn( `SSR-optimized slot function detected in a non-SSR-optimized render ` + `function. You need to mark this component with $dynamic-slots in the ` + `parent template.` ) slot = () => [] } // a compiled slot disables block tracking by default to avoid manual // invocation interfering with template-based block tracking, but in // `renderSlot` we can be sure that it's template-based so we can force // enable it. if (slot && (slot as ContextualRenderFn)._c) { ;(slot as ContextualRenderFn)._d = false } openBlock() const validSlotContent = slot && ensureValidVNode(slot(props)) const rendered = createBlock( Fragment, { key: props.key || // slot content array of a dynamic conditional slot may have a branch // key attached in the `createSlots` helper, respect that (validSlotContent && (validSlotContent as any).key) || `_${name}` }, validSlotContent || (fallback ? fallback() : []), validSlotContent && (slots as RawSlots)._ === SlotFlags.STABLE ? PatchFlags.STABLE_FRAGMENT : PatchFlags.BAIL ) if (!noSlotted && rendered.scopeId) { rendered.slotScopeIds = [rendered.scopeId + '-s'] } if (slot && (slot as ContextualRenderFn)._c) { ;(slot as ContextualRenderFn)._d = true } return rendered } function ensureValidVNode(vnodes: VNodeArrayChildren) { return vnodes.some(child => { if (!isVNode(child)) return true if (child.type === Comment) return false if ( child.type === Fragment && !ensureValidVNode(child.children as VNodeArrayChildren) ) return false return true }) ? vnodes : null }
packages/runtime-core/src/helpers/renderSlot.ts
0
https://github.com/vuejs/core/commit/3cb4dc9e5538e1c2bde9fa691b001615a848c546
[ 0.0011119651608169079, 0.0003061785246245563, 0.00016535639588255435, 0.00017819346976466477, 0.00027100229635834694 ]
{ "id": 3, "code_window": [ "}\n", "\n", "// Force-casted public typing for h and TSX props inference\n", "export const Teleport = TeleportImpl as unknown as {\n", " __isTeleport: true\n", " new (): { $props: VNodeProps & TeleportProps }\n", "}\n", "\n", "function updateCssVars(vnode: VNode) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " new(): {\n", " $props: VNodeProps & TeleportProps\n", " $slots: {\n", " default(): VNode[]\n", " }\n", " }\n" ], "file_path": "packages/runtime-core/src/components/Teleport.ts", "type": "replace", "edit_start_line_idx": 395 }
// TSX w/ defineComponent is tested in defineComponent.test-d.tsx import { KeepAlive, Suspense, Fragment, Teleport, VNode } from 'vue' import { expectType } from './utils' expectType<VNode>(<div />) expectType<JSX.Element>(<div />) expectType<JSX.Element>(<div id="foo" />) expectType<JSX.Element>(<div>hello</div>) expectType<JSX.Element>(<input value="foo" />) // @ts-expect-error style css property validation ;<div style={{ unknown: 123 }} /> // allow array styles and nested array styles expectType<JSX.Element>(<div style={[{ color: 'red' }]} />) expectType<JSX.Element>( <div style={[{ color: 'red' }, [{ fontSize: '1em' }]]} /> ) // @ts-expect-error unknown prop ;<div foo="bar" /> // allow key/ref on arbitrary element expectType<JSX.Element>(<div key="foo" />) expectType<JSX.Element>(<div ref="bar" />) expectType<JSX.Element>( <input onInput={e => { // infer correct event type expectType<EventTarget | null>(e.target) }} /> ) // built-in types expectType<JSX.Element>(<Fragment />) expectType<JSX.Element>(<Fragment key="1" />) expectType<JSX.Element>(<Teleport to="#foo" />) expectType<JSX.Element>(<Teleport to="#foo" key="1" />) // @ts-expect-error ;<Teleport /> // @ts-expect-error ;<Teleport to={1} /> // KeepAlive expectType<JSX.Element>(<KeepAlive include="foo" exclude={['a']} />) expectType<JSX.Element>(<KeepAlive key="1" />) // @ts-expect-error ;<KeepAlive include={123} /> // Suspense expectType<JSX.Element>(<Suspense />) expectType<JSX.Element>(<Suspense key="1" />) expectType<JSX.Element>( <Suspense onResolve={() => {}} onFallback={() => {}} onPending={() => {}} /> ) // @ts-expect-error ;<Suspense onResolve={123} />
packages/dts-test/tsx.test-d.tsx
0
https://github.com/vuejs/core/commit/3cb4dc9e5538e1c2bde9fa691b001615a848c546
[ 0.9656292796134949, 0.1561095267534256, 0.0001704815513221547, 0.00017722253687679768, 0.3330046534538269 ]
{ "id": 3, "code_window": [ "}\n", "\n", "// Force-casted public typing for h and TSX props inference\n", "export const Teleport = TeleportImpl as unknown as {\n", " __isTeleport: true\n", " new (): { $props: VNodeProps & TeleportProps }\n", "}\n", "\n", "function updateCssVars(vnode: VNode) {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " new(): {\n", " $props: VNodeProps & TeleportProps\n", " $slots: {\n", " default(): VNode[]\n", " }\n", " }\n" ], "file_path": "packages/runtime-core/src/components/Teleport.ts", "type": "replace", "edit_start_line_idx": 395 }
/* eslint-disable no-restricted-globals */ import { App } from './apiCreateApp' import { Fragment, Text, Comment, Static } from './vnode' import { ComponentInternalInstance } from './component' interface AppRecord { id: number app: App version: string types: Record<string, string | Symbol> } const enum DevtoolsHooks { APP_INIT = 'app:init', APP_UNMOUNT = 'app:unmount', COMPONENT_UPDATED = 'component:updated', COMPONENT_ADDED = 'component:added', COMPONENT_REMOVED = 'component:removed', COMPONENT_EMIT = 'component:emit', PERFORMANCE_START = 'perf:start', PERFORMANCE_END = 'perf:end' } interface DevtoolsHook { enabled?: boolean emit: (event: string, ...payload: any[]) => void on: (event: string, handler: Function) => void once: (event: string, handler: Function) => void off: (event: string, handler: Function) => void appRecords: AppRecord[] /** * Added at https://github.com/vuejs/devtools/commit/f2ad51eea789006ab66942e5a27c0f0986a257f9 * Returns wether the arg was buffered or not */ cleanupBuffer?: (matchArg: unknown) => boolean } export let devtools: DevtoolsHook let buffer: { event: string; args: any[] }[] = [] let devtoolsNotInstalled = false function emit(event: string, ...args: any[]) { if (devtools) { devtools.emit(event, ...args) } else if (!devtoolsNotInstalled) { buffer.push({ event, args }) } } export function setDevtoolsHook(hook: DevtoolsHook, target: any) { devtools = hook if (devtools) { devtools.enabled = true buffer.forEach(({ event, args }) => devtools.emit(event, ...args)) buffer = [] } else if ( // handle late devtools injection - only do this if we are in an actual // browser environment to avoid the timer handle stalling test runner exit // (#4815) typeof window !== 'undefined' && // some envs mock window but not fully window.HTMLElement && // also exclude jsdom !window.navigator?.userAgent?.includes('jsdom') ) { const replay = (target.__VUE_DEVTOOLS_HOOK_REPLAY__ = target.__VUE_DEVTOOLS_HOOK_REPLAY__ || []) replay.push((newHook: DevtoolsHook) => { setDevtoolsHook(newHook, target) }) // clear buffer after 3s - the user probably doesn't have devtools installed // at all, and keeping the buffer will cause memory leaks (#4738) setTimeout(() => { if (!devtools) { target.__VUE_DEVTOOLS_HOOK_REPLAY__ = null devtoolsNotInstalled = true buffer = [] } }, 3000) } else { // non-browser env, assume not installed devtoolsNotInstalled = true buffer = [] } } export function devtoolsInitApp(app: App, version: string) { emit(DevtoolsHooks.APP_INIT, app, version, { Fragment, Text, Comment, Static }) } export function devtoolsUnmountApp(app: App) { emit(DevtoolsHooks.APP_UNMOUNT, app) } export const devtoolsComponentAdded = /*#__PURE__*/ createDevtoolsComponentHook( DevtoolsHooks.COMPONENT_ADDED ) export const devtoolsComponentUpdated = /*#__PURE__*/ createDevtoolsComponentHook(DevtoolsHooks.COMPONENT_UPDATED) const _devtoolsComponentRemoved = /*#__PURE__*/ createDevtoolsComponentHook( DevtoolsHooks.COMPONENT_REMOVED ) export const devtoolsComponentRemoved = ( component: ComponentInternalInstance ) => { if ( devtools && typeof devtools.cleanupBuffer === 'function' && // remove the component if it wasn't buffered !devtools.cleanupBuffer(component) ) { _devtoolsComponentRemoved(component) } } function createDevtoolsComponentHook(hook: DevtoolsHooks) { return (component: ComponentInternalInstance) => { emit( hook, component.appContext.app, component.uid, component.parent ? component.parent.uid : undefined, component ) } } export const devtoolsPerfStart = /*#__PURE__*/ createDevtoolsPerformanceHook( DevtoolsHooks.PERFORMANCE_START ) export const devtoolsPerfEnd = /*#__PURE__*/ createDevtoolsPerformanceHook( DevtoolsHooks.PERFORMANCE_END ) function createDevtoolsPerformanceHook(hook: DevtoolsHooks) { return (component: ComponentInternalInstance, type: string, time: number) => { emit(hook, component.appContext.app, component.uid, component, type, time) } } export function devtoolsComponentEmit( component: ComponentInternalInstance, event: string, params: any[] ) { emit( DevtoolsHooks.COMPONENT_EMIT, component.appContext.app, component, event, params ) }
packages/runtime-core/src/devtools.ts
0
https://github.com/vuejs/core/commit/3cb4dc9e5538e1c2bde9fa691b001615a848c546
[ 0.00017639494035393, 0.00017070744070224464, 0.00016412127297371626, 0.00017091170593630522, 0.0000038104792565718526 ]
{ "id": 0, "code_window": [ "\n", "\n", "## Dependencies\n", "\n", "### Depends on\n", "\n", "- [ion-backdrop](../backdrop)\n", "- ion-icon\n", "- [ion-ripple-effect](../ripple-effect)\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "### Used by\n", "\n", " - [ion-select](../select)\n", "\n" ], "file_path": "core/src/components/action-sheet/readme.md", "type": "add", "edit_start_line_idx": 663 }
# ion-select Selects are form controls to select an option, or options, from a set of options, similar to a native `<select>` element. When a user taps the select, a dialog appears with all of the options in a large, easy to select list. A select should be used with child `<ion-select-option>` elements. If the child option is not given a `value` attribute then its text will be used as the value. If `value` is set on the `<ion-select>`, the selected option will be chosen based on that value. ## Interfaces By default, select uses [ion-alert](../alert) to open up the overlay of options in an alert. The interface can be changed to use [ion-action-sheet](../action-sheet) or [ion-popover](../popover) by passing `action-sheet` or `popover`, respectively, to the `interface` property. Read on to the other sections for the limitations of the different interfaces. ## Single Selection By default, the select allows the user to select only one option. The alert interface presents users with a radio button styled list of options. The action sheet interface can only be used with a single value select. The select component's value receives the value of the selected option's value. ## Multiple Selection By adding the `multiple` attribute to select, users are able to select multiple options. When multiple options can be selected, the alert overlay presents users with a checkbox styled list of options. The select component's value receives an array of all of the selected option values. Note: the `action-sheet` and `popover` interfaces will not work with multiple selection. ## Object Value References When using objects for select values, it is possible for the identities of these objects to change if they are coming from a server or database, while the selected value's identity remains the same. For example, this can occur when an existing record with the desired object value is loaded into the select, but the newly retrieved select options now have different identities. This will result in the select appearing to have no value at all, even though the original selection in still intact. By default, the select uses object equality (`===`) to determine if an option is selected. This can be overridden by providing a property name or a function to the `compareWith` property. ## Select Buttons The alert supports two buttons: `Cancel` and `OK`. Each button's text can be customized using the `cancelText` and `okText` properties. The `action-sheet` and `popover` interfaces do not have an `OK` button, clicking on any of the options will automatically close the overlay and select that value. The `popover` interface does not have a `Cancel` button, clicking on the backdrop will close the overlay. ## Interface Options Since select uses the alert, action sheet and popover interfaces, options can be passed to these components through the `interfaceOptions` property. This can be used to pass a custom header, subheader, css class, and more. See the [ion-alert docs](../alert), [ion-action-sheet docs](../action-sheet), and [ion-popover docs](../popover) for the properties that each interface accepts. Note: `interfaceOptions` will not override `inputs` or `buttons` with the `alert` interface. ## Customization There are two units that make up the Select component and each need to be styled separately. The `ion-select` element is represented on the view by the selected value(s), or placeholder if there is none, and dropdown icon. The interface, which is defined in the [Interfaces](#interfaces) section above, is the dialog that opens when clicking on the `ion-select`. The interface contains all of the options defined by adding `ion-select-option` elements. The following sections will go over the differences between styling these. ### Styling Select Element As mentioned, the `ion-select` element consists only of the value(s), or placeholder, and icon that is displayed on the view. To customize this, style using a combination of CSS and any of the [CSS custom properties](#css-custom-properties): ```css ion-select { /* Applies to the value and placeholder color */ color: #545ca7; /* Set a different placeholder color */ --placeholder-color: #971e49; /* Set full opacity on the placeholder */ --placeholder-opacity: 1; } ``` Alternatively, depending on the [browser support](https://caniuse.com/#feat=mdn-css_selectors_part) needed, CSS shadow parts can be used to style the select: ```css /* Set the width to the full container and center the content */ ion-select { width: 100%; justify-content: center; } /* Set the flex in order to size the text width to its content */ ion-select::part(placeholder), ion-select::part(text) { flex: 0 0 auto; } /* Set the placeholder color and opacity */ ion-select::part(placeholder) { color: #20a08a; opacity: 1; } /* * Set the font of the first letter of the placeholder * Shadow parts work with pseudo-elements, too! * https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements */ ion-select::part(placeholder)::first-letter { font-size: 24px; font-weight: 500; } /* Set the text color */ ion-select::part(text) { color: #545ca7; } /* Set the icon color and opacity */ ion-select::part(icon) { color: #971e49; opacity: 1; } ``` Notice that by using `::part`, any CSS property on the element can be targeted. ### Styling Select Interface Customizing the interface dialog should be done by following the Customization section in that interface's documentation: - [Alert Customization](../alert#customization) - [Action Sheet Customization](../action-sheet#customization) - [Popover Customization](../popover#customization) However, the Select Option does set a class for easier styling and allows for the ability to pass a class to the overlay option, see the [Select Options documentation](../select-option) for usage examples of customizing options. ## Interfaces ### SelectChangeEventDetail ```typescript interface SelectChangeEventDetail<T = any> { value: T; } ``` ### SelectCustomEvent While not required, this interface can be used in place of the `CustomEvent` interface for stronger typing with Ionic events emitted from this component. ```typescript interface SelectCustomEvent<T = any> extends CustomEvent { detail: SelectChangeEventDetail<T>; target: HTMLIonSelectElement; } ``` <!-- Auto Generated Below --> ## Usage ### Angular ### Single Selection ```html <ion-list> <ion-list-header> <ion-label> Single Selection </ion-label> </ion-list-header> <ion-item> <ion-label>Gender</ion-label> <ion-select placeholder="Select One"> <ion-select-option value="f">Female</ion-select-option> <ion-select-option value="m">Male</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Hair Color</ion-label> <ion-select value="brown" okText="Okay" cancelText="Dismiss"> <ion-select-option value="brown">Brown</ion-select-option> <ion-select-option value="blonde">Blonde</ion-select-option> <ion-select-option value="black">Black</ion-select-option> <ion-select-option value="red">Red</ion-select-option> </ion-select> </ion-item> </ion-list> ``` ### Multiple Selection ```html <ion-list> <ion-list-header> <ion-label> Multiple Selection </ion-label> </ion-list-header> <ion-item> <ion-label>Toppings</ion-label> <ion-select multiple="true" cancelText="Nah" okText="Okay!"> <ion-select-option value="bacon">Bacon</ion-select-option> <ion-select-option value="olives">Black Olives</ion-select-option> <ion-select-option value="xcheese">Extra Cheese</ion-select-option> <ion-select-option value="peppers">Green Peppers</ion-select-option> <ion-select-option value="mushrooms">Mushrooms</ion-select-option> <ion-select-option value="onions">Onions</ion-select-option> <ion-select-option value="pepperoni">Pepperoni</ion-select-option> <ion-select-option value="pineapple">Pineapple</ion-select-option> <ion-select-option value="sausage">Sausage</ion-select-option> <ion-select-option value="Spinach">Spinach</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Pets</ion-label> <ion-select multiple="true" [value]="['bird', 'dog']"> <ion-select-option value="bird">Bird</ion-select-option> <ion-select-option value="cat">Cat</ion-select-option> <ion-select-option value="dog">Dog</ion-select-option> <ion-select-option value="honeybadger">Honey Badger</ion-select-option> </ion-select> </ion-item> </ion-list> ``` ### Objects as Values ```html <ion-list> <ion-list-header> <ion-label> Objects as Values (compareWith) </ion-label> </ion-list-header> <ion-item> <ion-label>Users</ion-label> <ion-select [compareWith]="compareWith"> <ion-select-option *ngFor="let user of users" [value]="user">{{user.first + ' ' + user.last}}</ion-select-option> </ion-select> </ion-item> </ion-list> ``` ```typescript import { Component } from '@angular/core'; interface User { id: number; first: string; last: string; } @Component({ selector: 'select-example', templateUrl: 'select-example.html', styleUrls: ['./select-example.css'], }) export class SelectExample { users: User[] = [ { id: 1, first: 'Alice', last: 'Smith', }, { id: 2, first: 'Bob', last: 'Davis', }, { id: 3, first: 'Charlie', last: 'Rosenburg', } ]; compareWith(o1: User, o2: User) { return o1 && o2 ? o1.id === o2.id : o1 === o2; } } ``` ### Objects as Values with Multiple Selection ```html <ion-list> <ion-list-header> <ion-label> Objects as Values (compareWith) </ion-label> </ion-list-header> <ion-item> <ion-label>Users</ion-label> <ion-select [compareWith]="compareWith" multiple="true"> <ion-select-option *ngFor="let user of users" [value]="user">{{user.first + ' ' + user.last}}</ion-select-option> </ion-select> </ion-item> </ion-list> ``` ```typescript import { Component } from '@angular/core'; interface User { id: number; first: string; last: string; } @Component({ selector: 'select-example', templateUrl: 'select-example.html', styleUrls: ['./select-example.css'], }) export class SelectExample { users: User[] = [ { id: 1, first: 'Alice', last: 'Smith', }, { id: 2, first: 'Bob', last: 'Davis', }, { id: 3, first: 'Charlie', last: 'Rosenburg', } ]; compareWith(o1: User, o2: User | User[]) { if (!o1 || !o2) { return o1 === o2; } if (Array.isArray(o2)) { return o2.some((u: User) => u.id === o1.id); } return o1.id === o2.id; } } ``` ### Interface Options ```html <ion-list> <ion-list-header> <ion-label> Interface Options </ion-label> </ion-list-header> <ion-item> <ion-label>Alert</ion-label> <ion-select [interfaceOptions]="customAlertOptions" interface="alert" multiple="true" placeholder="Select One"> <ion-select-option value="bacon">Bacon</ion-select-option> <ion-select-option value="olives">Black Olives</ion-select-option> <ion-select-option value="xcheese">Extra Cheese</ion-select-option> <ion-select-option value="peppers">Green Peppers</ion-select-option> <ion-select-option value="mushrooms">Mushrooms</ion-select-option> <ion-select-option value="onions">Onions</ion-select-option> <ion-select-option value="pepperoni">Pepperoni</ion-select-option> <ion-select-option value="pineapple">Pineapple</ion-select-option> <ion-select-option value="sausage">Sausage</ion-select-option> <ion-select-option value="Spinach">Spinach</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Popover</ion-label> <ion-select [interfaceOptions]="customPopoverOptions" interface="popover" placeholder="Select One"> <ion-select-option value="brown">Brown</ion-select-option> <ion-select-option value="blonde">Blonde</ion-select-option> <ion-select-option value="black">Black</ion-select-option> <ion-select-option value="red">Red</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Action Sheet</ion-label> <ion-select [interfaceOptions]="customActionSheetOptions" interface="action-sheet" placeholder="Select One"> <ion-select-option value="red">Red</ion-select-option> <ion-select-option value="purple">Purple</ion-select-option> <ion-select-option value="yellow">Yellow</ion-select-option> <ion-select-option value="orange">Orange</ion-select-option> <ion-select-option value="green">Green</ion-select-option> </ion-select> </ion-item> </ion-list> ``` ```typescript import { Component } from '@angular/core'; @Component({ selector: 'select-example', templateUrl: 'select-example.html', styleUrls: ['./select-example.css'], }) export class SelectExample { customAlertOptions: any = { header: 'Pizza Toppings', subHeader: 'Select your toppings', message: '$1.00 per topping', translucent: true }; customPopoverOptions: any = { header: 'Hair Color', subHeader: 'Select your hair color', message: 'Only select your dominant hair color' }; customActionSheetOptions: any = { header: 'Colors', subHeader: 'Select your favorite color' }; } ``` ### Javascript ### Single Selection ```html <ion-list> <ion-list-header> <ion-label> Single Selection </ion-label> </ion-list-header> <ion-item> <ion-label>Gender</ion-label> <ion-select placeholder="Select One"> <ion-select-option value="f">Female</ion-select-option> <ion-select-option value="m">Male</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Hair Color</ion-label> <ion-select value="brown" ok-text="Okay" cancel-text="Dismiss"> <ion-select-option value="brown">Brown</ion-select-option> <ion-select-option value="blonde">Blonde</ion-select-option> <ion-select-option value="black">Black</ion-select-option> <ion-select-option value="red">Red</ion-select-option> </ion-select> </ion-item> </ion-list> ``` ### Multiple Selection ```html <ion-list> <ion-list-header> <ion-label> Multiple Selection </ion-label> </ion-list-header> <ion-item> <ion-label>Toppings</ion-label> <ion-select multiple="true" cancel-text="Nah" ok-text="Okay!"> <ion-select-option value="bacon">Bacon</ion-select-option> <ion-select-option value="olives">Black Olives</ion-select-option> <ion-select-option value="xcheese">Extra Cheese</ion-select-option> <ion-select-option value="peppers">Green Peppers</ion-select-option> <ion-select-option value="mushrooms">Mushrooms</ion-select-option> <ion-select-option value="onions">Onions</ion-select-option> <ion-select-option value="pepperoni">Pepperoni</ion-select-option> <ion-select-option value="pineapple">Pineapple</ion-select-option> <ion-select-option value="sausage">Sausage</ion-select-option> <ion-select-option value="Spinach">Spinach</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Pets</ion-label> <ion-select id="multiple" multiple="true"> <ion-select-option value="bird">Bird</ion-select-option> <ion-select-option value="cat">Cat</ion-select-option> <ion-select-option value="dog">Dog</ion-select-option> <ion-select-option value="honeybadger">Honey Badger</ion-select-option> </ion-select> </ion-item> </ion-list> ``` ```javascript const select = document.querySelector('multiple'); select.value = ['bird', 'dog']; ``` ### Objects as Values ```html <ion-list> <ion-list-header> <ion-label> Objects as Values (compareWith) </ion-label> </ion-list-header> <ion-item> <ion-label>Users</ion-label> <ion-select id="objectSelectCompareWith"></ion-select> </ion-item> </ion-list> ``` ```javascript let objectOptions = [ { id: 1, first: 'Alice', last: 'Smith', }, { id: 2, first: 'Bob', last: 'Davis', }, { id: 3, first: 'Charlie', last: 'Rosenburg', } ]; let compareWithFn = (o1, o2) => { return o1 && o2 ? o1.id === o2.id : o1 === o2; }; let objectSelectElement = document.getElementById('objectSelectCompareWith'); objectSelectElement.compareWith = compareWithFn; objectOptions.forEach((option, i) => { let selectOption = document.createElement('ion-select-option'); selectOption.value = option; selectOption.textContent = option.first + ' ' + option.last; objectSelectElement.appendChild(selectOption) }); objectSelectElement.value = objectOptions[0]; } ``` ### Interface Options ```html <ion-list> <ion-list-header> <ion-label> Interface Options </ion-label> </ion-list-header> <ion-item> <ion-label>Alert</ion-label> <ion-select id="customAlertSelect" interface="alert" multiple="true" placeholder="Select One"> <ion-select-option value="bacon">Bacon</ion-select-option> <ion-select-option value="olives">Black Olives</ion-select-option> <ion-select-option value="xcheese">Extra Cheese</ion-select-option> <ion-select-option value="peppers">Green Peppers</ion-select-option> <ion-select-option value="mushrooms">Mushrooms</ion-select-option> <ion-select-option value="onions">Onions</ion-select-option> <ion-select-option value="pepperoni">Pepperoni</ion-select-option> <ion-select-option value="pineapple">Pineapple</ion-select-option> <ion-select-option value="sausage">Sausage</ion-select-option> <ion-select-option value="Spinach">Spinach</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Popover</ion-label> <ion-select id="customPopoverSelect" interface="popover" placeholder="Select One"> <ion-select-option value="brown">Brown</ion-select-option> <ion-select-option value="blonde">Blonde</ion-select-option> <ion-select-option value="black">Black</ion-select-option> <ion-select-option value="red">Red</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Action Sheet</ion-label> <ion-select id="customActionSheetSelect" interface="action-sheet" placeholder="Select One"> <ion-select-option value="red">Red</ion-select-option> <ion-select-option value="purple">Purple</ion-select-option> <ion-select-option value="yellow">Yellow</ion-select-option> <ion-select-option value="orange">Orange</ion-select-option> <ion-select-option value="green">Green</ion-select-option> </ion-select> </ion-item> </ion-list> ``` ```javascript var customAlertSelect = document.getElementById('customAlertSelect'); var customAlertOptions = { header: 'Pizza Toppings', subHeader: 'Select your toppings', message: '$1.00 per topping', translucent: true }; customAlertSelect.interfaceOptions = customAlertOptions; var customPopoverSelect = document.getElementById('customPopoverSelect'); var customPopoverOptions = { header: 'Hair Color', subHeader: 'Select your hair color', message: 'Only select your dominant hair color' }; customPopoverSelect.interfaceOptions = customPopoverOptions; var customActionSheetSelect = document.getElementById('customActionSheetSelect'); var customActionSheetOptions = { header: 'Colors', subHeader: 'Select your favorite color' }; customActionSheetSelect.interfaceOptions = customActionSheetOptions; ``` ### React ### Single Selection ```tsx import React, { useState } from 'react'; import { IonContent, IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption, IonPage, IonItemDivider } from '@ionic/react'; export const SingleSelection: React.FC = () => { const [gender, setGender] = useState<string>(); const [hairColor, setHairColor] = useState<string>('brown'); return ( <IonPage> <IonContent> <IonList> <IonListHeader> <IonLabel> Single Selection </IonLabel> </IonListHeader> <IonItem> <IonLabel>Gender</IonLabel> <IonSelect value={gender} placeholder="Select One" onIonChange={e => setGender(e.detail.value)}> <IonSelectOption value="female">Female</IonSelectOption> <IonSelectOption value="male">Male</IonSelectOption> </IonSelect> </IonItem> <IonItem> <IonLabel>Hair Color</IonLabel> <IonSelect value={hairColor} okText="Okay" cancelText="Dismiss" onIonChange={e => setHairColor(e.detail.value)}> <IonSelectOption value="brown">Brown</IonSelectOption> <IonSelectOption value="blonde">Blonde</IonSelectOption> <IonSelectOption value="black">Black</IonSelectOption> <IonSelectOption value="red">Red</IonSelectOption> </IonSelect> </IonItem> <IonItemDivider>Your Selections</IonItemDivider> <IonItem>Gender: {gender ?? '(none selected)'}</IonItem> <IonItem>Hair Color: {hairColor}</IonItem> </IonList> </IonContent> </IonPage> ); }; ``` ### Multiple Selection ```tsx import React, { useState } from 'react'; import { IonContent, IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption, IonPage, IonItemDivider } from '@ionic/react'; export const MultipleSelection: React.FC = () => { const [toppings, setToppings] = useState<string[]>([]); const [pets, setPets] = useState<string[]>(['bird', 'dog']); return ( <IonPage> <IonContent> <IonList> <IonListHeader> <IonLabel> Multiple Selection </IonLabel> </IonListHeader> <IonItem> <IonLabel>Toppings</IonLabel> <IonSelect value={toppings} multiple={true} cancelText="Nah" okText="Okay!" onIonChange={e => setToppings(e.detail.value)}> <IonSelectOption value="bacon">Bacon</IonSelectOption> <IonSelectOption value="olives">Black Olives</IonSelectOption> <IonSelectOption value="xcheese">Extra Cheese</IonSelectOption> <IonSelectOption value="peppers">Green Peppers</IonSelectOption> <IonSelectOption value="mushrooms">Mushrooms</IonSelectOption> <IonSelectOption value="onions">Onions</IonSelectOption> <IonSelectOption value="pepperoni">Pepperoni</IonSelectOption> <IonSelectOption value="pineapple">Pineapple</IonSelectOption> <IonSelectOption value="sausage">Sausage</IonSelectOption> <IonSelectOption value="Spinach">Spinach</IonSelectOption> </IonSelect> </IonItem> <IonItem> <IonLabel>Pets</IonLabel> <IonSelect multiple={true} value={pets} onIonChange={e => setPets(e.detail.value)}> <IonSelectOption value="bird">Bird</IonSelectOption> <IonSelectOption value="cat">Cat</IonSelectOption> <IonSelectOption value="dog">Dog</IonSelectOption> <IonSelectOption value="honeybadger">Honey Badger</IonSelectOption> </IonSelect> </IonItem> <IonItemDivider>Your Selections</IonItemDivider> <IonItem>Toppings: {toppings.length ? toppings.reduce((curr, prev) => prev + ', ' + curr, '') : '(none selected)'}</IonItem> <IonItem>Pets: {pets.length ? pets.reduce((curr, prev) => prev + ', ' + curr, '') : '(none selected)'}</IonItem> </IonList> </IonContent> </IonPage> ); }; ``` ### Objects as Values ```tsx import React, { useState } from 'react'; import { IonContent, IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption, IonPage, IonItemDivider } from '@ionic/react'; const users = [ { id: 1, first: 'Alice', last: 'Smith' }, { id: 2, first: 'Bob', last: 'Davis' }, { id: 3, first: 'Charlie', last: 'Rosenburg', } ]; type User = typeof users[number]; const compareWith = (o1: User, o2: User) => { return o1 && o2 ? o1.id === o2.id : o1 === o2; }; export const ObjectSelection: React.FC = () => { const [selectedUsers, setSelectedUsers] = useState<User[]>([]); return ( <IonPage> <IonContent> <IonList> <IonListHeader> <IonLabel> Objects as Values (compareWith) </IonLabel> </IonListHeader> <IonItem> <IonLabel>Users</IonLabel> <IonSelect compareWith={compareWith} value={selectedUsers} multiple onIonChange={e => setSelectedUsers(e.detail.value)}> {users.map(user => ( <IonSelectOption key={user.id} value={user}> {user.first} {user.last} </IonSelectOption> ))} </IonSelect> </IonItem> <IonItemDivider>Selected Users</IonItemDivider> {selectedUsers.length ? selectedUsers.map(user => <IonItem key={user.id}>{user.first} {user.last}</IonItem>) : <IonItem>(none selected)</IonItem> } </IonList> </IonContent> </IonPage> ); }; ``` ### Interface Options ```tsx import React, { useState } from 'react'; import { IonContent, IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption, IonPage, IonItemDivider } from '@ionic/react'; const customAlertOptions = { header: 'Pizza Toppings', subHeader: 'Select your toppings', message: '$1.00 per topping', translucent: true }; const customPopoverOptions = { header: 'Hair Color', subHeader: 'Select your hair color', message: 'Only select your dominant hair color' }; const customActionSheetOptions = { header: 'Colors', subHeader: 'Select your favorite color' }; export const InterfaceOptionsSelection: React.FC = () => { const [toppings, setToppings] = useState<string[]>([]); const [hairColor, setHairColor] = useState<string>('brown'); const [color, setColor] = useState<string>(); return ( <IonPage> <IonContent> <IonList> <IonListHeader> <IonLabel> Interface Options </IonLabel> </IonListHeader> <IonItem> <IonLabel>Alert</IonLabel> <IonSelect interfaceOptions={customAlertOptions} interface="alert" multiple={true} placeholder="Select One" onIonChange={e => setToppings(e.detail.value)} value={toppings} > <IonSelectOption value="bacon">Bacon</IonSelectOption> <IonSelectOption value="olives">Black Olives</IonSelectOption> <IonSelectOption value="xcheese">Extra Cheese</IonSelectOption> <IonSelectOption value="peppers">Green Peppers</IonSelectOption> <IonSelectOption value="mushrooms">Mushrooms</IonSelectOption> <IonSelectOption value="onions">Onions</IonSelectOption> <IonSelectOption value="pepperoni">Pepperoni</IonSelectOption> <IonSelectOption value="pineapple">Pineapple</IonSelectOption> <IonSelectOption value="sausage">Sausage</IonSelectOption> <IonSelectOption value="Spinach">Spinach</IonSelectOption> </IonSelect> </IonItem> <IonItem> <IonLabel>Popover</IonLabel> <IonSelect interfaceOptions={customPopoverOptions} interface="popover" placeholder="Select One" onIonChange={e => setHairColor(e.detail.value)} value={hairColor}> <IonSelectOption value="brown">Brown</IonSelectOption> <IonSelectOption value="blonde">Blonde</IonSelectOption> <IonSelectOption value="black">Black</IonSelectOption> <IonSelectOption value="red">Red</IonSelectOption> </IonSelect> </IonItem> <IonItem> <IonLabel>Action Sheet</IonLabel> <IonSelect interfaceOptions={customActionSheetOptions} interface="action-sheet" placeholder="Select One" onIonChange={e => setColor(e.detail.value)} value={color} > <IonSelectOption value="red">Red</IonSelectOption> <IonSelectOption value="purple">Purple</IonSelectOption> <IonSelectOption value="yellow">Yellow</IonSelectOption> <IonSelectOption value="orange">Orange</IonSelectOption> <IonSelectOption value="green">Green</IonSelectOption> </IonSelect> </IonItem> <IonItemDivider>Your Selections</IonItemDivider> <IonItem>Toppings: {toppings.length ? toppings.reduce((curr, prev) => prev + ', ' + curr, '') : '(none selected)'}</IonItem> <IonItem>Hair Color: {hairColor}</IonItem> <IonItem>Color: {color ?? '(none selected)'}</IonItem> </IonList> </IonContent> </IonPage> ); }; ``` ### Stencil ### Single Selection ```tsx import { Component, h } from '@stencil/core'; @Component({ tag: 'select-example', styleUrl: 'select-example.css' }) export class SelectExample { render() { return [ <ion-list> <ion-list-header> <ion-label> Single Selection </ion-label> </ion-list-header> <ion-item> <ion-label>Gender</ion-label> <ion-select placeholder="Select One"> <ion-select-option value="f">Female</ion-select-option> <ion-select-option value="m">Male</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Hair Color</ion-label> <ion-select value="brown" okText="Okay" cancelText="Dismiss"> <ion-select-option value="brown">Brown</ion-select-option> <ion-select-option value="blonde">Blonde</ion-select-option> <ion-select-option value="black">Black</ion-select-option> <ion-select-option value="red">Red</ion-select-option> </ion-select> </ion-item> </ion-list> ]; } } ``` ### Multiple Selection ```tsx import { Component, h } from '@stencil/core'; @Component({ tag: 'select-example', styleUrl: 'select-example.css' }) export class SelectExample { render() { return [ <ion-list> <ion-list-header> <ion-label> Multiple Selection </ion-label> </ion-list-header> <ion-item> <ion-label>Toppings</ion-label> <ion-select multiple={true} cancelText="Nah" okText="Okay!"> <ion-select-option value="bacon">Bacon</ion-select-option> <ion-select-option value="olives">Black Olives</ion-select-option> <ion-select-option value="xcheese">Extra Cheese</ion-select-option> <ion-select-option value="peppers">Green Peppers</ion-select-option> <ion-select-option value="mushrooms">Mushrooms</ion-select-option> <ion-select-option value="onions">Onions</ion-select-option> <ion-select-option value="pepperoni">Pepperoni</ion-select-option> <ion-select-option value="pineapple">Pineapple</ion-select-option> <ion-select-option value="sausage">Sausage</ion-select-option> <ion-select-option value="Spinach">Spinach</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Pets</ion-label> <ion-select multiple={true} value={['bird', 'dog']}> <ion-select-option value="bird">Bird</ion-select-option> <ion-select-option value="cat">Cat</ion-select-option> <ion-select-option value="dog">Dog</ion-select-option> <ion-select-option value="honeybadger">Honey Badger</ion-select-option> </ion-select> </ion-item> </ion-list> ]; } } ``` ### Objects as Values ```tsx import { Component, h } from '@stencil/core'; @Component({ tag: 'select-example', styleUrl: 'select-example.css' }) export class SelectExample { private users: any[] = [ { id: 1, first: 'Alice', last: 'Smith', }, { id: 2, first: 'Bob', last: 'Davis', }, { id: 3, first: 'Charlie', last: 'Rosenburg', } ]; compareWith = (o1, o2) => { return o1 && o2 ? o1.id === o2.id : o1 === o2; }; render() { return [ <ion-list> <ion-list-header> <ion-label> Objects as Values (compareWith) </ion-label> </ion-list-header> <ion-item> <ion-label>Users</ion-label> <ion-select compareWith={this.compareWith}> {this.users.map(user => <ion-select-option value={user}> {user.first + ' ' + user.last} </ion-select-option> )} </ion-select> </ion-item> </ion-list> ]; } } ``` ### Interface Options ```tsx import { Component, h } from '@stencil/core'; @Component({ tag: 'select-example', styleUrl: 'select-example.css' }) export class SelectExample { private customAlertOptions: any = { header: 'Pizza Toppings', subHeader: 'Select your toppings', message: '$1.00 per topping', translucent: true }; private customPopoverOptions: any = { header: 'Hair Color', subHeader: 'Select your hair color', message: 'Only select your dominant hair color' }; private customActionSheetOptions: any = { header: 'Colors', subHeader: 'Select your favorite color' }; render() { return [ <ion-list> <ion-list-header> <ion-label> Interface Options </ion-label> </ion-list-header> <ion-item> <ion-label>Alert</ion-label> <ion-select interfaceOptions={this.customAlertOptions} interface="alert" multiple={true} placeholder="Select One"> <ion-select-option value="bacon">Bacon</ion-select-option> <ion-select-option value="olives">Black Olives</ion-select-option> <ion-select-option value="xcheese">Extra Cheese</ion-select-option> <ion-select-option value="peppers">Green Peppers</ion-select-option> <ion-select-option value="mushrooms">Mushrooms</ion-select-option> <ion-select-option value="onions">Onions</ion-select-option> <ion-select-option value="pepperoni">Pepperoni</ion-select-option> <ion-select-option value="pineapple">Pineapple</ion-select-option> <ion-select-option value="sausage">Sausage</ion-select-option> <ion-select-option value="Spinach">Spinach</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Popover</ion-label> <ion-select interfaceOptions={this.customPopoverOptions} interface="popover" placeholder="Select One"> <ion-select-option value="brown">Brown</ion-select-option> <ion-select-option value="blonde">Blonde</ion-select-option> <ion-select-option value="black">Black</ion-select-option> <ion-select-option value="red">Red</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Action Sheet</ion-label> <ion-select interfaceOptions={this.customActionSheetOptions} interface="action-sheet" placeholder="Select One"> <ion-select-option value="red">Red</ion-select-option> <ion-select-option value="purple">Purple</ion-select-option> <ion-select-option value="yellow">Yellow</ion-select-option> <ion-select-option value="orange">Orange</ion-select-option> <ion-select-option value="green">Green</ion-select-option> </ion-select> </ion-item> </ion-list> ]; } } ``` ### Vue ### Single Selection ```html <template> <ion-list> <ion-list-header> <ion-label> Single Selection </ion-label> </ion-list-header> <ion-item> <ion-label>Gender</ion-label> <ion-select placeholder="Select One"> <ion-select-option value="f">Female</ion-select-option> <ion-select-option value="m">Male</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Hair Color</ion-label> <ion-select value="brown" ok-text="Okay" cancel-text="Dismiss"> <ion-select-option value="brown">Brown</ion-select-option> <ion-select-option value="blonde">Blonde</ion-select-option> <ion-select-option value="black">Black</ion-select-option> <ion-select-option value="red">Red</ion-select-option> </ion-select> </ion-item> </ion-list> </template> <script> import { IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption } from '@ionic/vue'; import { defineComponent } from 'vue'; export default defineComponent({ components: { IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption } }); </script> ``` ### Multiple Selection ```html <template> <ion-list> <ion-list-header> <ion-label> Multiple Selection </ion-label> </ion-list-header> <ion-item> <ion-label>Toppings</ion-label> <ion-select multiple="true" cancel-text="Nah" ok-text="Okay!"> <ion-select-option value="bacon">Bacon</ion-select-option> <ion-select-option value="olives">Black Olives</ion-select-option> <ion-select-option value="xcheese">Extra Cheese</ion-select-option> <ion-select-option value="peppers">Green Peppers</ion-select-option> <ion-select-option value="mushrooms">Mushrooms</ion-select-option> <ion-select-option value="onions">Onions</ion-select-option> <ion-select-option value="pepperoni">Pepperoni</ion-select-option> <ion-select-option value="pineapple">Pineapple</ion-select-option> <ion-select-option value="sausage">Sausage</ion-select-option> <ion-select-option value="Spinach">Spinach</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Pets</ion-label> <ion-select multiple="true" :value=['bird', 'dog']> <ion-select-option value="bird">Bird</ion-select-option> <ion-select-option value="cat">Cat</ion-select-option> <ion-select-option value="dog">Dog</ion-select-option> <ion-select-option value="honeybadger">Honey Badger</ion-select-option> </ion-select> </ion-item> </ion-list> </template> <script> import { IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption } from '@ionic/vue'; import { defineComponent } from 'vue'; export default defineComponent({ components: { IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption } }); </script> ``` ### Interface Options ```html <template> <ion-list> <ion-list-header> <ion-label> Interface Options </ion-label> </ion-list-header> <ion-item> <ion-label>Alert</ion-label> <ion-select :interface-options="customAlertOptions" interface="alert" multiple="true" placeholder="Select One"> <ion-select-option value="bacon">Bacon</ion-select-option> <ion-select-option value="olives">Black Olives</ion-select-option> <ion-select-option value="xcheese">Extra Cheese</ion-select-option> <ion-select-option value="peppers">Green Peppers</ion-select-option> <ion-select-option value="mushrooms">Mushrooms</ion-select-option> <ion-select-option value="onions">Onions</ion-select-option> <ion-select-option value="pepperoni">Pepperoni</ion-select-option> <ion-select-option value="pineapple">Pineapple</ion-select-option> <ion-select-option value="sausage">Sausage</ion-select-option> <ion-select-option value="Spinach">Spinach</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Popover</ion-label> <ion-select :interface-options="customPopoverOptions" interface="popover" placeholder="Select One"> <ion-select-option value="brown">Brown</ion-select-option> <ion-select-option value="blonde">Blonde</ion-select-option> <ion-select-option value="black">Black</ion-select-option> <ion-select-option value="red">Red</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Action Sheet</ion-label> <ion-select :interface-options="customActionSheetOptions" interface="action-sheet" placeholder="Select One"> <ion-select-option value="red">Red</ion-select-option> <ion-select-option value="purple">Purple</ion-select-option> <ion-select-option value="yellow">Yellow</ion-select-option> <ion-select-option value="orange">Orange</ion-select-option> <ion-select-option value="green">Green</ion-select-option> </ion-select> </ion-item> </ion-list> </template> <script> import { IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption } from '@ionic/vue'; import { defineComponent } from 'vue'; export default defineComponent({ components: { IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption }, setup() { const customAlertOptions: any = { header: 'Pizza Toppings', subHeader: 'Select your toppings', message: '$1.00 per topping', translucent: true }; const customPopoverOptions: any = { header: 'Hair Color', subHeader: 'Select your hair color', message: 'Only select your dominant hair color' }; const customActionSheetOptions: any = { header: 'Colors', subHeader: 'Select your favorite color' }; return { customAlertOptions, customPopoverOptions, customActionSheetOptions } } }); </script> ``` ## Properties | Property | Attribute | Description | Type | Default | | ------------------ | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | -------------- | | `cancelText` | `cancel-text` | The text to display on the cancel button. | `string` | `'Cancel'` | | `compareWith` | `compare-with` | A property name or function used to compare object values | `((currentValue: any, compareValue: any) => boolean) \| null \| string \| undefined` | `undefined` | | `disabled` | `disabled` | If `true`, the user cannot interact with the select. | `boolean` | `false` | | `interface` | `interface` | The interface the select should use: `action-sheet`, `popover` or `alert`. | `"action-sheet" \| "alert" \| "popover"` | `'alert'` | | `interfaceOptions` | `interface-options` | Any additional options that the `alert`, `action-sheet` or `popover` interface can take. See the [ion-alert docs](../alert), the [ion-action-sheet docs](../action-sheet) and the [ion-popover docs](../popover) for the create options for each interface. Note: `interfaceOptions` will not override `inputs` or `buttons` with the `alert` interface. | `any` | `{}` | | `mode` | `mode` | The mode determines which platform styles to use. | `"ios" \| "md"` | `undefined` | | `multiple` | `multiple` | If `true`, the select can accept multiple values. | `boolean` | `false` | | `name` | `name` | The name of the control, which is submitted with the form data. | `string` | `this.inputId` | | `okText` | `ok-text` | The text to display on the ok button. | `string` | `'OK'` | | `placeholder` | `placeholder` | The text to display when the select is empty. | `string \| undefined` | `undefined` | | `selectedText` | `selected-text` | The text to display instead of the selected option's value. | `null \| string \| undefined` | `undefined` | | `value` | `value` | the value of the select. | `any` | `undefined` | ## Events | Event | Description | Type | | ----------- | ---------------------------------------- | ------------------------------------------- | | `ionBlur` | Emitted when the select loses focus. | `CustomEvent<void>` | | `ionCancel` | Emitted when the selection is cancelled. | `CustomEvent<void>` | | `ionChange` | Emitted when the value has changed. | `CustomEvent<SelectChangeEventDetail<any>>` | | `ionFocus` | Emitted when the select has focus. | `CustomEvent<void>` | ## Methods ### `open(event?: UIEvent | undefined) => Promise<any>` Open the select overlay. The overlay is either an alert, action sheet, or popover, depending on the `interface` property on the `ion-select`. #### Returns Type: `Promise<any>` ## Shadow Parts | Part | Description | | --------------- | -------------------------------------------------------- | | `"icon"` | The select icon container. | | `"placeholder"` | The text displayed in the select when there is no value. | | `"text"` | The displayed value of the select. | ## CSS Custom Properties | Name | Description | | ----------------------- | --------------------------------------------------------------------------------------------------------- | | `--padding-bottom` | Bottom padding of the select | | `--padding-end` | Right padding if direction is left-to-right, and left padding if direction is right-to-left of the select | | `--padding-start` | Left padding if direction is left-to-right, and right padding if direction is right-to-left of the select | | `--padding-top` | Top padding of the select | | `--placeholder-color` | Color of the select placeholder text | | `--placeholder-opacity` | Opacity of the select placeholder text | ## Dependencies ### Depends on - ion-select-popover ### Graph ```mermaid graph TD; ion-select --> ion-select-popover ion-select-popover --> ion-item ion-select-popover --> ion-checkbox ion-select-popover --> ion-label ion-select-popover --> ion-radio-group ion-select-popover --> ion-radio ion-select-popover --> ion-list ion-select-popover --> ion-list-header ion-item --> ion-icon ion-item --> ion-ripple-effect ion-item --> ion-note style ion-select fill:#f9f,stroke:#333,stroke-width:4px ``` ---------------------------------------------- *Built with [StencilJS](https://stenciljs.com/)*
core/src/components/select/readme.md
1
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.00395206268876791, 0.00027199462056159973, 0.00016548967687413096, 0.00023016950581222773, 0.00032611918868497014 ]
{ "id": 0, "code_window": [ "\n", "\n", "## Dependencies\n", "\n", "### Depends on\n", "\n", "- [ion-backdrop](../backdrop)\n", "- ion-icon\n", "- [ion-ripple-effect](../ripple-effect)\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "### Used by\n", "\n", " - [ion-select](../select)\n", "\n" ], "file_path": "core/src/components/action-sheet/readme.md", "type": "add", "edit_start_line_idx": 663 }
const DocsJson = require('@ionic/core/dist/docs.json'); const fs = require('fs'); const { paramCase } = require('change-case'); const generateTags = () => { const tagsObject = {}; DocsJson.components.forEach(component => { tagsObject[component.tag] = { description: component.docs, attributes: component.props.map(prop => paramCase(prop.name)) } }); fs.writeFileSync('./dist/vetur/tags.json', JSON.stringify(tagsObject, null, 2)); } const generateAttributes = () => { const attributesObject = {}; DocsJson.components.forEach(component => { component.props.forEach(prop => { attributesObject[`${component.tag}/${paramCase(prop.name)}`] = { type: prop.type, description: prop.docs, options: prop.values.filter(option => option.value !== undefined).map(option => option.value) } }); }); fs.writeFileSync('./dist/vetur/attributes.json', JSON.stringify(attributesObject, null, 2)); } const main = async () => { if (!fs.existsSync('./dist/vetur')) { fs.mkdirSync('./dist/vetur'); } generateTags(); generateAttributes(); } main();
packages/vue/scripts/build-vetur.js
0
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.00017767651297617704, 0.00017275156278628856, 0.00016888334357645363, 0.00017273685079999268, 0.000003447944209256093 ]
{ "id": 0, "code_window": [ "\n", "\n", "## Dependencies\n", "\n", "### Depends on\n", "\n", "- [ion-backdrop](../backdrop)\n", "- ion-icon\n", "- [ion-ripple-effect](../ripple-effect)\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "### Used by\n", "\n", " - [ion-select](../select)\n", "\n" ], "file_path": "core/src/components/action-sheet/readme.md", "type": "add", "edit_start_line_idx": 663 }
import { newE2EPage } from '@stencil/core/testing'; test('item: dividers', async () => { const page = await newE2EPage({ url: '/src/components/item/test/dividers?ionic:_testing=true' }); const compare = await page.compareScreenshot(); expect(compare).toMatchScreenshot(); });
core/src/components/item/test/dividers/e2e.ts
0
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.00017292273696511984, 0.00017160791321657598, 0.00017029308946803212, 0.00017160791321657598, 0.0000013148237485438585 ]
{ "id": 0, "code_window": [ "\n", "\n", "## Dependencies\n", "\n", "### Depends on\n", "\n", "- [ion-backdrop](../backdrop)\n", "- ion-icon\n", "- [ion-ripple-effect](../ripple-effect)\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "### Used by\n", "\n", " - [ion-select](../select)\n", "\n" ], "file_path": "core/src/components/action-sheet/readme.md", "type": "add", "edit_start_line_idx": 663 }
const PADDING_TIMER_KEY = '$ionPaddingTimer'; export const enableScrollPadding = (keyboardHeight: number) => { const doc = document; const onFocusin = (ev: any) => { setScrollPadding(ev.target, keyboardHeight); }; const onFocusout = (ev: any) => { setScrollPadding(ev.target, 0); }; doc.addEventListener('focusin', onFocusin); doc.addEventListener('focusout', onFocusout); return () => { doc.removeEventListener('focusin', onFocusin); doc.removeEventListener('focusout', onFocusout); }; }; const setScrollPadding = (input: HTMLElement, keyboardHeight: number) => { if (input.tagName !== 'INPUT') { return; } if (input.parentElement && input.parentElement.tagName === 'ION-INPUT') { return; } if ( input.parentElement && input.parentElement.parentElement && input.parentElement.parentElement.tagName === 'ION-SEARCHBAR' ) { return; } const el = input.closest('ion-content'); if (el === null) { return; } const timer = (el as any)[PADDING_TIMER_KEY]; if (timer) { clearTimeout(timer); } if (keyboardHeight > 0) { el.style.setProperty('--keyboard-offset', `${keyboardHeight}px`); } else { (el as any)[PADDING_TIMER_KEY] = setTimeout(() => { el.style.setProperty('--keyboard-offset', '0px'); }, 120); } };
core/src/utils/input-shims/hacks/scroll-padding.ts
0
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.00030707690166309476, 0.00021486244804691523, 0.00016814102127682418, 0.00019400796736590564, 0.000051397983042988926 ]
{ "id": 1, "code_window": [ " ion-action-sheet --> ion-backdrop\n", " ion-action-sheet --> ion-icon\n", " ion-action-sheet --> ion-ripple-effect\n", " style ion-action-sheet fill:#f9f,stroke:#333,stroke-width:4px\n", "```\n", "\n", "----------------------------------------------\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " ion-select --> ion-action-sheet\n" ], "file_path": "core/src/components/action-sheet/readme.md", "type": "add", "edit_start_line_idx": 675 }
# ion-popover A Popover is a dialog that appears on top of the current page. It can be used for anything, but generally it is used for overflow actions that don't fit in the navigation bar. There are two ways to use `ion-popover`: inline or via the `popoverController`. Each method comes with different considerations, so be sure to use the approach that best fits your use case. ## Inline Popovers `ion-popover` can be used by writing the component directly in your template. This reduces the number of handlers you need to wire up in order to present the popover. See [Usage](#usage) for an example of how to write a popover inline. When using `ion-popover` with Angular, React, or Vue, the component you pass in will be destroyed when the popover is dismissed. As this functionality is provided by the JavaScript framework, using `ion-popover` without a JavaScript framework will not destroy the component you passed in. If this is a needed functionality, we recommend using the `popoverController` instead. ### Angular Since the component you passed in needs to be created when the popover is presented and destroyed when the popover is dismissed, we are unable to project the content using `<ng-content>` internally. Instead, we use `<ng-container>` which expects an `<ng-template>` to be passed in. As a result, when passing in your component you will need to wrap it in an `<ng-template>`: ```html <ion-popover [isOpen]="isPopoverOpen"> <ng-template> <app-popover-content></app-popover-content> </ng-template> </ion-popover> ``` ### When to use Using a popover inline is useful when you do not want to explicitly wire up click events to open the popover. For example, you can use the `trigger` property to designate a button that should present the popover when clicked. You can also use the `trigger-action` property to customize whether the popover should be presented when the trigger is left clicked, right clicked, or hovered over. If you need fine grained control over when the popover is presented and dismissed, we recommend you use the `popoverController`. ## Controller Popovers `ion-popover` can also be presented programmatically by using the `popoverController` imported from Ionic Framework. This allows you to have complete control over when a popover is presented above and beyond the customization that inline popovers give you. See [Usage](#usage) for an example of how to use the `popoverController`. ### When to use We typically recommend that you write your popovers inline as it streamlines the amount of code in your application. You should only use the `popoverController` for complex use cases where writing a popover inline is impractical. When using a controller, your popover is not created ahead of time, so properties such as `trigger` and `trigger-action` are not applicable here. In addition, nested popovers are not compatible with the controller approach because the popover is automatically added to the root of your application when the `create` method is called. ## Styling Popovers are presented at the root of your application so they overlay your entire app. This behavior applies to both inline popovers and popovers presented from a controller. As a result, custom popover styles can not be scoped to a particular component as they will not apply to the popover. Instead, styles must be applied globally. For most developers, placing the custom styles in `global.css` is sufficient. > If you are building an Ionic Angular app, the styles need to be added to a global stylesheet file. Read [Style Placement](#style-placement) in the Angular section below for more information. ## Triggers A trigger for an `ion-popover` is the element that will open a popover when interacted with. The interaction behavior can be customized by setting the `trigger-action` property. Note that `trigger-action="context-menu"` will prevent your system's default context menu from opening. View the [Usage](#usage) section for an example of how to use triggers. > Triggers are not applicable when using the `popoverController` because the `ion-popover` is not created ahead of time. ## Positioning ### Reference When presenting a popover, Ionic Framework needs a reference point to present the popover relative to. With `reference="event"`, the popover will be presented relative to the x-y coordinates of the pointer event that was dispatched on your trigger element. With `reference="trigger"`, the popover will be presented relative to the bounding box of your trigger element. ### Side Regardless of what you choose for your reference point, you can position a popover to the `top`, `right`, `left`, or `bottom` of your reference point by using the `side` property. You can also use the `start` or `end` values if you would like the side to switch based on LTR or RTL modes. ### Alignment The `alignment` property allows you to line up an edge of your popover with a corresponding edge on your trigger element. The exact edge that is used depends on the value of the `side` property. ### Offsets If you need finer grained control over the positioning of your popover you can use the `--offset-x` and `--offset-y` CSS Variables. For example, `--offset-x: 10px` will move your popover content to the right by `10px`. ## Sizing When making dropdown menus, you may want to have the width of the popover match the width of the trigger element. Doing this without knowing the trigger width ahead of time is tricky. You can set the `size` property to `'cover'` and Ionic Framework will ensure that the width of the popover matches the width of your trigger element. If you are using the `popoverController`, you must provide an event via the `event` option and Ionic Framework will use `event.target` as the reference element. ## Nested Popovers When using `ion-popover` inline, you can nested popovers to create nested dropdown menus. When doing this, only the backdrop on the first popover will appear so that the screen does not get progressively darker as you open more popovers. See the [Usage](./#usage) section for an example on how to write a nested popover. You can use the `dismissOnSelect` property to automatically close the popover when the popover content has been clicked. This behavior does not apply when clicking a trigger element for another popover. > Nested popovers cannot be created when using the `popoverController` because the popover is automatically added to the root of your application when the `create` method is called. ## Interfaces Below you will find all of the options available to you when using the `popoverController`. These options should be supplied when calling `popoverController.create()`. ```typescript interface PopoverOptions { component: any; componentProps?: { [key: string]: any }; showBackdrop?: boolean; backdropDismiss?: boolean; translucent?: boolean; cssClass?: string | string[]; event?: Event; animated?: boolean; mode?: 'ios' | 'md'; keyboardClose?: boolean; id?: string; htmlAttributes?: PopoverAttributes; enterAnimation?: AnimationBuilder; leaveAnimation?: AnimationBuilder; size?: PopoverSize; dismissOnSelect?: boolean; reference?: PositionReference; side?: PositionSide; alignment?: PositionAlign; arrow?: boolean; } ``` ### PopoverAttributes ```typescript interface PopoverAttributes extends JSXBase.HTMLAttributes<HTMLElement> {} ``` ## Types Below you will find all of the custom types for `ion-popover`: ```typescript type PopoverSize = 'cover' | 'auto'; type TriggerAction = 'click' | 'hover' | 'context-menu'; type PositionReference = 'trigger' | 'event'; type PositionSide = 'top' | 'right' | 'bottom' | 'left' | 'start' | 'end'; type PositionAlign = 'start' | 'center' | 'end'; ``` ## Accessibility ### Keyboard Navigation `ion-popover` has basic keyboard support for navigating between focusable elements inside of the popover. The following table details what each key does: | Key | Function | | ------------------ | ------------------------------------------------------------ | | `Tab` | Moves focus to the next focusable element. | | `Shift` + `Tab` | Moves focus to the previous focusable element. | | `Esc` | Closes the popover. | | `Space` or `Enter` | Clicks the focusable element. | `ion-popover` has full arrow key support for navigating between `ion-item` elements with the `button` property. The most common use case for this is as a dropdown menu in a desktop-focused application. In addition to the basic keyboard support, the following table details arrow key support for dropdown menus: | Key | Function | | ------------------ | -------------------------------------------------------------- | | `ArrowUp` | Moves focus to the previous focusable element. | | `ArrowDown` | Moves focus to the next focusable element. | | `Home` | Moves focus to the first focusable element. | | `End` | Moves focus to the last focusable element. | | `ArrowLeft` | When used in a child popover, closes the popover and returns focus to the parent popover. | | `Space`, `Enter`, and `ArrowRight` | When focusing a trigger element, opens the associated popover. | <!-- Auto Generated Below --> ## Usage ### Angular ### Inline Popover ```html <!-- Default --> <ion-popover [isOpen]="true"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- No Arrow --> <ion-popover [isOpen]="true" [arrow]="false"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- Use a trigger --> <ion-button id="trigger-button">Click to open popover</ion-button> <ion-popover trigger="trigger-button"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- Hover over trigger to open --> <ion-button id="hover-button">Hover to open popover</ion-button> <ion-popover trigger="hover-button" triggerAction="hover"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- Show popover above trigger --> <ion-button id="side-button">Click to open popover</ion-button> <ion-popover trigger="side-button" side="top"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- Align popover to end of trigger --> <ion-button id="alignment-button">Click to open popover</ion-button> <ion-popover trigger="alignment-button" side="top" alignment="end"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- Make popover the same size as the trigger --> <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" size="cover"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- Make popover show relative to click coordinates rather than trigger --> <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" reference="event"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- Nested Popover --> <ion-button id="nested-button">Click to open popover</ion-button> <ion-popover trigger="nested-button" [dismissOnSelect]="true"> <ng-template> <ion-content> <ion-list> <ion-item [button]="true" [detail]="false"> <ion-label>Option 1</ion-label> </ion-item> <ion-item [button]="true" [detail]="false"> <ion-label>Option 2</ion-label> </ion-item> <ion-item [button]="true" [detail]="true" id="nested-trigger"> <ion-label>Option 3</ion-label> </ion-item> <ion-popover trigger="nested-trigger" [dismissOnSelect]="true" side="end"> <ng-template> <ion-content> <ion-item [button]="true"> <ion-label>Nested Option</ion-label> </ion-item> </ion-content> </ng-template> </ion-popover> </ion-list> </ion-content> </ng-template> </ion-popover> ``` ### Popover Controller ```typescript import { Component } from '@angular/core'; import { PopoverController } from '@ionic/angular'; import { PopoverComponent } from '../../component/popover/popover.component'; @Component({ selector: 'popover-example', templateUrl: 'popover-example.html', styleUrls: ['./popover-example.css'] }) export class PopoverExample { constructor(public popoverController: PopoverController) {} async presentPopover(ev: any) { const popover = await this.popoverController.create({ component: PopoverComponent, cssClass: 'my-custom-class', event: ev, translucent: true }); await popover.present(); const { role } = await popover.onDidDismiss(); console.log('onDidDismiss resolved with role', role); } } ``` ### Style Placement In Angular, the CSS of a specific page is scoped only to elements of that page. Even though the Popover can be presented from within a page, the `ion-popover` element is appended outside of the current page. This means that any custom styles need to go in a global stylesheet file. In an Ionic Angular starter this can be the `src/global.scss` file or you can register a new global style file by [adding to the `styles` build option in `angular.json`](https://angular.io/guide/workspace-config#style-script-config). ### Javascript ### Inline Popover ```html <!-- Default --> <ion-popover is-open="true"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- No Arrow --> <ion-popover is-open="true" arrow="false"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Use a trigger --> <ion-button id="trigger-button">Click to open popover</ion-button> <ion-popover trigger="trigger-button"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Hover over trigger to open --> <ion-button id="hover-button">Hover to open popover</ion-button> <ion-popover trigger="hover-button" trigger-action="hover"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Show popover above trigger --> <ion-button id="side-button">Click to open popover</ion-button> <ion-popover trigger="side-button" side="top"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Align popover to end of trigger --> <ion-button id="alignment-button">Click to open popover</ion-button> <ion-popover trigger="alignment-button" side="top" alignment="end"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Make popover the same size as the trigger --> <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" size="cover"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Make popover show relative to click coordinates rather than trigger --> <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" reference="event"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Nested Popover --> <ion-button id="nested-button">Click to open popover</ion-button> <ion-popover trigger="nested-button" dismiss-on-select="true"> <ion-content> <ion-list> <ion-item button="true" detail="false"> <ion-label>Option 1</ion-label> </ion-item> <ion-item button="true" detail="false"> <ion-label>Option 2</ion-label> </ion-item> <ion-item button="true" detail="true" id="nested-trigger"> <ion-label>Option 3</ion-label> </ion-item> <ion-popover trigger="nested-trigger" dismiss-on-select="true" side="end"> <ion-content> <ion-item button="true"> <ion-label>Nested Option</ion-label> </ion-item> </ion-content> </ion-popover> </ion-list> </ion-content> </ion-popover> ``` ### Using JavaScript ```javascript class PopoverExamplePage extends HTMLElement { constructor() { super(); } connectedCallback() { this.innerHTML = ` <ion-content> <ion-list> <ion-list-header><ion-label>Ionic</ion-label></ion-list-header> <ion-item button><ion-label>Item 0</ion-label></ion-item> <ion-item button><ion-label>Item 1</ion-label></ion-item> <ion-item button><ion-label>Item 2</ion-label></ion-item> <ion-item button><ion-label>Item 3</ion-label></ion-item> </ion-list> </ion-content> `; } } customElements.define('popover-example-page', PopoverExamplePage); async function presentPopover(ev) { const popover = Object.assign(document.createElement('ion-popover'), { component: 'popover-example-page', cssClass: 'my-custom-class', event: ev, translucent: true }); document.body.appendChild(popover); await popover.present(); const { role } = await popover.onDidDismiss(); console.log('onDidDismiss resolved with role', role); } ``` ### React ### Inline Popover ```tsx import React, { useState } from 'react'; import { IonPopover, IonContent, IonItem, IonLabel, IonButton } from '@ionic/react'; export const PopoverExample: React.FC = () => { return ( <> {/* Default */} <IonPopover isOpen={true}> <IonContent>Popover Content</IonContent> </IonPopover> {/* No Arrow */} <IonPopover isOpen={true} arrow={false}> <IonContent>Popover Content</IonContent> </IonPopover> {/* Use a trigger */} <IonButton id="trigger-button">Click to open popover</IonButton> <IonPopover trigger="trigger-button"> <IonContent>Popover Content</IonContent> </IonPopover> {/* Hover over trigger to open */} <IonButton id="hover-button">Hover to open popover</IonButton> <IonPopover trigger="hover-button" triggerAction="hover"> <IonContent>Popover Content</IonContent> </IonPopover> {/* Show popover above trigger */} <IonButton id="side-button">Click to open popover</IonButton> <IonPopover trigger="side-button" side="top"> <IonContent>Popover Content</IonContent> </IonPopover> {/* Align popover to end of trigger */} <IonButton id="alignment-button">Click to open popover</IonButton> <IonPopover trigger="alignment-button" side="top" alignment="end"> <IonContent>Popover Content</IonContent> </IonPopover> {/* Make popover the same size as the trigger */} <IonButton id="size-button">Click to open popover</IonButton> <IonPopover trigger="size-button" size="cover"> <IonContent>Popover Content</IonContent> </IonPopover> {/* Make popover show relative to click coordinates rather than trigger */} <IonButton id="size-button">Click to open popover</IonButton> <IonPopover trigger="size-button" reference="event"> <IonContent>Popover Content</IonContent> </IonPopover> {/* Nested Popover */} <IonButton id="nested-button">Click to open popover</IonButton> <IonPopover trigger="nested-button" dismissOnSelect={true}> <IonContent> <ion-list> <IonItem button={true} detail={false}> <IonLabel>Option 1</IonLabel> </IonItem> <IonItem button={true} detail={false}> <IonLabel>Option 2</IonLabel> </IonItem> <IonItem button={true} detail={true} id="nested-trigger"> <IonLabel>Option 3</IonLabel> </IonItem> <IonPopover trigger="nested-trigger" dismissOnSelect={true} side="end"> <IonContent> <IonItem button={true}> <IonLabel>Nested Option</IonLabel> </IonItem> </IonContent> </IonPopover> </ion-list> </IonContent> </IonPopover> </> ); }; ``` ### Inline Popover with State ```tsx import React, { useState } from 'react'; import { IonPopover, IonButton } from '@ionic/react'; export const PopoverExample: React.FC = () => { const [popoverState, setShowPopover] = useState({ showPopover: false, event: undefined }); return ( <> <IonPopover cssClass='my-custom-class' event={popoverState.event} isOpen={popoverState.showPopover} onDidDismiss={() => setShowPopover({ showPopover: false, event: undefined })} > <p>This is popover content</p> </IonPopover> <IonButton onClick={ (e: any) => { e.persist(); setShowPopover({ showPopover: true, event: e }) }} > Show Popover </IonButton> </> ); }; ``` ### useIonPopover Hook > `useIonPopover` requires being a descendant of `<IonApp>`. If you need to use a popover outside of an `<IonApp>`, consider using the component method instead. ```tsx import React from 'react'; import { IonButton, IonContent, IonItem, IonList, IonListHeader, IonPage, useIonPopover, } from '@ionic/react'; const PopoverList: React.FC<{ onHide: () => void; }> = ({ onHide }) => ( <IonList> <IonListHeader>Ionic</IonListHeader> <IonItem button>Learn Ionic</IonItem> <IonItem button>Documentation</IonItem> <IonItem button>Showcase</IonItem> <IonItem button>GitHub Repo</IonItem> <IonItem lines="none" detail={false} button onClick={onHide}> Close </IonItem> </IonList> ); const PopoverExample: React.FC = () => { const [present, dismiss] = useIonPopover(PopoverList, { onHide: () => dismiss() }); return ( <IonPage> <IonContent> <IonButton expand="block" onClick={(e) => present({ event: e.nativeEvent, }) } > Show Popover </IonButton> </IonContent> </IonPage> ); }; ``` ### Stencil ### Inline Popover ```tsx import { Component, h } from '@stencil/core'; @Component({ tag: 'popover-example', styleUrl: 'popover-example.css' }) export class PopoverExample { render() { return [ <ion-content> {/* Default */} <ion-popover isOpen={true}> <ion-content>Popover Content</ion-content> </ion-popover> {/* No Arrow */} <ion-popover isOpen={true} arrow={false}> <ion-content>Popover Content</ion-content> </ion-popover> {/* Use a trigger */} <ion-button id="trigger-button">Click to open popover</ion-button> <ion-popover trigger="trigger-button"> <ion-content>Popover Content</ion-content> </ion-popover> {/* Hover over trigger to open */} <ion-button id="hover-button">Hover to open popover</ion-button> <ion-popover trigger="hover-button" triggerAction="hover"> <ion-content>Popover Content</ion-content> </ion-popover> {/* Show popover above trigger */} <ion-button id="side-button">Click to open popover</ion-button> <ion-popover trigger="side-button" side="top"> <ion-content>Popover Content</ion-content> </ion-popover> {/* Align popover to end of trigger */} <ion-button id="alignment-button">Click to open popover</ion-button> <ion-popover trigger="alignment-button" side="top" alignment="end"> <ion-content>Popover Content</ion-content> </ion-popover> {/* Make popover the same size as the trigger */} <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" size="cover"> <ion-content>Popover Content</ion-content> </ion-popover> {/* Make popover show relative to click coordinates rather than trigger */} <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" reference="event"> <ion-content>Popover Content</ion-content> </ion-popover> {/* Nested Popover */} <ion-button id="nested-button">Click to open popover</ion-button> <ion-popover trigger="nested-button" dismissOnSelect={true}> <ion-content> <ion-list> <ion-item button={true} detail={false}> <ion-label>Option 1</ion-label> </ion-item> <ion-item button={true} detail={false}> <ion-label>Option 2</ion-label> </ion-item> <ion-item button={true} detail={true} id="nested-trigger"> <ion-label>Option 3</ion-label> </ion-item> <ion-popover trigger="nested-trigger" dismissOnSelect={true} side="end"> <ion-content> <ion-item button={true}> <ion-label>Nested Option</ion-label> </ion-item> </ion-content> </ion-popover> </ion-list> </ion-content> </ion-popover> </ion-content> ]; } } ``` ```tsx import { Component, h } from '@stencil/core'; @Component({ tag: 'page-popover', styleUrl: 'page-popover.css', }) export class PagePopover { render() { return [ <ion-list> <ion-item> <ion-label>Documentation</ion-label> </ion-item> <ion-item> <ion-label>Feedback</ion-label> </ion-item> <ion-item> <ion-label>Settings</ion-label> </ion-item> </ion-list> ]; } } ``` ### Popover Controller ```tsx import { Component, h } from '@stencil/core'; import { popoverController } from '@ionic/core'; @Component({ tag: 'popover-example', styleUrl: 'popover-example.css' }) export class PopoverExample { async presentPopover(ev: any) { const popover = await popoverController.create({ component: 'page-popover', cssClass: 'my-custom-class', event: ev, translucent: true }); await popover.present(); const { role } = await popover.onDidDismiss(); console.log('onDidDismiss resolved with role', role); } render() { return [ <ion-content> <ion-button onClick={(ev) => this.presentPopover(ev)}>Present Popover</ion-button> </ion-content> ]; } } ``` ```tsx import { Component, h } from '@stencil/core'; @Component({ tag: 'page-popover', styleUrl: 'page-popover.css', }) export class PagePopover { render() { return [ <ion-list> <ion-item> <ion-label>Documentation</ion-label> </ion-item> <ion-item> <ion-label>Feedback</ion-label> </ion-item> <ion-item> <ion-label>Settings</ion-label> </ion-item> </ion-list> ]; } } ``` ### Vue ### Inline Popover ```html <template> <!-- Default --> <ion-popover :is-open="true"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- No Arrow --> <ion-popover :is-open="true" :arrow="false"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Use a trigger --> <ion-button id="trigger-button">Click to open popover</ion-button> <ion-popover trigger="trigger-button"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Hover over trigger to open --> <ion-button id="hover-button">Hover to open popover</ion-button> <ion-popover trigger="hover-button" trigger-action="hover"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Show popover above trigger --> <ion-button id="side-button">Click to open popover</ion-button> <ion-popover trigger="side-button" side="top"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Align popover to end of trigger --> <ion-button id="alignment-button">Click to open popover</ion-button> <ion-popover trigger="alignment-button" side="top" alignment="end"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Make popover the same size as the trigger --> <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" size="cover"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Make popover show relative to click coordinates rather than trigger --> <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" reference="event"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Nested Popover --> <ion-button id="nested-button">Click to open popover</ion-button> <ion-popover trigger="nested-button" :dismiss-on-select="true"> <ion-content> <ion-list> <ion-item :button="true" :detail="false"> <ion-label>Option 1</ion-label> </ion-item> <ion-item :button="true" :detail="false"> <ion-label>Option 2</ion-label> </ion-item> <ion-item :button="true" :detail="true" id="nested-trigger"> <ion-label>Option 3</ion-label> </ion-item> <ion-popover trigger="nested-trigger" :dismiss-on-select="true" side="end"> <ion-content> <ion-item :button="true"> <ion-label>Nested Option</ion-label> </ion-item> </ion-content> </ion-popover> </ion-list> </ion-content> </ion-popover> </template> <script> import { IonButton, IonContent, IonItem, IonLabel, IonPopover } from '@ionic/vue'; import { defineComponent } from 'vue'; export default defineComponent({ components: { IonButton, IonContent, IonItem, IonLabel, IonPopover } }); </script> ``` ### Inline Popover with State ```html <template> <ion-button @click="setOpen(true, $event)">Show Popover</ion-button> <ion-popover :is-open="isOpenRef" css-class="my-custom-class" :event="event" :translucent="true" @didDismiss="setOpen(false)" > <Popover></Popover> </ion-popover> </template> <script> import { IonButton, IonPopover } from '@ionic/vue'; import { defineComponent, ref } from 'vue'; import Popover from './popover.vue'; export default defineComponent({ components: { IonButton, IonPopover, Popover }, setup() { const isOpenRef = ref(false); const event = ref(); const setOpen = (state: boolean, ev?: Event) => { event.value = ev; isOpenRef.value = state; } return { isOpenRef, setOpen, event } } }); </script> ``` ### Popover Controller ```html <template> <ion-content class="ion-padding"> Popover Content </ion-content> </template> <script> import { IonContent } from '@ionic/vue'; import { defineComponent } from 'vue'; export default defineComponent({ name: 'Popover', components: { IonContent } }); </script> ``` ```html <template> <ion-page> <ion-content class="ion-padding"> <ion-button @click="openPopover">Open Popover</ion-button> </ion-content> </ion-page> </template> <script> import { IonButton, IonContent, IonPage, popoverController } from '@ionic/vue'; import Popover from './popover.vue'; export default { components: { IonButton, IonContent, IonPage }, methods: { async openPopover(ev: Event) { const popover = await popoverController .create({ component: Popover, cssClass: 'my-custom-class', event: ev, translucent: true }) await popover.present(); const { role } = await popover.onDidDismiss(); console.log('onDidDismiss resolved with role', role); }, }, } </script> ``` ## Properties | Property | Attribute | Description | Type | Default | | ----------------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | ----------- | | `alignment` | `alignment` | Describes how to align the popover content with the `reference` point. Defaults to `'center'` for `ios` mode, and `'start'` for `md` mode. | `"center" \| "end" \| "start" \| undefined` | `undefined` | | `animated` | `animated` | If `true`, the popover will animate. | `boolean` | `true` | | `arrow` | `arrow` | If `true`, the popover will display an arrow that points at the `reference` when running in `ios` mode on mobile. Does not apply in `md` mode or on desktop. | `boolean` | `true` | | `backdropDismiss` | `backdrop-dismiss` | If `true`, the popover will be dismissed when the backdrop is clicked. | `boolean` | `true` | | `component` | `component` | The component to display inside of the popover. You only need to use this if you are not using a JavaScript framework. Otherwise, you can just slot your component inside of `ion-popover`. | `Function \| HTMLElement \| null \| string \| undefined` | `undefined` | | `componentProps` | -- | The data to pass to the popover component. You only need to use this if you are not using a JavaScript framework. Otherwise, you can just set the props directly on your component. | `undefined \| { [key: string]: any; }` | `undefined` | | `dismissOnSelect` | `dismiss-on-select` | If `true`, the popover will be automatically dismissed when the content has been clicked. | `boolean` | `false` | | `enterAnimation` | -- | Animation to use when the popover is presented. | `((baseEl: any, opts?: any) => Animation) \| undefined` | `undefined` | | `event` | `event` | The event to pass to the popover animation. | `any` | `undefined` | | `htmlAttributes` | -- | Additional attributes to pass to the popover. | `PopoverAttributes \| undefined` | `undefined` | | `isOpen` | `is-open` | If `true`, the popover will open. If `false`, the popover will close. Use this if you need finer grained control over presentation, otherwise just use the popoverController or the `trigger` property. Note: `isOpen` will not automatically be set back to `false` when the popover dismisses. You will need to do that in your code. | `boolean` | `false` | | `keyboardClose` | `keyboard-close` | If `true`, the keyboard will be automatically dismissed when the overlay is presented. | `boolean` | `true` | | `leaveAnimation` | -- | Animation to use when the popover is dismissed. | `((baseEl: any, opts?: any) => Animation) \| undefined` | `undefined` | | `mode` | `mode` | The mode determines which platform styles to use. | `"ios" \| "md"` | `undefined` | | `reference` | `reference` | Describes what to position the popover relative to. If `'trigger'`, the popover will be positioned relative to the trigger button. If passing in an event, this is determined via event.target. If `'event'`, the popover will be positioned relative to the x/y coordinates of the trigger action. If passing in an event, this is determined via event.clientX and event.clientY. | `"event" \| "trigger"` | `'trigger'` | | `showBackdrop` | `show-backdrop` | If `true`, a backdrop will be displayed behind the popover. | `boolean` | `true` | | `side` | `side` | Describes which side of the `reference` point to position the popover on. The `'start'` and `'end'` values are RTL-aware, and the `'left'` and `'right'` values are not. | `"bottom" \| "end" \| "left" \| "right" \| "start" \| "top"` | `'bottom'` | | `size` | `size` | Describes how to calculate the popover width. If `'cover'`, the popover width will match the width of the trigger. If `'auto'`, the popover width will be determined by the content in the popover. | `"auto" \| "cover"` | `'auto'` | | `translucent` | `translucent` | If `true`, the popover will be translucent. Only applies when the mode is `"ios"` and the device supports [`backdrop-filter`](https://developer.mozilla.org/en-US/docs/Web/CSS/backdrop-filter#Browser_compatibility). | `boolean` | `false` | | `trigger` | `trigger` | An ID corresponding to the trigger element that causes the popover to open. Use the `trigger-action` property to customize the interaction that results in the popover opening. | `string \| undefined` | `undefined` | | `triggerAction` | `trigger-action` | Describes what kind of interaction with the trigger that should cause the popover to open. Does not apply when the `trigger` property is `undefined`. If `'click'`, the popover will be presented when the trigger is left clicked. If `'hover'`, the popover will be presented when a pointer hovers over the trigger. If `'context-menu'`, the popover will be presented when the trigger is right clicked on desktop and long pressed on mobile. This will also prevent your device's normal context menu from appearing. | `"click" \| "context-menu" \| "hover"` | `'click'` | ## Events | Event | Description | Type | | ----------------------- | ------------------------------------------------------------------------------ | -------------------------------------- | | `didDismiss` | Emitted after the popover has dismissed. Shorthand for ionPopoverDidDismiss. | `CustomEvent<OverlayEventDetail<any>>` | | `didPresent` | Emitted after the popover has presented. Shorthand for ionPopoverWillDismiss. | `CustomEvent<void>` | | `ionPopoverDidDismiss` | Emitted after the popover has dismissed. | `CustomEvent<OverlayEventDetail<any>>` | | `ionPopoverDidPresent` | Emitted after the popover has presented. | `CustomEvent<void>` | | `ionPopoverWillDismiss` | Emitted before the popover has dismissed. | `CustomEvent<OverlayEventDetail<any>>` | | `ionPopoverWillPresent` | Emitted before the popover has presented. | `CustomEvent<void>` | | `willDismiss` | Emitted before the popover has dismissed. Shorthand for ionPopoverWillDismiss. | `CustomEvent<OverlayEventDetail<any>>` | | `willPresent` | Emitted before the popover has presented. Shorthand for ionPopoverWillPresent. | `CustomEvent<void>` | ## Methods ### `dismiss(data?: any, role?: string | undefined, dismissParentPopover?: boolean) => Promise<boolean>` Dismiss the popover overlay after it has been presented. #### Returns Type: `Promise<boolean>` ### `onDidDismiss<T = any>() => Promise<OverlayEventDetail<T>>` Returns a promise that resolves when the popover did dismiss. #### Returns Type: `Promise<OverlayEventDetail<T>>` ### `onWillDismiss<T = any>() => Promise<OverlayEventDetail<T>>` Returns a promise that resolves when the popover will dismiss. #### Returns Type: `Promise<OverlayEventDetail<T>>` ### `present(event?: MouseEvent | TouchEvent | PointerEvent | CustomEvent<any> | undefined) => Promise<void>` Present the popover overlay after it has been created. Developers can pass a mouse, touch, or pointer event to position the popover relative to where that event was dispatched. #### Returns Type: `Promise<void>` ## Slots | Slot | Description | | ---- | ----------------------------------------------------------- | | | Content is placed inside of the `.popover-content` element. | ## Shadow Parts | Part | Description | | ------------ | --------------------------------------------------------------------------- | | `"arrow"` | The arrow that points to the reference element. Only applies on `ios` mode. | | `"backdrop"` | The `ion-backdrop` element. | | `"content"` | The wrapper element for the default slot. | ## CSS Custom Properties | Name | Description | | -------------------- | ----------------------------------------------- | | `--backdrop-opacity` | Opacity of the backdrop | | `--background` | Background of the popover | | `--box-shadow` | Box shadow of the popover | | `--height` | Height of the popover | | `--max-height` | Maximum height of the popover | | `--max-width` | Maximum width of the popover | | `--min-height` | Minimum height of the popover | | `--min-width` | Minimum width of the popover | | `--offset-x` | The amount to move the popover by on the x-axis | | `--offset-y` | The amount to move the popover by on the y-axis | | `--width` | Width of the popover | ## Dependencies ### Used by - [ion-datetime](../datetime) ### Depends on - [ion-backdrop](../backdrop) ### Graph ```mermaid graph TD; ion-popover --> ion-backdrop ion-datetime --> ion-popover style ion-popover fill:#f9f,stroke:#333,stroke-width:4px ``` ---------------------------------------------- *Built with [StencilJS](https://stenciljs.com/)*
core/src/components/popover/readme.md
1
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.030745716765522957, 0.0007034431910142303, 0.00015907199122011662, 0.00017230439698323607, 0.0029979448299854994 ]
{ "id": 1, "code_window": [ " ion-action-sheet --> ion-backdrop\n", " ion-action-sheet --> ion-icon\n", " ion-action-sheet --> ion-ripple-effect\n", " style ion-action-sheet fill:#f9f,stroke:#333,stroke-width:4px\n", "```\n", "\n", "----------------------------------------------\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " ion-select --> ion-action-sheet\n" ], "file_path": "core/src/components/action-sheet/readme.md", "type": "add", "edit_start_line_idx": 675 }
import type { JSX } from '@ionic/core/components'; import { IonBreadcrumb as IonBreadcrumbCmp } from '@ionic/core/components/ion-breadcrumb.js'; import { IonButton as IonButtonCmp } from '@ionic/core/components/ion-button.js'; import { IonCard as IonCardCmp } from '@ionic/core/components/ion-card.js'; import { IonFabButton as IonFabButtonCmp } from '@ionic/core/components/ion-fab-button.js'; import { IonItemOption as IonItemOptionCmp } from '@ionic/core/components/ion-item-option.js'; import { IonItem as IonItemCmp } from '@ionic/core/components/ion-item.js'; import { IonRouterLink as IonRouterLinkCmp } from '@ionic/core/components/ion-router-link.js'; import { createRoutingComponent } from './createRoutingComponent'; import { HrefProps } from './hrefprops'; export const IonRouterLink = /*@__PURE__*/ createRoutingComponent< HrefProps<JSX.IonRouterLink>, HTMLIonRouterLinkElement >('ion-router-link', IonRouterLinkCmp); export const IonButton = /*@__PURE__*/ createRoutingComponent< HrefProps<JSX.IonButton>, HTMLIonButtonElement >('ion-button', IonButtonCmp); export const IonCard = /*@__PURE__*/ createRoutingComponent< HrefProps<JSX.IonCard>, HTMLIonCardElement >('ion-card', IonCardCmp); export const IonFabButton = /*@__PURE__*/ createRoutingComponent< HrefProps<JSX.IonFabButton>, HTMLIonFabButtonElement >('ion-fab-button', IonFabButtonCmp); export const IonItem = /*@__PURE__*/ createRoutingComponent< HrefProps<JSX.IonItem>, HTMLIonItemElement >('ion-item', IonItemCmp); export const IonItemOption = /*@__PURE__*/ createRoutingComponent< HrefProps<JSX.IonItemOption>, HTMLIonItemOptionElement >('ion-item-option', IonItemOptionCmp); export const IonBreadcrumb = /*@__PURE__*/ createRoutingComponent< HrefProps<JSX.IonBreadcrumb>, HTMLIonBreadcrumbElement >('ion-breadcrumb', IonBreadcrumbCmp);
packages/react/src/components/routing-proxies.ts
0
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.0002143734454875812, 0.0001781763567123562, 0.00016731848882045597, 0.0001686427858658135, 0.000018163691493100487 ]